@davidbyoung/software-factory 0.0.0-stage → 0.1.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.
Files changed (141) hide show
  1. package/.claude-plugin/plugin.json +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +135 -2
  4. package/actions/factory-agent/action.yml +218 -0
  5. package/agents/factory-test-reviewer.md +129 -0
  6. package/agents/factory-ticket-readiness.md +107 -0
  7. package/agents/factory-ui-reviewer.md +160 -0
  8. package/bin/factory.js +45 -0
  9. package/bin/launch.js +67 -0
  10. package/dist/board.d.mts +128 -0
  11. package/dist/board.mjs +456 -0
  12. package/dist/build.d.mts +18 -0
  13. package/dist/build.mjs +60 -0
  14. package/dist/cli.d.mts +17 -0
  15. package/dist/cli.mjs +264 -0
  16. package/dist/code-host/github.d.mts +118 -0
  17. package/dist/code-host/github.mjs +419 -0
  18. package/dist/code-host/index.d.mts +9 -0
  19. package/dist/code-host/index.mjs +18 -0
  20. package/dist/code-host/types.d.mts +205 -0
  21. package/dist/code-host/types.mjs +12 -0
  22. package/dist/config.d.mts +166 -0
  23. package/dist/config.mjs +548 -0
  24. package/dist/deps.d.mts +32 -0
  25. package/dist/deps.mjs +126 -0
  26. package/dist/doctor.d.mts +34 -0
  27. package/dist/doctor.mjs +188 -0
  28. package/dist/guard-commit.d.mts +41 -0
  29. package/dist/guard-commit.mjs +205 -0
  30. package/dist/guard-permission.d.mts +15 -0
  31. package/dist/guard-permission.mjs +52 -0
  32. package/dist/guard-ticket-text.d.mts +27 -0
  33. package/dist/guard-ticket-text.mjs +288 -0
  34. package/dist/guard.d.mts +4 -0
  35. package/dist/guard.mjs +37 -0
  36. package/dist/init.d.mts +58 -0
  37. package/dist/init.mjs +556 -0
  38. package/dist/lib/clock.d.mts +14 -0
  39. package/dist/lib/clock.mjs +36 -0
  40. package/dist/lib/gh.d.mts +28 -0
  41. package/dist/lib/gh.mjs +92 -0
  42. package/dist/lib/glob.d.mts +2 -0
  43. package/dist/lib/glob.mjs +41 -0
  44. package/dist/lib/pricing.d.mts +25 -0
  45. package/dist/lib/pricing.mjs +77 -0
  46. package/dist/lib/usage.d.mts +34 -0
  47. package/dist/lib/usage.mjs +128 -0
  48. package/dist/lib/work-status.d.mts +251 -0
  49. package/dist/lib/work-status.mjs +510 -0
  50. package/dist/merge-policy.d.mts +66 -0
  51. package/dist/merge-policy.mjs +146 -0
  52. package/dist/parts.d.mts +39 -0
  53. package/dist/parts.mjs +138 -0
  54. package/dist/poller.d.mts +61 -0
  55. package/dist/poller.mjs +247 -0
  56. package/dist/pr-watch.d.mts +45 -0
  57. package/dist/pr-watch.mjs +244 -0
  58. package/dist/pr.d.mts +65 -0
  59. package/dist/pr.mjs +571 -0
  60. package/dist/review-cost.d.mts +18 -0
  61. package/dist/review-cost.mjs +95 -0
  62. package/dist/review-tools.d.mts +5 -0
  63. package/dist/review-tools.mjs +46 -0
  64. package/dist/review-verdict.d.mts +50 -0
  65. package/dist/review-verdict.mjs +171 -0
  66. package/dist/reviewers.d.mts +54 -0
  67. package/dist/reviewers.mjs +312 -0
  68. package/dist/runner/github-actions.d.mts +12 -0
  69. package/dist/runner/github-actions.mjs +97 -0
  70. package/dist/runner/index.d.mts +9 -0
  71. package/dist/runner/index.mjs +22 -0
  72. package/dist/runner/types.d.mts +60 -0
  73. package/dist/runner/types.mjs +7 -0
  74. package/dist/session-start.d.mts +20 -0
  75. package/dist/session-start.mjs +115 -0
  76. package/dist/site/capture.d.mts +44 -0
  77. package/dist/site/capture.mjs +114 -0
  78. package/dist/site/measure.d.mts +83 -0
  79. package/dist/site/measure.mjs +225 -0
  80. package/dist/site/pages.d.mts +10 -0
  81. package/dist/site/pages.mjs +71 -0
  82. package/dist/site/pixels.d.mts +47 -0
  83. package/dist/site/pixels.mjs +157 -0
  84. package/dist/site/servers.d.mts +47 -0
  85. package/dist/site/servers.mjs +141 -0
  86. package/dist/site.d.mts +60 -0
  87. package/dist/site.mjs +341 -0
  88. package/dist/status.d.mts +100 -0
  89. package/dist/status.mjs +514 -0
  90. package/dist/sync.d.mts +59 -0
  91. package/dist/sync.mjs +292 -0
  92. package/dist/ticket.d.mts +61 -0
  93. package/dist/ticket.mjs +562 -0
  94. package/dist/tickets/github.d.mts +128 -0
  95. package/dist/tickets/github.mjs +491 -0
  96. package/dist/tickets/index.d.mts +15 -0
  97. package/dist/tickets/index.mjs +27 -0
  98. package/dist/tickets/transport.d.mts +42 -0
  99. package/dist/tickets/transport.mjs +158 -0
  100. package/dist/tickets/types.d.mts +191 -0
  101. package/dist/tickets/types.mjs +76 -0
  102. package/docs/builds.md +227 -0
  103. package/docs/cli.md +221 -0
  104. package/docs/configuration.md +809 -0
  105. package/docs/design.md +106 -0
  106. package/docs/developing.md +400 -0
  107. package/docs/existing-repo.md +138 -0
  108. package/docs/github/reference.md +288 -0
  109. package/docs/github/setup.md +312 -0
  110. package/docs/glossary.md +106 -0
  111. package/docs/limitations.md +115 -0
  112. package/docs/plugins.md +192 -0
  113. package/docs/quick-start.md +222 -0
  114. package/docs/removing.md +76 -0
  115. package/docs/skills.md +270 -0
  116. package/docs/updating.md +108 -0
  117. package/docs/workflow.md +195 -0
  118. package/package.json +67 -4
  119. package/poller.Dockerfile +21 -0
  120. package/review.md +170 -0
  121. package/rules.md +313 -0
  122. package/settings.schema.json +411 -0
  123. package/skills/factory-address-review/SKILL.md +547 -0
  124. package/skills/factory-address-review/patch-coverage.py +68 -0
  125. package/skills/factory-build/SKILL.md +412 -0
  126. package/skills/factory-deps/SKILL.md +185 -0
  127. package/skills/factory-design/SKILL.md +159 -0
  128. package/skills/factory-diagnose/SKILL.md +93 -0
  129. package/skills/factory-mutate/SKILL.md +76 -0
  130. package/skills/factory-refine/SKILL.md +417 -0
  131. package/skills/factory-resolve-conflicts/SKILL.md +235 -0
  132. package/workflows/factory-board-sync.yml +91 -0
  133. package/workflows/factory-build.yml +72 -0
  134. package/workflows/factory-check.yml +37 -0
  135. package/workflows/factory-claude-review.yml +133 -0
  136. package/workflows/factory-conflicts.yml +69 -0
  137. package/workflows/factory-deps-auto-merge.yml +43 -0
  138. package/workflows/factory-deps.yml +59 -0
  139. package/workflows/factory-merge-policy.yml +121 -0
  140. package/workflows/factory-review-verdict.yml +54 -0
  141. package/workflows/factory-review.yml +75 -0
