@theholocron/holocron-plugin-github 5.0.0-alpha.501 → 5.0.0-alpha.503

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,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import { AuthError, MissingTokenError, ProviderApiError, connectionProbe, createFeatureResolver, pickByCreation, readKeysLimited, reportProgress, tokenExpectations } from "@theholocron/cli";
2
+ import { AuthError, MissingTokenError, ProviderApiError, areaLabelsForFiles, areaLabelsForTitle, connectionProbe, createFeatureResolver, pickByCreation, readKeysLimited, reportProgress, tokenExpectations } from "@theholocron/cli";
3
3
  import { createGitHubClient, createGitHubClient as createGitHubClient$1 } from "@theholocron/github-client";
4
4
  import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
5
5
  import { dirname, join } from "node:path";
@@ -151,15 +151,21 @@ var GitHubEnvironments = class {
151
151
  }));
152
152
  }
153
153
  };
154
- // src/capabilities/issue-priority.ts
155
- const OPTION_NAMES = {
156
- urgent: "Urgent",
157
- high: "High",
158
- medium: "Medium",
159
- low: "Low"
160
- };
154
+ // src/capabilities/issue-field-setter.ts
155
+ /**
156
+ * Sets and clears one organization issue field (Priority, Effort, Start date, Target date) on an issue, for the
157
+ * `issues` capability's `create` and `update` and for `createPrioritySetter()`.
158
+ *
159
+ * The field list is read once per setter. A value is added with `POST`, which leaves the issue's other field values
160
+ * alone (`PUT` replaces all of them, and a multi-select value cannot be sent back with certainty); a value that differs
161
+ * is removed first. A missing field, a missing option or a refusal from GitHub (401, 403, 404, 422) comes back as a
162
+ * `note` for the caller's `dropped` list; a rate limit and every other failure are thrown. Spec
163
+ * `tech-github-issue-priority-field`, #2253, and `tool-work-commands`, #2429.
164
+ *
165
+ * Not verified against the live API: that Effort, Start date and Target date are written the way Priority is.
166
+ */
161
167
  /** Whether GitHub refused for a reason about access or setup, which a run reports and goes on from. */
162
- function refusal(err) {
168
+ function fieldRefusal(err) {
163
169
  if (!(err instanceof ProviderApiError)) return void 0;
164
170
  if (err.status === void 0 || ![
165
171
  401,
@@ -170,50 +176,108 @@ function refusal(err) {
170
176
  if (/rate limit/i.test(`${err.message} ${String(err.details)}`)) return void 0;
171
177
  return `GitHub refused: ${err.status}`;
172
178
  }
173
- function createPrioritySetter(client, repo) {
179
+ const DATA_TYPE = {
180
+ select: "single_select",
181
+ date: "date"
182
+ };
183
+ /** Makes the setter for the issues of `repo` (`owner/name`); the organization's field list is read on first use and kept. */
184
+ function createFieldSetter(client, repo) {
174
185
  const org = repo.split("/")[0];
175
- let lookup;
176
- const findField = () => lookup ??= client.issueFields.list(org).then((fields) => {
177
- const field = fields.find((f) => f.name === "Priority" && f.data_type === "single_select");
178
- return field ? { field } : { note: `priority field (${org} has no Priority issue field)` };
179
- }, (err) => {
180
- const why = refusal(err);
186
+ let fields;
187
+ const listFields = () => fields ??= client.issueFields.list(org).then((list) => list, (err) => {
188
+ const why = fieldRefusal(err);
181
189
  if (why === void 0) throw err;
182
- return { note: `priority field (${why})` };
190
+ return why;
183
191
  });
184
- return { async set(number, level, flags = {}) {
185
- if (!level || level === "none") return { changed: false };
186
- const found = await findField();
187
- if ("note" in found) return {
188
- changed: false,
189
- note: found.note
190
- };
191
- const { field } = found;
192
- const optionName = OPTION_NAMES[level];
193
- const option = field.options?.find((o) => o.name.toLowerCase() === optionName.toLowerCase());
194
- if (!option) return {
195
- changed: false,
196
- note: `priority field (no "${optionName}" option)`
197
- };
198
- try {
199
- const current = flags.isNew ? void 0 : (await client.issueFields.values(repo, number)).find((v) => v.issue_field_id === field.id);
200
- if ((current ? current.single_select_option?.name ?? String(current.value) : void 0)?.toLowerCase() === option.name.toLowerCase()) return { changed: false };
201
- if (flags.dryRun) return { changed: true };
202
- if (current) await client.issueFields.deleteValue(repo, number, field.id);
203
- await client.issueFields.addValues(repo, number, [{
204
- field_id: field.id,
205
- value: option.name
206
- }]);
207
- return { changed: true };
208
- } catch (err) {
209
- const why = refusal(err);
210
- if (why === void 0) throw err;
211
- return {
192
+ const label = (target) => `${target.name.toLowerCase()} field`;
193
+ const find = async (target) => {
194
+ const list = await listFields();
195
+ if (typeof list === "string") return { note: `${label(target)} (${list})` };
196
+ const field = list.find((f) => f.name.toLowerCase() === target.name.toLowerCase() && f.data_type === DATA_TYPE[target.type]);
197
+ return field ? { field } : { note: `${label(target)} (${org} has no ${target.name} issue field)` };
198
+ };
199
+ const currentOf = async (number, field, target, flags) => {
200
+ if (flags.isNew) return void 0;
201
+ const found = (await client.issueFields.values(repo, number)).find((v) => v.issue_field_id === field.id);
202
+ if (!found) return void 0;
203
+ return target.type === "date" ? String(found.value).slice(0, 10) : found.single_select_option?.name ?? String(found.value);
204
+ };
205
+ return {
206
+ async set(number, target, flags = {}) {
207
+ if (!target.value) return { changed: false };
208
+ const found = await find(target);
209
+ if ("note" in found) return {
212
210
  changed: false,
213
- note: `priority field (${why})`
211
+ note: found.note
214
212
  };
213
+ const { field } = found;
214
+ let value = target.value;
215
+ if (target.type === "select") {
216
+ const option = field.options?.find((o) => o.name.toLowerCase() === value.toLowerCase());
217
+ if (!option) return {
218
+ changed: false,
219
+ note: `${label(target)} (no "${value}" option)`
220
+ };
221
+ value = option.name;
222
+ }
223
+ try {
224
+ const current = await currentOf(number, field, target, flags);
225
+ if (current?.toLowerCase() === value.toLowerCase()) return { changed: false };
226
+ if (flags.dryRun) return { changed: true };
227
+ if (current !== void 0) await client.issueFields.deleteValue(repo, number, field.id);
228
+ await client.issueFields.addValues(repo, number, [{
229
+ field_id: field.id,
230
+ value
231
+ }]);
232
+ return { changed: true };
233
+ } catch (err) {
234
+ const why = fieldRefusal(err);
235
+ if (why === void 0) throw err;
236
+ return {
237
+ changed: false,
238
+ note: `${label(target)} (${why})`
239
+ };
240
+ }
241
+ },
242
+ async clear(number, target, flags = {}) {
243
+ if (flags.isNew) return { changed: false };
244
+ const found = await find(target);
245
+ if ("note" in found) return {
246
+ changed: false,
247
+ note: found.note
248
+ };
249
+ try {
250
+ if (await currentOf(number, found.field, target, flags) === void 0) return { changed: false };
251
+ if (flags.dryRun) return { changed: true };
252
+ await client.issueFields.deleteValue(repo, number, found.field.id);
253
+ return { changed: true };
254
+ } catch (err) {
255
+ const why = fieldRefusal(err);
256
+ if (why === void 0) throw err;
257
+ return {
258
+ changed: false,
259
+ note: `${label(target)} (${why})`
260
+ };
261
+ }
215
262
  }
216
- } };
263
+ };
264
+ }
265
+ // src/capabilities/issue-priority.ts
266
+ /** The Priority field's option for each level. */
267
+ const PRIORITY_OPTION_NAMES = {
268
+ urgent: "Urgent",
269
+ high: "High",
270
+ medium: "Medium",
271
+ low: "Low"
272
+ };
273
+ /** Makes the Priority setter for the issues of `repo` (`owner/name`). */
274
+ function createPrioritySetter(client, repo) {
275
+ const fields = createFieldSetter(client, repo);
276
+ return { set: (number, level, flags = {}) => !level || level === "none" ? Promise.resolve({ changed: false }) : fields.set(number, {
277
+ name: "Priority",
278
+ type: "select",
279
+ value: PRIORITY_OPTION_NAMES[level]
280
+ }, flags) };
217
281
  }
218
282
  // src/capabilities/issues-migration.ts
219
283
  /**
@@ -561,6 +625,215 @@ async function update(client, repo, issue, record, options, priority) {
561
625
  dropped: [...droppedFor(record), ...field.note ? [field.note] : []]
562
626
  };
563
627
  }
628
+ // src/capabilities/issues-update.ts
629
+ const KIND_NAMES = {
630
+ bug: "Bug",
631
+ feature: "Feature",
632
+ task: "Task"
633
+ };
634
+ const EFFORT_NAMES = {
635
+ high: "High",
636
+ medium: "Medium",
637
+ low: "Low"
638
+ };
639
+ /** Runs one step; a refusal or a bad key is a `dropped` line, anything else (a rate limit) is thrown. */
640
+ async function guarded(what, out, step) {
641
+ try {
642
+ await step();
643
+ } catch (err) {
644
+ const why = fieldRefusal(err);
645
+ if (why !== void 0) out.dropped.push(`${what} (${why})`);
646
+ else if (!(err instanceof ProviderApiError)) out.dropped.push(`${what} (${err.message})`);
647
+ else throw err;
648
+ }
649
+ }
650
+ const CLEAR_FIELD = {
651
+ priority: {
652
+ name: "Priority",
653
+ type: "select"
654
+ },
655
+ effort: {
656
+ name: "Effort",
657
+ type: "select"
658
+ },
659
+ startDate: {
660
+ name: "Start date",
661
+ type: "date"
662
+ },
663
+ targetDate: {
664
+ name: "Target date",
665
+ type: "date"
666
+ }
667
+ };
668
+ /**
669
+ * Writes the {@link IssueFields} of an issue, and clears and unblocks as `clear` and `unblock` ask. `issue` is the issue
670
+ * as it is now (its numeric id and Type); `isNew` says it was just made, so nothing is read to compare.
671
+ */
672
+ async function applyIssueFields(ctx, issue, input, isNew) {
673
+ const { client, repo } = ctx;
674
+ const fields = ctx.fields ??= createFieldSetter(client, repo);
675
+ const out = {
676
+ changed: [],
677
+ dropped: []
678
+ };
679
+ const flags = { isNew };
680
+ const clear = new Set(input.clear ?? []);
681
+ if (input.kind) {
682
+ const name = KIND_NAMES[input.kind];
683
+ if (issue.type?.name?.toLowerCase() !== name.toLowerCase()) await guarded(`kind ${name}`, out, async () => {
684
+ await client.issues.updateIssue(repo, issue.number, { type: name });
685
+ out.changed.push(`kind: ${name}`);
686
+ });
687
+ } else if (clear.has("kind") && issue.type) await guarded("kind", out, async () => {
688
+ await client.issues.updateIssue(repo, issue.number, { type: null });
689
+ out.changed.push("kind cleared");
690
+ });
691
+ const values = [
692
+ [
693
+ "priority",
694
+ "Priority",
695
+ "select",
696
+ input.priority && input.priority !== "none" ? PRIORITY_OPTION_NAMES[input.priority] : void 0
697
+ ],
698
+ [
699
+ "effort",
700
+ "Effort",
701
+ "select",
702
+ input.effort ? EFFORT_NAMES[input.effort] : void 0
703
+ ],
704
+ [
705
+ "startDate",
706
+ "Start date",
707
+ "date",
708
+ input.startDate
709
+ ],
710
+ [
711
+ "targetDate",
712
+ "Target date",
713
+ "date",
714
+ input.targetDate
715
+ ]
716
+ ];
717
+ for (const [label, name, type, value] of values) {
718
+ if (!value) continue;
719
+ const result = await fields.set(issue.number, {
720
+ name,
721
+ type,
722
+ value
723
+ }, flags);
724
+ if (result.note) out.dropped.push(result.note);
725
+ else if (result.changed) out.changed.push(`${label}: ${value}`);
726
+ }
727
+ for (const key of clear) {
728
+ const target = CLEAR_FIELD[key];
729
+ if (!target) continue;
730
+ const result = await fields.clear(issue.number, target, flags);
731
+ if (result.note) out.dropped.push(result.note);
732
+ else if (result.changed) out.changed.push(`${key} cleared`);
733
+ }
734
+ if (input.parent) {
735
+ const parentKey = input.parent;
736
+ await guarded(`parent ${parentKey}`, out, async () => {
737
+ const parentNumber = ctx.parseKey(parentKey);
738
+ const current = isNew ? null : await client.issues.getParent(repo, issue.number);
739
+ if (current?.number === parentNumber) return;
740
+ await client.issues.addSubIssue(repo, parentNumber, issue.id, current !== null);
741
+ out.changed.push(`parent: ${parentKey}`);
742
+ });
743
+ } else if (clear.has("parent") && !isNew) await guarded("parent", out, async () => {
744
+ const current = await client.issues.getParent(repo, issue.number);
745
+ if (!current) return;
746
+ await client.issues.removeSubIssue(repo, current.number, issue.id);
747
+ out.changed.push("parent cleared");
748
+ });
749
+ const adds = input.blockedBy ?? [];
750
+ const removes = input.unblock ?? [];
751
+ if (adds.length > 0 || removes.length > 0) {
752
+ let blockers;
753
+ const current = async () => blockers ??= isNew ? [] : await client.issues.listBlockedBy(repo, issue.number);
754
+ for (const key of adds) await guarded(`blocked by ${key}`, out, async () => {
755
+ const number = ctx.parseKey(key);
756
+ if ((await current()).some((b) => b.number === number)) return;
757
+ const blocker = await client.issues.getIssue(repo, number);
758
+ await client.issues.addBlockedBy(repo, issue.number, blocker.id);
759
+ out.changed.push(`blocked by: ${key}`);
760
+ });
761
+ for (const key of removes) await guarded(`unblock ${key}`, out, async () => {
762
+ const number = ctx.parseKey(key);
763
+ const blocker = (await current()).find((b) => b.number === number);
764
+ if (!blocker) return;
765
+ await client.issues.removeBlockedBy(repo, issue.number, blocker.id);
766
+ out.changed.push(`unblocked: ${key}`);
767
+ });
768
+ }
769
+ return out;
770
+ }
771
+ const sameSet = (a, b) => a.length === b.length && a.every((x) => b.includes(x));
772
+ /** Changes an issue to match the patch; whatever is already as asked is not written. */
773
+ async function updateGitHubIssue(ctx, key, patch) {
774
+ const { client, repo } = ctx;
775
+ const number = ctx.parseKey(key);
776
+ const issue = await client.issues.getIssue(repo, number);
777
+ const changed = [];
778
+ const clear = new Set(patch.clear ?? []);
779
+ const body = {};
780
+ if (patch.title !== void 0 && patch.title !== issue.title) {
781
+ body.title = patch.title;
782
+ changed.push("title");
783
+ }
784
+ if (patch.body !== void 0 && patch.body !== (issue.body ?? "")) {
785
+ body.body = patch.body;
786
+ changed.push("body");
787
+ }
788
+ if (patch.state && patch.state !== issue.state) {
789
+ body.state = patch.state;
790
+ if (patch.state === "closed") body.state_reason = patch.stateReason ?? "completed";
791
+ changed.push(`state: ${patch.state}`);
792
+ }
793
+ const have = (issue.assignees ?? (issue.assignee ? [issue.assignee] : [])).map((a) => a.login);
794
+ if (patch.assignees?.length) {
795
+ const isMe = (a) => /^@?me$/i.test(a);
796
+ const me = patch.assignees.some(isMe) ? await ctx.myLogin() : void 0;
797
+ const want = [...new Set(patch.assignees.map((a) => isMe(a) && me ? me : a.replace(/^@/, "")))];
798
+ if (!sameSet(want.map((a) => a.toLowerCase()), have.map((a) => a.toLowerCase()))) {
799
+ body.assignees = want;
800
+ changed.push(`assignees: ${want.join(", ")}`);
801
+ }
802
+ } else if (clear.has("assignees") && have.length > 0) {
803
+ body.assignees = [];
804
+ changed.push("assignees cleared");
805
+ }
806
+ if (patch.milestone) {
807
+ const milestone = await ctx.resolveMilestone(patch.milestone);
808
+ if (issue.milestone?.number !== milestone) {
809
+ body.milestone = milestone;
810
+ changed.push(`milestone: ${patch.milestone}`);
811
+ }
812
+ } else if (clear.has("milestone") && issue.milestone) {
813
+ body.milestone = null;
814
+ changed.push("milestone cleared");
815
+ }
816
+ if (Object.keys(body).length > 0) await client.issues.updateIssue(repo, number, body);
817
+ const labels = new Set(issue.labels.map((l) => l.name.toLowerCase()));
818
+ const add = [...new Set(patch.addLabels ?? [])].filter((l) => !labels.has(l.toLowerCase()));
819
+ if (add.length > 0) {
820
+ await client.issues.addLabels(repo, number, add);
821
+ changed.push(`labels added: ${add.join(", ")}`);
822
+ }
823
+ for (const label of new Set(patch.removeLabels ?? [])) {
824
+ if (!labels.has(label.toLowerCase())) continue;
825
+ const exact = issue.labels.find((l) => l.name.toLowerCase() === label.toLowerCase()).name;
826
+ await client.issues.removeLabel(repo, number, exact);
827
+ changed.push(`label removed: ${exact}`);
828
+ }
829
+ const fields = await applyIssueFields(ctx, issue, patch, false);
830
+ const all = [...changed, ...fields.changed];
831
+ return {
832
+ key: `#${number}`,
833
+ changed: all,
834
+ ...fields.dropped.length > 0 ? { dropped: fields.dropped } : {}
835
+ };
836
+ }
564
837
  // src/capabilities/issues.ts
565
838
  /** Issues read per request when `search` has a `text`; GitHub's largest page. */
566
839
  const TEXT_PAGE_SIZE = 100;
@@ -655,7 +928,11 @@ var GitHubIssues = class {
655
928
  const raw = await this.client.issues.getIssue(this.repo, number);
656
929
  return this.mapIssue(raw);
657
930
  }
658
- /** Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. */
931
+ /**
932
+ * Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. Type, Priority,
933
+ * Effort, the dates, the parent and the blockers are set after the issue exists; what GitHub refuses of them comes
934
+ * back in `dropped`, never as a failure, because the issue is made by then and its key must not be lost.
935
+ */
659
936
  async create(input) {
660
937
  const body = { title: input.summary };
661
938
  if (input.assignees?.length) {
@@ -666,7 +943,24 @@ var GitHubIssues = class {
666
943
  if (input.body) body.body = input.body;
667
944
  if (input.labels?.length) body.labels = input.labels;
668
945
  if (input.milestone) body.milestone = await this.resolveMilestone(input.milestone);
669
- return { key: `#${(await this.client.issues.createIssue(this.repo, body)).number}` };
946
+ const raw = await this.client.issues.createIssue(this.repo, body);
947
+ const key = `#${raw.number}`;
948
+ const fields = await applyIssueFields(this.fieldContext(), raw, input, true).catch((err) => ({
949
+ changed: [],
950
+ dropped: [`fields (not set: ${err.message})`]
951
+ }));
952
+ return {
953
+ key,
954
+ ...fields.dropped.length > 0 ? { dropped: fields.dropped } : {}
955
+ };
956
+ }
957
+ /** Changes an issue; see {@link updateGitHubIssue}. */
958
+ update(key, patch) {
959
+ return updateGitHubIssue({
960
+ ...this.fieldContext(),
961
+ myLogin: async () => (await this.getMyself()).id,
962
+ resolveMilestone: (ref) => this.resolveMilestone(ref)
963
+ }, key, patch);
670
964
  }
671
965
  async transition(key, slot) {
672
966
  const number = parseIssueNumber(key, this.owner, this.repoName);
@@ -794,6 +1088,17 @@ var GitHubIssues = class {
794
1088
  sync(records, options) {
795
1089
  return syncIssues(this.client, this.repo, records, options);
796
1090
  }
1091
+ fieldSetter;
1092
+ /** What the field writers need; the setter is shared so the organization's field list is read once. */
1093
+ fieldContext() {
1094
+ this.fieldSetter ??= createFieldSetter(this.client, this.repo);
1095
+ return {
1096
+ client: this.client,
1097
+ repo: this.repo,
1098
+ parseKey: (k) => parseIssueNumber(k, this.owner, this.repoName),
1099
+ fields: this.fieldSetter
1100
+ };
1101
+ }
797
1102
  async resolveMilestone(ref) {
798
1103
  if (/^\d+$/.test(ref)) return parseInt(ref, 10);
799
1104
  const match = (await this.client.issues.listMilestones(this.repo, { state: "all" })).find((m) => m.title.toLowerCase() === ref.toLowerCase());
@@ -855,7 +1160,7 @@ const CLOSING_QUERY = `query($id: ID!) { node(id: $id) { ... on Issue {
855
1160
  } } } } }
856
1161
  } }
857
1162
  } } }`;
858
- const FAILED = /* @__PURE__ */ new Set([
1163
+ const FAILED$1 = /* @__PURE__ */ new Set([
859
1164
  "FAILURE",
860
1165
  "TIMED_OUT",
861
1166
  "STARTUP_FAILURE",
@@ -872,7 +1177,7 @@ function aggregateChecks(runs) {
872
1177
  if (!newest) return "none";
873
1178
  if (newest.status !== "COMPLETED") return "pending";
874
1179
  if (newest.conclusion === "SUCCESS") return "success";
875
- if (newest.conclusion && FAILED.has(newest.conclusion)) return "failure";
1180
+ if (newest.conclusion && FAILED$1.has(newest.conclusion)) return "failure";
876
1181
  if (newest.conclusion === "CANCELLED") return "pending";
877
1182
  return "none";
878
1183
  }
@@ -1702,6 +2007,25 @@ async function syncLabels(client, repo, canonical, stale) {
1702
2007
  }
1703
2008
  return `${created} created, ${updated} updated, ${deleted} deleted`;
1704
2009
  }
2010
+ /**
2011
+ * Make the labels a repo lacks and change nothing else: an existing label (found without regard to case) keeps its
2012
+ * colour and description, and nothing is deleted. Used for the `area:<name>` family, which is not in the canonical set.
2013
+ */
2014
+ async function ensureLabels(client, repo, labels) {
2015
+ const existing = await client.labels.listLabels(repo);
2016
+ const have = new Set(existing.map((l) => l.name.toLowerCase()));
2017
+ let created = 0;
2018
+ for (const label of labels) {
2019
+ if (have.has(label.name.toLowerCase())) continue;
2020
+ await client.labels.createLabel(repo, {
2021
+ name: label.name,
2022
+ color: label.color,
2023
+ description: label.description
2024
+ });
2025
+ created++;
2026
+ }
2027
+ return `${created} created, ${labels.length - created} already there`;
2028
+ }
1705
2029
  // src/capabilities/property-fix-hints.ts
1706
2030
  /** GitHub's wording when a custom property value is not one the organization's definition allows. */
1707
2031
  const NOT_ALLOWED = /Value '([^']+)' is not allowed for property '([^']+)'/g;
@@ -1828,6 +2152,178 @@ async function addOrgPropertyValues(client, repo, name, values, viaOrgToken = tr
1828
2152
  }
1829
2153
  return added;
1830
2154
  }
2155
+ // src/capabilities/pull-request-checks.ts
2156
+ /** The check run the aggregate `ci` workflow posts on a pull request's head commit. */
2157
+ const AGGREGATE_CHECK = "ci / Required checks";
2158
+ const FAILED = /* @__PURE__ */ new Set([
2159
+ "failure",
2160
+ "timed_out",
2161
+ "startup_failure",
2162
+ "action_required",
2163
+ "stale"
2164
+ ]);
2165
+ const newestFirst = (a, b) => (b.started_at ?? "").localeCompare(a.started_at ?? "") || b.id - a.id;
2166
+ /** The aggregate's verdict from its runs: only the newest counts; a cancelled or unfinished run is `pending`. */
2167
+ function aggregateState(runs) {
2168
+ const newest = [...runs].sort(newestFirst)[0];
2169
+ if (!newest) return "none";
2170
+ if (newest.status !== "completed") return "pending";
2171
+ if (newest.conclusion === "success") return "success";
2172
+ if (newest.conclusion && FAILED.has(newest.conclusion)) return "failure";
2173
+ if (newest.conclusion === "cancelled") return "pending";
2174
+ return "none";
2175
+ }
2176
+ /**
2177
+ * The aggregate check of a pull request's newest commit and the checks that failed on it, read now (never cached, so a
2178
+ * caller that polls sees each change). The newest run of each name counts, so a job that failed and was re-run to green
2179
+ * is not listed.
2180
+ */
2181
+ async function readPullRequestChecks(client, repo, number) {
2182
+ const sha = (await client.pulls.getPullRequest(repo, number)).head.sha;
2183
+ const runs = await client.checks.listCheckRunsForRef(repo, sha);
2184
+ const newest = /* @__PURE__ */ new Map();
2185
+ for (const run of [...runs].sort(newestFirst)) if (!newest.has(run.name)) newest.set(run.name, run);
2186
+ return {
2187
+ state: aggregateState(runs.filter((r) => r.name === AGGREGATE_CHECK)),
2188
+ sha,
2189
+ failing: [...newest.values()].filter((r) => r.status === "completed" && r.conclusion !== null && FAILED.has(r.conclusion)).map((r) => ({
2190
+ name: r.name,
2191
+ url: r.details_url ?? r.html_url
2192
+ }))
2193
+ };
2194
+ }
2195
+ // src/capabilities/pull-requests.ts
2196
+ /** The GitHub pull request as the neutral {@link PullRequest}. */
2197
+ function toPullRequest(raw) {
2198
+ return {
2199
+ number: raw.number,
2200
+ title: raw.title,
2201
+ state: raw.state,
2202
+ merged: raw.merged_at !== null,
2203
+ branch: raw.head.ref,
2204
+ headSha: raw.head.sha,
2205
+ url: raw.html_url
2206
+ };
2207
+ }
2208
+ /** Whether a body already holds a closing or referencing line for the issue (any keyword, any case). */
2209
+ function names(body, issue) {
2210
+ const escaped = issue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2211
+ return new RegExp(`\\b(closes?|fix(es)?|resolves?|refs?)\\s+${escaped}(?![\\w-])`, "i").test(body);
2212
+ }
2213
+ /**
2214
+ * The body with the link line the issue's closing reference needs. GitHub reads `Closes #12` itself, so the link is
2215
+ * text, not a call; a body that already names the issue is left alone.
2216
+ */
2217
+ function withLink(body, link) {
2218
+ if (!link) return body;
2219
+ const issue = link.issue.trim();
2220
+ const ref = /^\d+$/.test(issue) ? `#${issue}` : issue;
2221
+ const text = body ?? "";
2222
+ if (names(text, ref)) return body;
2223
+ const line = `${link.keyword ?? "Refs"} ${ref}`;
2224
+ return text.trim() === "" ? line : `${text.replace(/\s+$/, "")}\n\n${line}`;
2225
+ }
2226
+ /** Puts the pull request (by node id) on each board of the organization found by title; a board not found or refused is returned by name. */
2227
+ async function addToBoards(client, repo, nodeId, titles) {
2228
+ const dropped = [];
2229
+ const owner = repo.slice(0, repo.indexOf("/"));
2230
+ let boards;
2231
+ try {
2232
+ boards = (await client.graphql.query(`query($owner: String!) { organization(login: $owner) { projectsV2(first: 100) { nodes { id title closed } } } }`, { owner })).organization;
2233
+ } catch {
2234
+ return titles.map((t) => `project ${t}`);
2235
+ }
2236
+ for (const title of titles) {
2237
+ const board = boards?.projectsV2.nodes.find((b) => b.title === title && !b.closed);
2238
+ if (!board) {
2239
+ dropped.push(`project ${title}`);
2240
+ continue;
2241
+ }
2242
+ try {
2243
+ await client.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
2244
+ project: board.id,
2245
+ content: nodeId
2246
+ });
2247
+ } catch {
2248
+ dropped.push(`project ${title}`);
2249
+ }
2250
+ }
2251
+ return dropped;
2252
+ }
2253
+ /**
2254
+ * Puts the fields an issue and its pull request share on the pull request (GitHub serves a pull request through
2255
+ * the issues API for these): labels and assignees are added to what is there, a milestone is found by title and
2256
+ * boards by title. What cannot be applied comes back by name; nothing is created or cleared.
2257
+ */
2258
+ async function applyFields(client, repo, pr, fields) {
2259
+ const dropped = [];
2260
+ const { number } = pr;
2261
+ if (fields.labels?.length) await client.issues.addLabels(repo, number, fields.labels);
2262
+ for (const label of fields.removeLabels ?? []) try {
2263
+ await client.issues.removeLabel(repo, number, label);
2264
+ } catch {}
2265
+ const patch = {};
2266
+ if (fields.assignees?.length) {
2267
+ const have = ((await client.issues.getIssue(repo, number)).assignees ?? []).map((a) => a.login);
2268
+ const want = fields.assignees.map((a) => a.replace(/^@/, ""));
2269
+ const next = [.../* @__PURE__ */ new Set([...have, ...want])];
2270
+ if (next.length !== have.length) patch.assignees = next;
2271
+ }
2272
+ if (fields.milestone) {
2273
+ const found = (await client.issues.listMilestones(repo, { state: "open" })).find((m) => m.title === fields.milestone);
2274
+ if (found) patch.milestone = found.number;
2275
+ else dropped.push(`milestone ${fields.milestone}`);
2276
+ }
2277
+ if (Object.keys(patch).length) await client.issues.updateIssue(repo, number, patch);
2278
+ if (fields.projects?.length) {
2279
+ if (pr.node_id) dropped.push(...await addToBoards(client, repo, pr.node_id, fields.projects));
2280
+ else dropped.push(...fields.projects.map((t) => `project ${t}`));
2281
+ }
2282
+ return dropped;
2283
+ }
2284
+ /** Opens a draft pull request, or returns the open one for the same head, and applies the mirrored fields. */
2285
+ async function createPullRequest(client, repo, input) {
2286
+ const existing = (await client.pulls.listOpenByHead(repo, input.head))[0];
2287
+ const created = !existing;
2288
+ const raw = existing ?? await client.pulls.createPullRequest(repo, {
2289
+ title: input.title,
2290
+ head: input.head,
2291
+ base: input.base,
2292
+ body: withLink(input.body, input.link),
2293
+ draft: input.draft ?? true
2294
+ });
2295
+ const dropped = await applyFields(client, repo, raw, input);
2296
+ return {
2297
+ pullRequest: toPullRequest(raw),
2298
+ created,
2299
+ draft: raw.draft ?? false,
2300
+ dropped
2301
+ };
2302
+ }
2303
+ /** Changes a pull request's own fields, then the mirrored ones. A patch that names none of the own fields makes no PATCH. */
2304
+ async function updatePullRequest(client, repo, number, patch) {
2305
+ const own = {};
2306
+ if (patch.title !== void 0) own.title = patch.title;
2307
+ if (patch.body !== void 0) own.body = patch.body;
2308
+ if (patch.base !== void 0) own.base = patch.base;
2309
+ if (patch.state !== void 0) own.state = patch.state;
2310
+ const raw = Object.keys(own).length ? await client.pulls.updatePullRequest(repo, number, own) : await client.pulls.getPullRequest(repo, number);
2311
+ const dropped = await applyFields(client, repo, raw, patch);
2312
+ return {
2313
+ pullRequest: toPullRequest(raw),
2314
+ created: false,
2315
+ draft: raw.draft ?? false,
2316
+ dropped
2317
+ };
2318
+ }
2319
+ /** Takes a draft out of draft; `false` when it was not a draft or is not open. */
2320
+ async function markReady(client, repo, number) {
2321
+ const raw = await client.pulls.getPullRequest(repo, number);
2322
+ if (!raw.draft || raw.state !== "open") return false;
2323
+ if (!raw.node_id) throw new Error(`pull request ${repo}#${number} has no node id to mark ready`);
2324
+ await client.pulls.markReadyForReview(raw.node_id);
2325
+ return true;
2326
+ }
1831
2327
  // src/capabilities/read-repo.ts
1832
2328
  /** The settings `setup` writes, which `GET /repos/{repo}` reports under the same names. */
1833
2329
  const SETTING_KEYS = [
@@ -2030,17 +2526,6 @@ function syncOrgVariables(client, repo, org, variables, opts = {}) {
2030
2526
  });
2031
2527
  }
2032
2528
  // src/capabilities/source.ts
2033
- function toPullRequest(raw) {
2034
- return {
2035
- number: raw.number,
2036
- title: raw.title,
2037
- state: raw.state,
2038
- merged: raw.merged_at !== null,
2039
- branch: raw.head.ref,
2040
- headSha: raw.head.sha,
2041
- url: raw.html_url
2042
- };
2043
- }
2044
2529
  /**
2045
2530
  * The GitHub implementation of the `source` capability: repo settings, rulesets, branch protection, security
2046
2531
  * features and local workflow files.
@@ -2172,6 +2657,9 @@ var GitHubSource = class {
2172
2657
  async syncLabels(canonical, stale) {
2173
2658
  return syncLabels(this.client, this.repo, canonical, stale);
2174
2659
  }
2660
+ async ensureLabels(labels) {
2661
+ return ensureLabels(this.client, this.repo, labels);
2662
+ }
2175
2663
  async syncProperties(values) {
2176
2664
  return syncProperties(this.client, this.repo, values, this.orgClient ?? this.client);
2177
2665
  }
@@ -2281,6 +2769,22 @@ var GitHubSource = class {
2281
2769
  async listPullRequestCommits(number, repo) {
2282
2770
  return (await this.client.pulls.listCommits(repo ?? this.repo, number)).map((commit) => commit.sha);
2283
2771
  }
2772
+ async listPullRequestFiles(number, repo) {
2773
+ const files = await this.client.pulls.listFiles(repo ?? this.repo, number);
2774
+ return [...new Set(files.flatMap((f) => f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]))];
2775
+ }
2776
+ async createPullRequest(input, repo) {
2777
+ return createPullRequest(this.client, repo ?? this.repo, input);
2778
+ }
2779
+ async updatePullRequest(number, patch, repo) {
2780
+ return updatePullRequest(this.client, repo ?? this.repo, number, patch);
2781
+ }
2782
+ async markReady(number, repo) {
2783
+ return markReady(this.client, repo ?? this.repo, number);
2784
+ }
2785
+ async getPullRequestChecks(number, repo) {
2786
+ return readPullRequestChecks(this.client, repo ?? this.repo, number);
2787
+ }
2284
2788
  async configurePages(config, token) {
2285
2789
  const pagesClient = createGitHubClient$1({
2286
2790
  token,
@@ -2318,6 +2822,591 @@ async function ensureDir(path) {
2318
2822
  throw err;
2319
2823
  }
2320
2824
  }
2825
+ // src/probes/issue-types/github-api.ts
2826
+ const PAGE = 100;
2827
+ const PROJECTS_OF = `query($ids: [ID!]!) { nodes(ids: $ids) { ... on Issue { id projectItems(first: 20) { nodes { project { id } } } } } }`;
2828
+ const ADD_ITEM = `mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`;
2829
+ function toItem(issue) {
2830
+ return {
2831
+ number: issue.number,
2832
+ title: issue.title,
2833
+ state: issue.state,
2834
+ labels: issue.labels.map((l) => l.name),
2835
+ type: issue.type?.name ?? null,
2836
+ milestone: issue.milestone ?? null,
2837
+ nodeId: issue.node_id ?? "",
2838
+ isPullRequest: issue.pull_request !== void 0,
2839
+ createdAt: issue.created_at ?? ""
2840
+ };
2841
+ }
2842
+ /**
2843
+ * The backfill's reads and writes over the GitHub client. `client` reads and writes issues (the `github.issues` token);
2844
+ * `orgClient` reads and writes the organization's projects (the `github.org` token). Each method is the one call, or the
2845
+ * fixed few, its name says, so the probe's logic is tested against a fake of {@link BackfillApi} and this stays thin.
2846
+ */
2847
+ function createBackfillApi(client, orgClient, repo) {
2848
+ const org = repo.split("/")[0];
2849
+ const projects = new GitHubProjects(orgClient.graphql, { repo });
2850
+ let fieldList;
2851
+ const fields = async () => fieldList ??= client.issueFields.list(org);
2852
+ return {
2853
+ async list(page) {
2854
+ return (await client.issues.listIssues(repo, {
2855
+ state: "all",
2856
+ sort: "created",
2857
+ direction: "asc",
2858
+ per_page: PAGE,
2859
+ page
2860
+ })).map(toItem);
2861
+ },
2862
+ async get(number) {
2863
+ return toItem(await client.issues.getIssue(repo, number));
2864
+ },
2865
+ async parent(number) {
2866
+ const parent = await client.issues.getParent(repo, number);
2867
+ return parent ? {
2868
+ number: parent.number,
2869
+ milestone: parent.milestone?.number ?? null
2870
+ } : null;
2871
+ },
2872
+ async labelNames() {
2873
+ return new Set((await client.labels.listLabels(repo)).map((l) => l.name.toLowerCase()));
2874
+ },
2875
+ async milestoneNumber(title) {
2876
+ return (await client.issues.listMilestones(repo, { state: "all" })).find((m) => m.title.toLowerCase() === title.toLowerCase())?.number;
2877
+ },
2878
+ async projectId(title) {
2879
+ return (await projects.find(org, title))?.id;
2880
+ },
2881
+ async projectsOf(nodeIds) {
2882
+ const data = await orgClient.graphql.query(PROJECTS_OF, { ids: nodeIds });
2883
+ const out = /* @__PURE__ */ new Map();
2884
+ for (const node of data.nodes) if (node?.id) out.set(node.id, (node.projectItems?.nodes ?? []).map((i) => i.project.id));
2885
+ return out;
2886
+ },
2887
+ async fieldNames() {
2888
+ try {
2889
+ return new Set((await fields()).map((f) => f.name.toLowerCase()));
2890
+ } catch (err) {
2891
+ const why = fieldRefusal(err);
2892
+ if (why === void 0) throw err;
2893
+ return why;
2894
+ }
2895
+ },
2896
+ async fieldValues(number) {
2897
+ const byId = new Map((await fields()).map((f) => [f.id, f.name.toLowerCase()]));
2898
+ const values = await client.issueFields.values(repo, number);
2899
+ return new Set(values.map((v) => v.issue_field_name?.toLowerCase() ?? byId.get(v.issue_field_id) ?? ""));
2900
+ },
2901
+ async files(number) {
2902
+ return (await client.pulls.listFiles(repo, number)).map((f) => f.filename);
2903
+ },
2904
+ async setType(number, type) {
2905
+ await client.issues.updateIssue(repo, number, { type });
2906
+ },
2907
+ async addLabels(number, labels) {
2908
+ await client.issues.addLabels(repo, number, labels);
2909
+ },
2910
+ async setMilestone(number, milestone) {
2911
+ await client.issues.updateIssue(repo, number, { milestone });
2912
+ },
2913
+ async addToProject(projectId, nodeId) {
2914
+ await orgClient.graphql.query(ADD_ITEM, {
2915
+ project: projectId,
2916
+ content: nodeId
2917
+ });
2918
+ }
2919
+ };
2920
+ }
2921
+ // src/probes/issue-types/gather.ts
2922
+ /** Whether a day (`YYYY-MM-DD`) is before the start of the window. */
2923
+ const before = (item, since) => since !== void 0 && item.createdAt.slice(0, 10) < since;
2924
+ /** The issues named by `--issues`, past the cursor, at most `limit` of them. */
2925
+ async function named(api, options, isRateLimited) {
2926
+ const numbers = [...new Set(options.issues)].sort((a, b) => a - b).filter((n) => n > options.after);
2927
+ const out = {
2928
+ items: [],
2929
+ more: numbers.length > options.limit,
2930
+ rateLimited: false,
2931
+ pullRequestsSkipped: 0
2932
+ };
2933
+ for (const number of numbers.slice(0, options.limit)) try {
2934
+ const item = await api.get(number);
2935
+ if (item.isPullRequest && !options.pullRequests) out.pullRequestsSkipped++;
2936
+ else out.items.push(item);
2937
+ } catch (err) {
2938
+ if (!isRateLimited(err)) throw err;
2939
+ return {
2940
+ ...out,
2941
+ more: true,
2942
+ rateLimited: true
2943
+ };
2944
+ }
2945
+ return out;
2946
+ }
2947
+ /**
2948
+ * The items one run looks at: with `--issues` those numbers, otherwise every issue of the repository oldest first, a
2949
+ * page at a time, past the `--after` cursor and on or after `--since`, until `--limit` are kept. Issue numbers rise with
2950
+ * creation, so the last number read is a cursor the next run can resume from. A rate limit ends the read with what it has.
2951
+ */
2952
+ async function gather(api, options, isRateLimited) {
2953
+ if (options.issues) return named(api, options, isRateLimited);
2954
+ const out = {
2955
+ items: [],
2956
+ more: false,
2957
+ rateLimited: false,
2958
+ pullRequestsSkipped: 0
2959
+ };
2960
+ try {
2961
+ for (let page = 1;; page++) {
2962
+ const batch = await api.list(page);
2963
+ if (batch.length === 0) return out;
2964
+ for (const item of batch) {
2965
+ if (item.number <= options.after || before(item, options.since)) continue;
2966
+ if (item.isPullRequest && !options.pullRequests) {
2967
+ out.pullRequestsSkipped++;
2968
+ continue;
2969
+ }
2970
+ if (out.items.length >= options.limit) return {
2971
+ ...out,
2972
+ more: true
2973
+ };
2974
+ out.items.push(item);
2975
+ }
2976
+ }
2977
+ } catch (err) {
2978
+ if (!isRateLimited(err)) throw err;
2979
+ return {
2980
+ ...out,
2981
+ more: true,
2982
+ rateLimited: true
2983
+ };
2984
+ }
2985
+ }
2986
+ // src/probes/issue-types/plan-type.ts
2987
+ /** The kind labels and the Type each one means (spec `tech-github-area-labels`, decision 3). */
2988
+ const KIND_TYPES = {
2989
+ bug: "Bug",
2990
+ enhancement: "Feature",
2991
+ chore: "Task"
2992
+ };
2993
+ /**
2994
+ * The Type an issue gets from its kind labels. One that has a Type keeps it, whatever its labels say; one with exactly
2995
+ * one of `bug`, `enhancement` and `chore` gets that label's Type; one with two or more is `ambiguous` and left for a
2996
+ * person (the spec's rule: the probe never picks between two kinds); one with none has no source.
2997
+ */
2998
+ function planType(item) {
2999
+ if (item.type) return { skip: "typed" };
3000
+ const kinds = [...new Set(item.labels.map((l) => l.toLowerCase()).filter((l) => l in KIND_TYPES))];
3001
+ if (kinds.length === 0) return { skip: "no-kind-label" };
3002
+ if (kinds.length > 1) return {
3003
+ skip: "ambiguous",
3004
+ labels: kinds
3005
+ };
3006
+ return { set: KIND_TYPES[kinds[0]] };
3007
+ }
3008
+ // src/probes/issue-types/report.ts
3009
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
3010
+ const GROUPS = [
3011
+ ["project", "a project"],
3012
+ ["milestone", "a milestone"],
3013
+ ["priority", "a Priority"],
3014
+ ["effort", "an Effort"]
3015
+ ];
3016
+ /** The command the maintainer runs to continue, from the cursor. */
3017
+ function resumeCommand(options, cursor) {
3018
+ const flags = ["--after", String(cursor)];
3019
+ if (options.issues) flags.push("--issues", options.issues.join(","));
3020
+ if (options.since) flags.push("--since", options.since);
3021
+ flags.push("--limit", String(options.limit));
3022
+ if (options.milestone) flags.push("--milestone", options.milestone);
3023
+ if (options.project) flags.push("--project", options.project);
3024
+ if (options.pullRequests) flags.push("--pull-requests");
3025
+ return `holocron probe github issue-types -- ${flags.join(" ")}`;
3026
+ }
3027
+ /** Prints the counts, what was left for a person, the lists of what is still missing and how to go on. */
3028
+ function reportBackfill(ctx, input) {
3029
+ const { tally, options, dryRun, more, rateLimited, fields } = input;
3030
+ const verb = dryRun ? "would be set" : "set";
3031
+ ctx.say({
3032
+ status: "heading",
3033
+ label: "Backfill"
3034
+ });
3035
+ ctx.say({
3036
+ status: "info",
3037
+ label: "read",
3038
+ detail: `${plural(tally.examined, "item")} finished` + (tally.pullRequestsSkipped > 0 ? `, ${plural(tally.pullRequestsSkipped, "pull request")} passed over` : "") + (tally.failed > 0 ? `, ${plural(tally.failed, "failure")}` : "")
3039
+ });
3040
+ const types = Object.entries(tally.typeSet).map(([name, n]) => `${name} ${n}`).join(", ");
3041
+ ctx.say({
3042
+ status: "info",
3043
+ label: "Type",
3044
+ detail: `${types || "none"} ${verb}; ${tally.typed} already typed, ${tally.noKind} with no kind label, ${tally.ambiguous.length} with two kind labels`
3045
+ });
3046
+ for (const a of tally.ambiguous) ctx.say({
3047
+ status: "info",
3048
+ label: `#${a.number}`,
3049
+ detail: `has ${a.labels.join(" and ")}: left for a person to choose`
3050
+ });
3051
+ ctx.say({
3052
+ status: "info",
3053
+ label: "area labels",
3054
+ detail: `added to ${plural(tally.areaLabelsAdded, "item")}`
3055
+ });
3056
+ for (const label of tally.missingAreaLabels) ctx.say({
3057
+ status: "info",
3058
+ label,
3059
+ detail: "wanted but the repository has no such label: run `holocron setup` first"
3060
+ });
3061
+ ctx.say({
3062
+ status: "info",
3063
+ label: "milestone",
3064
+ detail: `${verb} on ${tally.milestoneSet.parent + tally.milestoneSet.explicit} (${tally.milestoneSet.parent} from a parent, ${tally.milestoneSet.explicit} from --milestone)`
3065
+ });
3066
+ ctx.say({
3067
+ status: "info",
3068
+ label: "project",
3069
+ detail: `${plural(tally.projectSet, "issue")} ${dryRun ? "would be added" : "added"} from --project`
3070
+ });
3071
+ ctx.say({
3072
+ status: "heading",
3073
+ label: `Still lacking, among the ${plural(tally.examined, "item")} read${dryRun ? ", after the changes above" : ""}`
3074
+ });
3075
+ if (tally.skippedFields !== void 0) ctx.say({
3076
+ status: "info",
3077
+ label: "Priority, Effort",
3078
+ detail: `not listed: the issue fields could not be read (${tally.skippedFields})`
3079
+ });
3080
+ for (const [group, noun] of GROUPS) {
3081
+ if (!(group === "project" || group === "milestone" || fields.includes(group))) continue;
3082
+ const items = tally.lacking[group];
3083
+ ctx.say({
3084
+ status: items.length === 0 ? "ok" : "info",
3085
+ label: `without ${noun}`,
3086
+ detail: String(items.length)
3087
+ });
3088
+ for (const item of items) ctx.say({
3089
+ status: "info",
3090
+ label: `#${item.number}`,
3091
+ detail: `${item.state}: ${item.title}`
3092
+ });
3093
+ }
3094
+ if (more && tally.last !== void 0) ctx.say({
3095
+ status: "info",
3096
+ label: "resume",
3097
+ detail: `${rateLimited ? "GitHub's rate limit stopped the run" : "the limit was reached"}; to continue: ${resumeCommand(options, tally.last)}`
3098
+ });
3099
+ else if (more) ctx.say({
3100
+ status: "info",
3101
+ label: "resume",
3102
+ detail: "GitHub's rate limit stopped the run before it finished one item; run it again later"
3103
+ });
3104
+ else ctx.say({
3105
+ status: "info",
3106
+ label: "resume",
3107
+ detail: "the window is finished"
3108
+ });
3109
+ }
3110
+ // src/probes/issue-types/backfill.ts
3111
+ /** The numbers the report is made of. */
3112
+ const emptyTally = () => ({
3113
+ examined: 0,
3114
+ pullRequestsSkipped: 0,
3115
+ typeSet: {},
3116
+ typed: 0,
3117
+ noKind: 0,
3118
+ ambiguous: [],
3119
+ areaLabelsAdded: 0,
3120
+ missingAreaLabels: /* @__PURE__ */ new Set(),
3121
+ milestoneSet: {
3122
+ parent: 0,
3123
+ explicit: 0
3124
+ },
3125
+ projectSet: 0,
3126
+ lacking: {
3127
+ project: [],
3128
+ milestone: [],
3129
+ priority: [],
3130
+ effort: []
3131
+ },
3132
+ failed: 0,
3133
+ last: void 0,
3134
+ skippedFields: void 0
3135
+ });
3136
+ /** How an issue is named in a row. */
3137
+ const labelOf = (item) => `#${item.number}`;
3138
+ /** Reads what the run needs before it starts: labels, the named milestone and project, the organization's issue fields. Says why and returns nothing when a name does not exist. */
3139
+ async function prepare(run, tally) {
3140
+ const { api, ctx, options } = run;
3141
+ const setup = {
3142
+ labelNames: await api.labelNames(),
3143
+ fields: []
3144
+ };
3145
+ if (options.milestone !== void 0) {
3146
+ setup.milestone = await api.milestoneNumber(options.milestone);
3147
+ if (setup.milestone === void 0) {
3148
+ ctx.say({
3149
+ status: "fail",
3150
+ label: "milestone",
3151
+ detail: `${options.milestone} is not a milestone of this repository`
3152
+ });
3153
+ return;
3154
+ }
3155
+ }
3156
+ if (options.project !== void 0) {
3157
+ setup.projectId = await api.projectId(options.project);
3158
+ if (setup.projectId === void 0) {
3159
+ ctx.say({
3160
+ status: "fail",
3161
+ label: "project",
3162
+ detail: `${options.project} is not a project of this organization`
3163
+ });
3164
+ return;
3165
+ }
3166
+ }
3167
+ const names = await api.fieldNames();
3168
+ if (typeof names === "string") tally.skippedFields = names;
3169
+ else setup.fields = ["priority", "effort"].filter((f) => names.has(f));
3170
+ return setup;
3171
+ }
3172
+ /** Does one issue or pull request; throws for a rate limit or a failed request, which the caller tells apart. */
3173
+ async function handle(run, setup, tally, item, projects) {
3174
+ const { api, ctx, areas, options } = run;
3175
+ const n = item.number;
3176
+ const wanted = item.isPullRequest ? areaLabelsForFiles(await api.files(n), areas.areas) : areaLabelsForTitle(item.title, areas.scopes);
3177
+ const have = new Set(item.labels.map((l) => l.toLowerCase()));
3178
+ const add = [];
3179
+ for (const label of wanted) {
3180
+ if (have.has(label.toLowerCase())) continue;
3181
+ if (setup.labelNames.has(label.toLowerCase())) add.push(label);
3182
+ else tally.missingAreaLabels.add(label);
3183
+ }
3184
+ if (add.length > 0) {
3185
+ await ctx.write(`add ${add.join(", ")} to ${labelOf(item)}`, () => api.addLabels(n, add));
3186
+ tally.areaLabelsAdded++;
3187
+ }
3188
+ if (item.isPullRequest) return;
3189
+ const type = planType(item);
3190
+ if ("set" in type) {
3191
+ await ctx.write(`set Type ${type.set} on ${labelOf(item)}`, () => api.setType(n, type.set));
3192
+ tally.typeSet[type.set] = (tally.typeSet[type.set] ?? 0) + 1;
3193
+ } else if (type.skip === "typed") tally.typed++;
3194
+ else if (type.skip === "no-kind-label") tally.noKind++;
3195
+ else tally.ambiguous.push({
3196
+ number: n,
3197
+ labels: type.labels
3198
+ });
3199
+ let milestone = item.milestone !== null;
3200
+ if (!milestone) {
3201
+ const parent = await api.parent(n);
3202
+ const fromParent = parent?.milestone;
3203
+ const target = fromParent ?? setup.milestone;
3204
+ if (target !== void 0) {
3205
+ const source = typeof fromParent === "number" ? "parent" : "explicit";
3206
+ const why = source === "parent" ? `from its parent #${parent?.number}` : `from --milestone ${options.milestone}`;
3207
+ await ctx.write(`set milestone on ${labelOf(item)} ${why}`, () => api.setMilestone(n, target));
3208
+ tally.milestoneSet[source]++;
3209
+ milestone = true;
3210
+ }
3211
+ }
3212
+ if (!milestone) tally.lacking.milestone.push(item);
3213
+ let onProject = projects.length > 0;
3214
+ if (!onProject && setup.projectId !== void 0) {
3215
+ const id = setup.projectId;
3216
+ await ctx.write(`add ${labelOf(item)} to project ${options.project}`, () => api.addToProject(id, item.nodeId));
3217
+ tally.projectSet++;
3218
+ onProject = true;
3219
+ }
3220
+ if (!onProject) tally.lacking.project.push(item);
3221
+ if (setup.fields.length > 0) {
3222
+ const values = await api.fieldValues(n);
3223
+ for (const field of setup.fields) if (!values.has(field)) tally.lacking[field].push(item);
3224
+ }
3225
+ }
3226
+ /**
3227
+ * The backfill of `holocron probe github issue-types` (spec `tech-github-area-labels`, rollout item 5): reads a window of
3228
+ * issues, and for each adds what it can derive and nothing else.
3229
+ *
3230
+ * - **Type** from the kind labels (`bug`, `enhancement`, `chore`); one that has a Type keeps it, one with two kind labels
3231
+ * is listed and left.
3232
+ * - **Area labels** from the title's scope, or, for a pull request with `--pull-requests`, from its changed files; only
3233
+ * added, and only when the label exists (`holocron setup` makes them).
3234
+ * - **Milestone** from the issue's parent, else `--milestone` for an issue in the window named by `--issues` or `--since`.
3235
+ * - **Project** from `--project` for such an issue that is on no project.
3236
+ *
3237
+ * Nothing is overwritten and no label is removed. Priority and Effort are never set, only listed when missing. Every
3238
+ * change goes through `ctx.write`, so `--dry-run` says `would ...` and writes nothing. A rate limit ends the run with the
3239
+ * cursor to resume from; any other failure is a row for that issue and the run goes on.
3240
+ */
3241
+ async function runBackfill(run) {
3242
+ const { ctx, api, options } = run;
3243
+ const tally = emptyTally();
3244
+ const setup = await prepare(run, tally);
3245
+ if (!setup) return;
3246
+ const read = await gather(api, options, run.isRateLimited);
3247
+ tally.pullRequestsSkipped = read.pullRequestsSkipped;
3248
+ const projects = /* @__PURE__ */ new Map();
3249
+ const ids = read.items.filter((i) => !i.isPullRequest).map((i) => i.nodeId);
3250
+ try {
3251
+ for (let at = 0; at < ids.length; at += 100) for (const [id, found] of await api.projectsOf(ids.slice(at, at + 100))) projects.set(id, found);
3252
+ } catch (err) {
3253
+ if (!run.isRateLimited(err)) throw err;
3254
+ read.rateLimited = true;
3255
+ read.more = true;
3256
+ read.items.length = 0;
3257
+ }
3258
+ let stopped = read.rateLimited;
3259
+ for (const item of read.items) {
3260
+ try {
3261
+ await handle(run, setup, tally, item, projects.get(item.nodeId) ?? []);
3262
+ } catch (err) {
3263
+ if (run.isRateLimited(err)) {
3264
+ stopped = true;
3265
+ break;
3266
+ }
3267
+ ctx.say({
3268
+ status: "fail",
3269
+ label: labelOf(item),
3270
+ detail: errorMessage(err)
3271
+ });
3272
+ tally.failed++;
3273
+ }
3274
+ tally.examined++;
3275
+ tally.last = item.number;
3276
+ }
3277
+ reportBackfill(ctx, {
3278
+ tally,
3279
+ options,
3280
+ dryRun: ctx.dryRun,
3281
+ more: read.more || stopped,
3282
+ rateLimited: stopped,
3283
+ fields: setup.fields
3284
+ });
3285
+ }
3286
+ const VALUED = [
3287
+ "--issues",
3288
+ "--since",
3289
+ "--after",
3290
+ "--limit",
3291
+ "--milestone",
3292
+ "--project"
3293
+ ];
3294
+ const INTEGER = /^\d+$/;
3295
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
3296
+ const MAX_RANGE = 1e3;
3297
+ /** `12,15,20-23` to `[12, 15, 20, 21, 22, 23]`, or `undefined` for text that is not such a list. */
3298
+ function numbersOf(text) {
3299
+ const out = [];
3300
+ for (const part of text.split(",")) {
3301
+ const [from, to, ...rest] = part.trim().split("-");
3302
+ if (rest.length > 0 || !INTEGER.test(from)) return void 0;
3303
+ const end = to === void 0 ? Number(from) : INTEGER.test(to) ? Number(to) : -1;
3304
+ if (end < Number(from) || end - Number(from) > MAX_RANGE) return void 0;
3305
+ for (let n = Number(from); n <= end; n++) out.push(n);
3306
+ }
3307
+ return out;
3308
+ }
3309
+ /** The words after `issue-types`, read into options, or the one thing wrong with them. */
3310
+ function parseArgs(args) {
3311
+ const options = {
3312
+ after: 0,
3313
+ limit: 100,
3314
+ pullRequests: false
3315
+ };
3316
+ for (let i = 0; i < args.length; i++) {
3317
+ const flag = args[i];
3318
+ if (flag === "--pull-requests") {
3319
+ options.pullRequests = true;
3320
+ continue;
3321
+ }
3322
+ if (!VALUED.includes(flag)) return {
3323
+ ok: false,
3324
+ message: `unknown argument ${flag}`
3325
+ };
3326
+ const value = args[++i];
3327
+ if (value === void 0 || value.startsWith("--")) return {
3328
+ ok: false,
3329
+ message: `${flag} needs a value`
3330
+ };
3331
+ if (flag === "--issues") {
3332
+ const issues = numbersOf(value);
3333
+ if (!issues) return {
3334
+ ok: false,
3335
+ message: `--issues takes numbers and ranges such as 12,15,20-25, not ${value}`
3336
+ };
3337
+ options.issues = issues;
3338
+ } else if (flag === "--since") {
3339
+ if (!DAY.test(value)) return {
3340
+ ok: false,
3341
+ message: `--since takes a day as YYYY-MM-DD, not ${value}`
3342
+ };
3343
+ options.since = value;
3344
+ } else if (flag === "--after") {
3345
+ if (!INTEGER.test(value)) return {
3346
+ ok: false,
3347
+ message: `--after takes a whole number, not ${value}`
3348
+ };
3349
+ options.after = Number(value);
3350
+ } else if (flag === "--limit") {
3351
+ if (!INTEGER.test(value) || Number(value) < 1) return {
3352
+ ok: false,
3353
+ message: `--limit takes a whole number of at least 1, not ${value}`
3354
+ };
3355
+ options.limit = Number(value);
3356
+ } else if (flag === "--milestone") options.milestone = value;
3357
+ else options.project = value;
3358
+ }
3359
+ if ((options.milestone || options.project) && !options.issues && !options.since) return {
3360
+ ok: false,
3361
+ message: "--milestone and --project need a window to apply to: name it with --issues or --since"
3362
+ };
3363
+ return {
3364
+ ok: true,
3365
+ options
3366
+ };
3367
+ }
3368
+ // src/probes/issue-types/issue-types.ts
3369
+ /**
3370
+ * `holocron probe github issue-types`: the one-time backfill of spec `tech-github-area-labels` (rollout item 5), a writer
3371
+ * the maintainer runs. It sets the Type of an issue from its kind labels, adds `area:<name>` labels, fills a milestone
3372
+ * and a project where a source exists, and ends with the list of every issue it read that still lacks a project, a
3373
+ * milestone, a Priority or an Effort. See `backfill.ts` for the rules. Run it with `--dry-run` first.
3374
+ *
3375
+ * Not verified against the live API: writing an issue's Type, adding an issue to a project, and the endpoints that read an
3376
+ * issue's field values and parent.
3377
+ */
3378
+ function issueTypesProbe(ctx) {
3379
+ return {
3380
+ summary: "Backfill issues: set Type from the kind labels, add area labels, fill milestone and project where a source exists, and list what still lacks a project, milestone, Priority or Effort. Never overwrites a value. Run with --dry-run first.",
3381
+ writes: true,
3382
+ async run(probe) {
3383
+ const parsed = parseArgs(probe.args ?? []);
3384
+ if (!parsed.ok) {
3385
+ probe.say({
3386
+ status: "fail",
3387
+ label: "arguments",
3388
+ detail: parsed.message
3389
+ });
3390
+ return;
3391
+ }
3392
+ try {
3393
+ await runBackfill({
3394
+ ctx: probe,
3395
+ api: ctx.makeApi(),
3396
+ options: parsed.options,
3397
+ areas: ctx.areas,
3398
+ isRateLimited
3399
+ });
3400
+ } catch (err) {
3401
+ probe.say({
3402
+ status: "fail",
3403
+ label: "issue-types",
3404
+ detail: errorMessage(err)
3405
+ });
3406
+ }
3407
+ }
3408
+ };
3409
+ }
2321
3410
  // src/probes/token/expectations.ts
2322
3411
  /** The same rules in every layer that runs the workflow: a laptop (`local` inherits `dev`) and CI. */
2323
3412
  function everywhere(rules) {
@@ -2832,6 +3921,10 @@ function createPlugin(options) {
2832
3921
  resolve: (envName) => TOKEN_RESOLVERS[envName]?.(options),
2833
3922
  tokenNames: Object.keys(TOKEN_RESOLVERS)
2834
3923
  }),
3924
+ "issue-types": issueTypesProbe({
3925
+ makeApi: () => createBackfillApi(makeCtx(resolveIssuesToken).client, makeCtx(resolveOrgToken).client, options.repo),
3926
+ areas: options.areaLabels ?? {}
3927
+ }),
2835
3928
  connection: connectionProbe({
2836
3929
  provider: "GitHub",
2837
3930
  url: options.baseUrl ?? "https://api.github.com",