@@ -0,0 +1,419 @@
1
+ import { NotFoundError } from "../tickets/types.mjs";
2
+ import { statusOf } from "../tickets/transport.mjs";
3
+ import { NeedsScopeError } from "./types.mjs";
4
+ /** What a check wrote about its result: its title and its summary. */
5
+ const reportOf = (output) => [output?.title, output?.summary].filter(Boolean).join("\n") || undefined;
6
+ const endOf = (end) => ({
7
+ sha: end?.sha ?? "",
8
+ branch: end?.ref ?? "",
9
+ repository: end?.repo?.full_name ?? null,
10
+ });
11
+ function pullOf(raw) {
12
+ const base = endOf(raw.base);
13
+ return {
14
+ number: raw.number,
15
+ title: raw.title,
16
+ state: raw.state,
17
+ merged: raw.merged ?? false,
18
+ isDraft: raw.draft ?? false,
19
+ body: raw.body ?? "",
20
+ mergeableState: raw.mergeable_state ?? "unknown",
21
+ author: raw.user?.login ?? "ghost",
22
+ labels: (raw.labels ?? []).map((l) => l.name),
23
+ head: endOf(raw.head),
24
+ base: { ...base, repository: base.repository ?? "" },
25
+ createdAt: raw.created_at ?? "",
26
+ autoMerge: (raw.auto_merge ?? null) !== null,
27
+ };
28
+ }
29
+ const commentOf = (raw) => ({
30
+ id: raw.id,
31
+ author: raw.user?.login ?? "ghost",
32
+ body: raw.body ?? "",
33
+ createdAt: raw.created_at,
34
+ ...(raw.path === undefined ? {} : { path: raw.path, line: raw.line }),
35
+ ...(raw.in_reply_to_id === undefined ? {} : { replyTo: raw.in_reply_to_id }),
36
+ });
37
+ const reviewOf = (raw) => ({
38
+ id: raw.id,
39
+ author: raw.user?.login ?? "ghost",
40
+ body: raw.body ?? "",
41
+ submittedAt: raw.submitted_at,
42
+ });
43
+ const THREADS_QUERY = `
44
+ query ReviewThreads($owner: String!, $name: String!, $number: Int!) {
45
+ repository(owner: $owner, name: $name) {
46
+ pullRequest(number: $number) {
47
+ reviewThreads(first: 100) {
48
+ nodes {
49
+ id isResolved isOutdated path line
50
+ comments(first: 50) { nodes { databaseId author { login } body } }
51
+ }
52
+ }
53
+ }
54
+ }
55
+ }`;
56
+ export function fromGraph(nodes) {
57
+ return nodes.map((t) => ({
58
+ commentId: t.comments.nodes[0]?.databaseId ?? 0,
59
+ nodeId: t.id,
60
+ isResolved: t.isResolved,
61
+ isOutdated: t.isOutdated,
62
+ path: t.path,
63
+ line: t.line,
64
+ comments: t.comments.nodes.map((c) => ({
65
+ id: c.databaseId,
66
+ author: c.author?.login ?? "ghost",
67
+ body: c.body,
68
+ })),
69
+ }));
70
+ }
71
+ // The open pull requests, for the views, the sync, and the poller. Only the
72
+ // sync asks for their comments ($costs), which it needs for Cost; the
73
+ // poller, which reads every minute, and the terminal view do not.
74
+ export const OPEN_PULLS_QUERY = `
75
+ query OpenPulls(
76
+ $owner: String!
77
+ $name: String!
78
+ $checks: Boolean = false
79
+ $costs: Boolean = false
80
+ ) {
81
+ repository(owner: $owner, name: $name) {
82
+ pullRequests(states: OPEN, first: 100) {
83
+ nodes {
84
+ ...pull
85
+ reviewThreads(first: 100) { nodes { isResolved } }
86
+ commits(last: 1) @include(if: $checks) {
87
+ nodes { commit { statusCheckRollup { state } } }
88
+ }
89
+ }
90
+ }
91
+ }
92
+ }
93
+ fragment pull on PullRequest {
94
+ number createdAt body isDraft
95
+ author { login }
96
+ closingIssuesReferences(first: 25) {
97
+ nodes { number repository { nameWithOwner } }
98
+ }
99
+ comments(last: 100) @include(if: $costs) {
100
+ nodes { databaseId createdAt body author { login } }
101
+ }
102
+ }`;
103
+ // Every pull request, open, merged, or closed and however old, that
104
+ // mentioned one of the tickets "Read everything at once" returns: the set
105
+ // the sync reads cost markers from. A ticket system other than GitHub's
106
+ // could not answer this, so it is asked here, of the pull requests.
107
+ export const LINKING_PULLS_QUERY = `
108
+ query LinkingPulls($owner: String!, $name: String!, $after: String) {
109
+ repository(owner: $owner, name: $name) {
110
+ open: issues(states: OPEN, first: 100, after: $after) {
111
+ pageInfo { hasNextPage endCursor }
112
+ nodes { ...links }
113
+ }
114
+ closed: issues(states: CLOSED, first: 30, orderBy: {field: UPDATED_AT, direction: DESC}) {
115
+ nodes { ...links }
116
+ }
117
+ }
118
+ }
119
+ fragment links on Issue {
120
+ builders: timelineItems(itemTypes: [CROSS_REFERENCED_EVENT], last: 20) {
121
+ nodes { ... on CrossReferencedEvent { source { ... on PullRequest {
122
+ number createdAt body isDraft
123
+ author { login }
124
+ closingIssuesReferences(first: 25) {
125
+ nodes { number repository { nameWithOwner } }
126
+ }
127
+ comments(last: 100) {
128
+ nodes { databaseId createdAt body author { login } }
129
+ }
130
+ } } } }
131
+ }
132
+ }`;
133
+ const toComments = (raw) => (raw?.nodes ?? []).map((c) => ({
134
+ id: c.databaseId,
135
+ createdAt: c.createdAt,
136
+ body: c.body,
137
+ author: c.author?.login ?? "ghost",
138
+ }));
139
+ export function toPull(raw, repository) {
140
+ return {
141
+ number: raw.number,
142
+ createdAt: raw.createdAt,
143
+ body: raw.body,
144
+ isDraft: raw.isDraft,
145
+ author: raw.author?.login ?? "ghost",
146
+ closes: raw.closingIssuesReferences.nodes
147
+ .filter((ref) => ref.repository.nameWithOwner === repository)
148
+ .map((ref) => ref.number),
149
+ openThreads: (raw.reviewThreads?.nodes ?? []).filter((t) => !t.isResolved)
150
+ .length,
151
+ checks: raw.commits?.nodes[0]?.commit.statusCheckRollup?.state ?? null,
152
+ comments: toComments(raw.comments),
153
+ };
154
+ }
155
+ /** The pull requests in every page of LINKING_PULLS_QUERY, less those in
156
+ * `skip`, which the caller already has. */
157
+ export function fromLinkingPages(pages, repository, skip = []) {
158
+ const done = new Map();
159
+ const issues = [
160
+ ...pages.flatMap((p) => p.data.repository.open.nodes),
161
+ ...(pages[0]?.data.repository.closed.nodes ?? []),
162
+ ];
163
+ for (const issue of issues)
164
+ for (const { source } of issue.builders?.nodes ?? []) {
165
+ // A cross-reference from an issue has no pull request fields.
166
+ if (source?.number === undefined || !source.closingIssuesReferences)
167
+ continue;
168
+ if (skip.includes(source.number))
169
+ continue;
170
+ done.set(source.number, toPull(source, repository));
171
+ }
172
+ return [...done.values()];
173
+ }
174
+ const RESOLVE = "mutation ResolveThread($id: ID!) { resolveReviewThread(input: {threadId: $id}) { thread { isResolved } } }";
175
+ const CLOSING_QUERY = `
176
+ query ClosingIssues($owner: String!, $name: String!, $number: Int!) {
177
+ repository(owner: $owner, name: $name) {
178
+ pullRequest(number: $number) {
179
+ closingIssuesReferences(first: 25) { nodes { number } }
180
+ }
181
+ }
182
+ }`;
183
+ const OPEN_THREADS_QUERY = "query($owner:String!,$name:String!,$n:Int!){repository(owner:$owner,name:$name){pullRequest(number:$n){reviewThreads(first:100){nodes{isResolved}}}}}";
184
+ /** Rethrows a 404 as NotFoundError for `what`. */
185
+ async function found(what, call) {
186
+ try {
187
+ return await call;
188
+ }
189
+ catch (error) {
190
+ if (statusOf(error) === 404)
191
+ throw new NotFoundError(what);
192
+ throw error;
193
+ }
194
+ }
195
+ export function githubCodeHost(o) {
196
+ const t = o.transport;
197
+ const API = `repos/${o.repository}`;
198
+ const [owner, name] = o.repository.split("/");
199
+ const list = (path) => t.rest("GET", path, { paginate: true });
200
+ async function threads(n) {
201
+ const result = await t.graphql(THREADS_QUERY, { owner, name, number: n });
202
+ return fromGraph(result.data.repository.pullRequest.reviewThreads.nodes);
203
+ }
204
+ return {
205
+ get: async (n) => pullOf(await found(`pull request #${n}`, t.rest("GET", `${API}/pulls/${n}`))),
206
+ async create(pull) {
207
+ const made = await t.rest("POST", `${API}/pulls`, {
208
+ fields: pull,
209
+ });
210
+ return made.number;
211
+ },
212
+ listOpen: async () => (await list(`${API}/pulls?state=open&per_page=100`)).map(pullOf),
213
+ async forBranch(branch) {
214
+ const open = await t.rest("GET", `${API}/pulls?head=${owner}:${branch}&state=open`);
215
+ return open[0]?.number ?? null;
216
+ },
217
+ forCommit: async (sha) => (await t.rest("GET", `${API}/commits/${sha}/pulls`)).map(({ number, state }) => ({ number, state })),
218
+ files: async (n) => (await list(`${API}/pulls/${n}/files?per_page=100`)).map((f) => ({
219
+ path: f.filename,
220
+ ...(f.previous_filename === undefined
221
+ ? {}
222
+ : { previousPath: f.previous_filename }),
223
+ status: f.status,
224
+ })),
225
+ async mergeBase(base, head) {
226
+ const compare = await t.rest("GET", `${API}/compare/${base}...${head}`);
227
+ return compare.merge_base_commit.sha;
228
+ },
229
+ async defaultBranch() {
230
+ const repo = await t.rest("GET", API);
231
+ return repo.default_branch;
232
+ },
233
+ async checkRuns(sha) {
234
+ const answer = await t.rest("GET", `${API}/commits/${sha}/check-runs?per_page=100`);
235
+ return answer.check_runs.map((c) => ({
236
+ id: c.id,
237
+ name: c.name,
238
+ status: c.status,
239
+ conclusion: c.conclusion,
240
+ link: c.html_url,
241
+ checksId: c.check_suite?.id,
242
+ report: reportOf(c.output),
243
+ }));
244
+ },
245
+ async statuses(sha) {
246
+ const answer = await t.rest("GET", `${API}/commits/${sha}/status`);
247
+ return answer.statuses.map((s) => ({
248
+ id: s.id,
249
+ name: s.context,
250
+ state: s.state,
251
+ link: s.target_url,
252
+ }));
253
+ },
254
+ async setStatus(sha, status) {
255
+ await t.rest("POST", `${API}/statuses/${sha}`, {
256
+ fields: {
257
+ state: status.state,
258
+ context: status.name,
259
+ description: status.description,
260
+ ...(status.link === undefined ? {} : { target_url: status.link }),
261
+ },
262
+ });
263
+ },
264
+ comments: async (n) => (await list(`${API}/issues/${n}/comments?per_page=100`)).map(commentOf),
265
+ async comment(n, body) {
266
+ const made = await found(`pull request #${n}`, t.rest("POST", `${API}/issues/${n}/comments`, {
267
+ fields: { body },
268
+ }));
269
+ return made.id;
270
+ },
271
+ commentView: async (id) => commentOf(await found(`comment ${id}`, t.rest("GET", `${API}/issues/comments/${id}`))),
272
+ async editComment(id, body) {
273
+ await found(`comment ${id}`, t.rest("PATCH", `${API}/issues/comments/${id}`, { fields: { body } }));
274
+ },
275
+ async addLabel(n, label) {
276
+ await found(`pull request #${n}`, t.rest("POST", `${API}/issues/${n}/labels`, {
277
+ fields: { labels: [label] },
278
+ }));
279
+ },
280
+ async removeLabel(n, label) {
281
+ await found(`the ${label} label on #${n}`, t.rest("DELETE", `${API}/issues/${n}/labels/${encodeURIComponent(label)}`));
282
+ },
283
+ reviews: async (n) => (await list(`${API}/pulls/${n}/reviews?per_page=100`)).map(reviewOf),
284
+ reviewCommentsOf: async (n, reviewId) => (await list(`${API}/pulls/${n}/reviews/${reviewId}/comments?per_page=100`)).map(commentOf),
285
+ reviewComments: async (n) => (await list(`${API}/pulls/${n}/comments?per_page=100`)).map(commentOf),
286
+ async setBody(n, body) {
287
+ await t.rest("PATCH", `${API}/pulls/${n}`, { fields: { body } });
288
+ },
289
+ threads,
290
+ async openThreadCount(n) {
291
+ const result = await t.graphql(OPEN_THREADS_QUERY, { owner, name, n });
292
+ return result.data.repository.pullRequest.reviewThreads.nodes.filter((x) => !x.isResolved).length;
293
+ },
294
+ async reply(n, commentId, body) {
295
+ const made = await t.rest("POST", `${API}/pulls/${n}/comments/${commentId}/replies`, { fields: { body } });
296
+ return made.id;
297
+ },
298
+ async resolve(n, commentId) {
299
+ const thread = (await threads(n)).find((x) => x.comments.some((c) => c.id === commentId));
300
+ if (!thread?.nodeId)
301
+ throw new Error(`No review thread on #${n} holds comment ${commentId}.`);
302
+ await t.graphql(RESOLVE, { id: thread.nodeId });
303
+ },
304
+ async ready(n) {
305
+ if (!o.cli)
306
+ throw new Error("Marking ready needs the GitHub CLI.");
307
+ await o.cli(["pr", "ready", String(n), "--repo", o.repository]);
308
+ },
309
+ // GitHub is asked because a runner's git cannot verify an SSH signature
310
+ // itself.
311
+ async unverifiedCommits(n) {
312
+ const commits = await t.rest("GET", `${API}/pulls/${n}/commits?per_page=100`);
313
+ return commits
314
+ .filter((c) => c.commit.verification?.verified !== true)
315
+ .map((c) => `${c.sha.slice(0, 7)} ${c.commit.verification?.reason ?? "unknown"}`);
316
+ },
317
+ async closes(n) {
318
+ const result = await t.graphql(CLOSING_QUERY, { owner, name, number: n });
319
+ return result.data.repository.pullRequest.closingIssuesReferences.nodes.map((x) => x.number);
320
+ },
321
+ async open(options = {}) {
322
+ const page = await t.graphql(OPEN_PULLS_QUERY, {
323
+ owner,
324
+ name,
325
+ checks: options.checks ?? false,
326
+ costs: options.costs ?? false,
327
+ });
328
+ return page.data.repository.pullRequests.nodes.map((p) => toPull(p, o.repository));
329
+ },
330
+ async linking(skip = []) {
331
+ const pages = [];
332
+ let after = null;
333
+ do {
334
+ const page = await t.graphql(LINKING_PULLS_QUERY, { owner, name, after });
335
+ pages.push(page);
336
+ const info = page.data.repository.open.pageInfo;
337
+ after = info.hasNextPage ? info.endCursor : null;
338
+ } while (after);
339
+ return fromLinkingPages(pages, o.repository, skip);
340
+ },
341
+ address: (n) => `https://github.com/${o.repository}/pull/${n}`,
342
+ async signedInAs() {
343
+ return (await t.rest("GET", "user")).login;
344
+ },
345
+ async tokenOwner(token) {
346
+ const response = await (o.fetch ?? fetch)("https://api.github.com/user", {
347
+ headers: {
348
+ Authorization: `Bearer ${token}`,
349
+ Accept: "application/vnd.github+json",
350
+ "User-Agent": "software-factory",
351
+ },
352
+ });
353
+ const body = (await response.json().catch(() => ({})));
354
+ if (!response.ok || !body.login)
355
+ throw new Error(`GitHub refused the token: ${body.message ?? response.statusText}`);
356
+ const scopes = response.headers.get("x-oauth-scopes");
357
+ return {
358
+ account: body.login,
359
+ scopes: scopes === null
360
+ ? null
361
+ : scopes
362
+ .split(",")
363
+ .map((x) => x.trim())
364
+ .filter(Boolean),
365
+ };
366
+ },
367
+ scopesFor: (needs) => needs.map((n) => ({ push: "repo", workflows: "workflow", board: "project" })[n]),
368
+ newTokenPage: (scopes, note) => `https://github.com/settings/tokens/new?scopes=${scopes.join(",")}&description=${encodeURIComponent(note)}`,
369
+ reviewAppPage: () => "https://github.com/apps/claude/installations/new",
370
+ async allowAutoMerge() {
371
+ await t.rest("PATCH", API, { fields: { allow_auto_merge: true } });
372
+ },
373
+ async requireCheck(rule, check) {
374
+ const existing = await t.rest("GET", `${API}/rulesets?per_page=100`);
375
+ if (existing.some((r) => r.name === rule))
376
+ return;
377
+ await t.rest("POST", `${API}/rulesets`, {
378
+ body: {
379
+ name: rule,
380
+ target: "branch",
381
+ enforcement: "active",
382
+ conditions: {
383
+ ref_name: { include: ["~DEFAULT_BRANCH"], exclude: [] },
384
+ },
385
+ rules: [
386
+ {
387
+ type: "required_status_checks",
388
+ parameters: {
389
+ required_status_checks: [{ context: check }],
390
+ strict_required_status_checks_policy: false,
391
+ },
392
+ },
393
+ ],
394
+ },
395
+ });
396
+ },
397
+ async addSigningKey(title, key) {
398
+ try {
399
+ await t.rest("POST", "user/ssh_signing_keys", {
400
+ fields: { title, key },
401
+ });
402
+ }
403
+ catch (error) {
404
+ const scope = "admin:ssh_signing_key";
405
+ if (String(error).includes(scope) || statusOf(error) === 404)
406
+ throw new NeedsScopeError(scope, [
407
+ "gh",
408
+ "auth",
409
+ "refresh",
410
+ "-h",
411
+ "github.com",
412
+ "-s",
413
+ scope,
414
+ ]);
415
+ throw error;
416
+ }
417
+ },
418
+ };
419
+ }
@@ -0,0 +1,9 @@
1
+ import { type Gh } from "../lib/gh.mts";
2
+ import type { CodeHost } from "./types.mts";
3
+ export * from "./types.mts";
4
+ export declare const DEFAULT_CODE_HOST: "github";
5
+ /** The message for a code host that is not built. */
6
+ export declare const unsupportedCodeHost: (type: string) => string;
7
+ /** The code host of that name for the repository, reached through the
8
+ * GitHub CLI. */
9
+ export declare function openCodeHost(repository: string, type?: string, run?: Gh): CodeHost;
@@ -0,0 +1,18 @@
1
+ // Which code host a name picks, built for a command in a session or CI.
2
+ // `github` is the only one, and the settings refuse any other value of
3
+ // `code-host.type` before this runs (`config.mts`). A command that has not
4
+ // read the settings asks for the default.
5
+ import { gh } from "../lib/gh.mjs";
6
+ import { ghTransport } from "../tickets/transport.mjs";
7
+ import { githubCodeHost } from "./github.mjs";
8
+ export * from "./types.mjs";
9
+ export const DEFAULT_CODE_HOST = "github";
10
+ /** The message for a code host that is not built. */
11
+ export const unsupportedCodeHost = (type) => `code-host.type "${type}" is not supported. "github" is the only code host built.`;
12
+ /** The code host of that name for the repository, reached through the
13
+ * GitHub CLI. */
14
+ export function openCodeHost(repository, type = DEFAULT_CODE_HOST, run = gh) {
15
+ if (type !== "github")
16
+ throw new Error(unsupportedCodeHost(type));
17
+ return githubCodeHost({ transport: ghTransport(run), repository, cli: run });
18
+ }
@@ -0,0 +1,205 @@
1
+ import type { PullRequest } from "../lib/work-status.mts";
2
+ /** One end of a pull request: the commit, its branch, and the repository
3
+ * the branch is in, as owner/name. */
4
+ export type PullEnd = {
5
+ sha: string;
6
+ branch: string;
7
+ repository: string;
8
+ };
9
+ export type Pull = {
10
+ number: number;
11
+ title: string;
12
+ /** `open` or `closed`. */
13
+ state: string;
14
+ merged?: boolean;
15
+ isDraft: boolean;
16
+ body: string;
17
+ /** Whether it merges into its base: `dirty` for a conflict, and `unknown`
18
+ * until the code host has worked it out, which `listOpen` never does. */
19
+ mergeableState: string;
20
+ author: string;
21
+ labels: string[];
22
+ /** Its repository is null once the fork it came from is gone. */
23
+ head: Omit<PullEnd, "repository"> & {
24
+ repository: string | null;
25
+ };
26
+ base: PullEnd;
27
+ createdAt?: string;
28
+ /** Whether it is set to merge itself once its gates pass. */
29
+ autoMerge?: boolean;
30
+ };
31
+ /** A conversation comment, or a comment a review left on a line. */
32
+ export type PullComment = {
33
+ id: number;
34
+ author: string;
35
+ body: string;
36
+ createdAt: string;
37
+ /** The file and line, on a review's comment. */
38
+ path?: string;
39
+ line?: number | null;
40
+ /** The comment this one replies to, when it is a reply in a thread. */
41
+ replyTo?: number;
42
+ };
43
+ export type Review = {
44
+ id: number;
45
+ author: string;
46
+ body: string;
47
+ submittedAt: string;
48
+ };
49
+ export type Thread = {
50
+ /** The thread's first comment, which `reply` and `resolve` take. */
51
+ commentId: number;
52
+ /** The code host's own ID for the thread, when it has one. */
53
+ nodeId?: string;
54
+ isResolved: boolean;
55
+ isOutdated: boolean;
56
+ path: string;
57
+ line: number | null;
58
+ comments: {
59
+ id: number;
60
+ author: string;
61
+ body: string;
62
+ }[];
63
+ };
64
+ /** One run of a check on a commit. `status` is `completed` once it has
65
+ * ended, and `conclusion` says how. */
66
+ export type CheckRun = {
67
+ id: number;
68
+ name: string;
69
+ status: string;
70
+ conclusion: string | null;
71
+ link?: string;
72
+ /** The ID the check shares with the runner's run that reported it. */
73
+ checksId?: number;
74
+ /** What the check wrote about its own result, when it wrote anything. */
75
+ report?: string;
76
+ };
77
+ /** A status set on a commit by name: `pending`, `success`, `failure`, or
78
+ * `error`. */
79
+ export type CommitStatus = {
80
+ id: number;
81
+ name: string;
82
+ state: string;
83
+ link?: string;
84
+ };
85
+ export type NewStatus = {
86
+ name: string;
87
+ state: "success" | "failure" | "pending";
88
+ description: string;
89
+ link?: string;
90
+ };
91
+ /** A pull request to open: from the `head` branch into the `base` branch. */
92
+ export type NewPull = {
93
+ title: string;
94
+ head: string;
95
+ base: string;
96
+ body: string;
97
+ draft: boolean;
98
+ };
99
+ export type ChangedFile = {
100
+ path: string;
101
+ /** The path it had before, when the pull request renamed it. */
102
+ previousPath?: string;
103
+ status: string;
104
+ };
105
+ export type CodeHost = {
106
+ /** The pull request, or NotFoundError when there is none. */
107
+ get(pull: number): Promise<Pull>;
108
+ /** Opens a pull request and returns its number. It fails in the code
109
+ * host's own words when the head has nothing the base lacks, or already
110
+ * has an open pull request. */
111
+ create(pull: NewPull): Promise<number>;
112
+ listOpen(): Promise<Pull[]>;
113
+ /** The open pull request from this branch, or null. */
114
+ forBranch(branch: string): Promise<number | null>;
115
+ /** The pull requests that hold the commit, open or not. */
116
+ forCommit(sha: string): Promise<{
117
+ number: number;
118
+ state: string;
119
+ }[]>;
120
+ files(pull: number): Promise<ChangedFile[]>;
121
+ /** The commit two commits both descend from. */
122
+ mergeBase(base: string, head: string): Promise<string>;
123
+ defaultBranch(): Promise<string>;
124
+ /** The check runs on a commit, without its statuses. */
125
+ checkRuns(sha: string): Promise<CheckRun[]>;
126
+ /** The statuses on a commit, without its check runs. */
127
+ statuses(sha: string): Promise<CommitStatus[]>;
128
+ setStatus(sha: string, status: NewStatus): Promise<void>;
129
+ /** The conversation comments. */
130
+ comments(pull: number): Promise<PullComment[]>;
131
+ /** One conversation comment, or NotFoundError when it is gone. */
132
+ commentView(id: number): Promise<PullComment>;
133
+ /** Returns the comment's ID. The body is posted as given. */
134
+ comment(pull: number, body: string): Promise<number>;
135
+ /** NotFoundError when the comment is gone. */
136
+ editComment(id: number, body: string): Promise<void>;
137
+ addLabel(pull: number, label: string): Promise<void>;
138
+ /** NotFoundError when the pull request does not carry the label. */
139
+ removeLabel(pull: number, label: string): Promise<void>;
140
+ reviews(pull: number): Promise<Review[]>;
141
+ /** The comments one review carries. */
142
+ reviewCommentsOf(pull: number, review: number): Promise<PullComment[]>;
143
+ /** Every comment every review left on a line. */
144
+ reviewComments(pull: number): Promise<PullComment[]>;
145
+ threads(pull: number): Promise<Thread[]>;
146
+ openThreadCount(pull: number): Promise<number>;
147
+ /** Replies on the thread `commentId` starts, and returns the reply's ID. */
148
+ reply(pull: number, commentId: number, body: string): Promise<number>;
149
+ /** Resolves the thread that holds the comment. */
150
+ resolve(pull: number, commentId: number): Promise<void>;
151
+ setBody(pull: number, body: string): Promise<void>;
152
+ /** Marks a draft ready for review. */
153
+ ready(pull: number): Promise<void>;
154
+ /** One line for each commit on the pull request the code host does not
155
+ * show as signed: its short ID and the reason, such as `unsigned`. */
156
+ unverifiedCommits(pull: number): Promise<string[]>;
157
+ /** The tickets the pull request closes when it merges. */
158
+ closes(pull: number): Promise<number[]>;
159
+ /** The open pull requests, as the views and the sync read them: with
160
+ * their check state when `checks` is asked, and their comments, for the
161
+ * cost markers, when `costs` is. */
162
+ open(options?: {
163
+ checks?: boolean;
164
+ costs?: boolean;
165
+ }): Promise<PullRequest[]>;
166
+ /** The pull requests, open or not, that link to an open ticket or one
167
+ * closed lately, other than those in `skip`. */
168
+ linking(skip?: number[]): Promise<PullRequest[]>;
169
+ /** The address of a pull request's page. */
170
+ address(pull: number): string;
171
+ /** Who the code host's command-line tool is signed in as. */
172
+ signedInAs(): Promise<string>;
173
+ /** The account a token belongs to, and its scopes: null when the code
174
+ * host does not say, as for a token with fine-grained permissions.
175
+ * Rejects a token the code host refuses. */
176
+ tokenOwner(token: string): Promise<{
177
+ account: string;
178
+ scopes: string[] | null;
179
+ }>;
180
+ /** The code host's names for the scopes a token needs to do these. */
181
+ scopesFor(needs: TokenNeed[]): string[];
182
+ /** The page that makes a token with these scopes, noted as `note`. */
183
+ newTokenPage(scopes: string[], note: string): string;
184
+ /** The page that installs the app the automated review posts through,
185
+ * or null where the review needs none. */
186
+ reviewAppPage(): string | null;
187
+ /** Lets a pull request be set to merge itself once its gates pass. */
188
+ allowAutoMerge(): Promise<void>;
189
+ /** Requires `check` to pass before a merge to the default branch, as a
190
+ * rule named `rule`. A rule of that name already there is left alone. */
191
+ requireCheck(rule: string, check: string): Promise<void>;
192
+ /** Adds a public key to the signed-in account, to sign commits with.
193
+ * Rejects with NeedsScopeError when the sign-in lacks the permission. */
194
+ addSigningKey(title: string, publicKey: string): Promise<void>;
195
+ };
196
+ /** What a token for the factory's jobs may need to do: push a branch,
197
+ * change a workflow's file, and write the board. */
198
+ export type TokenNeed = "push" | "workflows" | "board";
199
+ /** A call the signed-in account's sign-in lacks the permission for. `fix`
200
+ * is the command that asks for it. */
201
+ export declare class NeedsScopeError extends Error {
202
+ readonly scope: string;
203
+ readonly fix: string[];
204
+ constructor(scope: string, fix: string[]);
205
+ }
@@ -0,0 +1,12 @@
1
+ /** A call the signed-in account's sign-in lacks the permission for. `fix`
2
+ * is the command that asks for it. */
3
+ export class NeedsScopeError extends Error {
4
+ scope;
5
+ fix;
6
+ constructor(scope, fix) {
7
+ super(`The sign-in needs the ${scope} permission.`);
8
+ this.name = "NeedsScopeError";
9
+ this.scope = scope;
10
+ this.fix = fix;
11
+ }
12
+ }