@skitterbyte/skitterspec-github 0.0.0-stage → 1.0.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 (112) hide show
  1. package/MIGRATION.md +1107 -0
  2. package/README.md +53 -2
  3. package/assets/claude-md-section.md +85 -0
  4. package/assets/commands/allow-main.md +33 -0
  5. package/assets/commands/spec-connect.md +13 -0
  6. package/assets/commands/spec-live.md +14 -0
  7. package/assets/commands/spec-remote-review.md +37 -0
  8. package/assets/commands/spec-skip.md +24 -0
  9. package/assets/core/SETUP.md +112 -0
  10. package/assets/core/env.config.json.example +56 -0
  11. package/assets/core/env.config.md +557 -0
  12. package/assets/core/gating.config.json.example +4 -0
  13. package/assets/core/gating.config.md +81 -0
  14. package/assets/core/github.config.json.example +18 -0
  15. package/assets/core/github.config.md +66 -0
  16. package/assets/hooks/main-guard.cjs +162 -0
  17. package/assets/hooks/review-gate.cjs +146 -0
  18. package/assets/review/page.html +3384 -0
  19. package/assets/rules/commit-trailers.md +103 -0
  20. package/assets/rules/negative-checks.md +69 -0
  21. package/assets/rules/offered-unblocks.md +100 -0
  22. package/assets/rules/spec-planning.md +692 -0
  23. package/assets/rules/spec-reports.md +557 -0
  24. package/assets/skills/no-spec/SKILL.md +246 -0
  25. package/assets/skills/spec/SKILL.md +718 -0
  26. package/assets/skills/spec-bug/SKILL.md +646 -0
  27. package/assets/skills/spec-cancel/SKILL.md +263 -0
  28. package/assets/skills/spec-claim/SKILL.md +122 -0
  29. package/assets/skills/spec-complete/SKILL.md +450 -0
  30. package/assets/skills/spec-diff/SKILL.md +870 -0
  31. package/assets/skills/spec-github-setup/SKILL.md +236 -0
  32. package/assets/skills/spec-hotfix/SKILL.md +668 -0
  33. package/assets/skills/spec-init/SKILL.md +178 -0
  34. package/assets/skills/spec-list/SKILL.md +172 -0
  35. package/assets/skills/spec-next/SKILL.md +685 -0
  36. package/assets/skills/spec-push/SKILL.md +307 -0
  37. package/assets/skills/spec-review/SKILL.md +258 -0
  38. package/assets/skills/spec-reviewed/SKILL.md +284 -0
  39. package/assets/skills/spec-start/SKILL.md +554 -0
  40. package/assets/skills/spec-status/SKILL.md +112 -0
  41. package/assets/skills/spec-sync/SKILL.md +226 -0
  42. package/assets/skills/spec-to-main/SKILL.md +139 -0
  43. package/bin/skitterspec-github.js +61 -0
  44. package/package.json +41 -4
  45. package/src/cli.js +5901 -0
  46. package/src/deprecate.js +138 -0
  47. package/src/env/bootstrap.js +188 -0
  48. package/src/env/building.js +143 -0
  49. package/src/env/classify.js +176 -0
  50. package/src/env/commitcmd.js +108 -0
  51. package/src/env/config.js +753 -0
  52. package/src/env/dev.js +63 -0
  53. package/src/env/hooks.js +226 -0
  54. package/src/env/hotfix.js +411 -0
  55. package/src/env/hotfixland.js +302 -0
  56. package/src/env/integrate.js +126 -0
  57. package/src/env/live.js +504 -0
  58. package/src/env/mainguard.js +299 -0
  59. package/src/env/provision.js +466 -0
  60. package/src/env/proxy.js +192 -0
  61. package/src/env/prune.js +119 -0
  62. package/src/env/registry.js +159 -0
  63. package/src/env/render.js +17 -0
  64. package/src/env/resolve.js +716 -0
  65. package/src/env/review.js +2577 -0
  66. package/src/env/reviewers/coderabbit.js +228 -0
  67. package/src/env/reviewers.js +517 -0
  68. package/src/env/serve.js +1044 -0
  69. package/src/env/supervise.js +157 -0
  70. package/src/env/teardown.js +248 -0
  71. package/src/env/trust.js +87 -0
  72. package/src/gating.js +155 -0
  73. package/src/init.js +1150 -0
  74. package/src/lines-diff.js +114 -0
  75. package/src/prompts.js +129 -0
  76. package/src/vendor/github/api.js +786 -0
  77. package/src/vendor/github/cli-sync.js +1530 -0
  78. package/src/vendor/github/commands.js +44 -0
  79. package/src/vendor/github/config.js +414 -0
  80. package/src/vendor/github/credentials.js +109 -0
  81. package/src/vendor/github/dialect.js +62 -0
  82. package/src/vendor/github/identity.js +38 -0
  83. package/src/vendor/github/mcp.js +85 -0
  84. package/src/vendor/provider-kit/index.js +41 -0
  85. package/src/vendor/provider-kit/src/adapter.js +23 -0
  86. package/src/vendor/provider-kit/src/apply.js +207 -0
  87. package/src/vendor/provider-kit/src/args.js +68 -0
  88. package/src/vendor/provider-kit/src/assignment.js +277 -0
  89. package/src/vendor/provider-kit/src/config.js +198 -0
  90. package/src/vendor/provider-kit/src/credentials.js +404 -0
  91. package/src/vendor/provider-kit/src/doctor.js +35 -0
  92. package/src/vendor/provider-kit/src/http.js +63 -0
  93. package/src/vendor/provider-kit/src/identity.js +93 -0
  94. package/src/vendor/provider-kit/src/md-compare.js +39 -0
  95. package/src/vendor/provider-kit/src/md-tables.js +94 -0
  96. package/src/vendor/provider-kit/src/prompt.js +50 -0
  97. package/src/vendor/provider-kit/src/released.js +269 -0
  98. package/src/vendor/provider-kit/src/releases.js +380 -0
  99. package/src/vendor/provider-kit/src/specs.js +166 -0
  100. package/src/vendor/provider-kit/src/transport.js +22 -0
  101. package/src/vendor/sync-core/index.js +93 -0
  102. package/src/vendor/sync-core/src/base.js +81 -0
  103. package/src/vendor/sync-core/src/compare.js +338 -0
  104. package/src/vendor/sync-core/src/dialect.js +51 -0
  105. package/src/vendor/sync-core/src/fields.js +36 -0
  106. package/src/vendor/sync-core/src/legacy.js +100 -0
  107. package/src/vendor/sync-core/src/normalize.js +998 -0
  108. package/src/vendor/sync-core/src/push.js +85 -0
  109. package/src/vendor/sync-core/src/retarget.js +278 -0
  110. package/src/vendor/sync-core/src/task-block.js +308 -0
  111. package/src/vendor/sync-core/src/verify.js +67 -0
  112. package/src/vendor/sync-core/src/write.js +191 -0
@@ -0,0 +1,786 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * The GitHub adapter — the one place that speaks GitHub's protocol: REST for
5
+ * issues, sub-issues and comments, GraphQL for the Projects v2 board.
6
+ *
7
+ * Every op takes and returns the engine's shapes. An issue's identifier is
8
+ * `#123`, its `id` the number as a string (what every other op accepts back),
9
+ * its workflow state `{ name }` — the BOARD's Status value, never the issue's
10
+ * open/closed — and an assignee `{ id, name }` where the id is the login.
11
+ * Node ids and database ids ride along on the normalised issue for the calls
12
+ * that need them, and are never stamped into a spec.
13
+ *
14
+ * WORKFLOW STATE IS A BOARD FIELD. `setStatus` adds the issue to the board when
15
+ * it is not on it (an issue off the board has no state at all) and sets the
16
+ * Status option by NAME, resolved to an option id against the live field. An
17
+ * unknown name is a loud, named refusal listing the options that DO exist — a
18
+ * positive signal (options listed, target absent), never a guess. The issue's
19
+ * own open/closed is a separate write (`setIssueOpen`); which bucket closes it
20
+ * is config's call (`config.js` `closeReasonFor`), not this module's.
21
+ *
22
+ * Auth is a bearer token. 401 is phrased for the human holding the token;
23
+ * rate limits — a 429, or a 403 carrying `Retry-After` or a spent
24
+ * `X-RateLimit-Remaining` — wait and retry via the kit's shared discipline
25
+ * (`provider-kit/src/http.js`), and one that never recovers is a retryable
26
+ * refusal, distinguishable from every other failure.
27
+ *
28
+ * WHAT WOULD FOOL A 404 HERE: GitHub answers 404, not 403, for a private repo
29
+ * the token cannot see. So a 404 on a READ is "nothing there that this token
30
+ * can see" — the read returns null, the harmless answer — and a 404 on a
31
+ * WRITE is a refusal that names both readings rather than claiming the issue
32
+ * does not exist.
33
+ */
34
+
35
+ const { withRateLimitRetry, MAX_RETRIES } = require('../provider-kit/src/http.js')
36
+ const { assertBodyFits } = require('./dialect.js')
37
+
38
+ const API_URL = 'https://api.github.com'
39
+ const API_VERSION = '2022-11-28'
40
+ const PAGE = 100
41
+ // A bound on paging, so a misbehaving server cannot loop us forever. 10 pages
42
+ // of 100 is past anything a spec issue carries.
43
+ const MAX_PAGES = 10
44
+
45
+ // A refusal GitHub itself expressed — its `message`, validation `errors`, or
46
+ // GraphQL `errors` — kept apart from transport failures so callers can report
47
+ // cause, not symptom.
48
+ class GitHubRefusal extends Error {
49
+ constructor(message, { status = null, retryable = false, errors = null, orphan = null } = {}) {
50
+ super(message)
51
+ this.name = 'GitHubRefusal'
52
+ this.status = status
53
+ this.retryable = retryable
54
+ this.errors = errors
55
+ // Set on a refusal that came AFTER something was created (a sub-issue that
56
+ // could not be linked) — the orphan the caller must name. Not `created`:
57
+ // the kit's apply accounting writes that name onto every error it sees.
58
+ this.orphan = orphan
59
+ }
60
+ }
61
+
62
+ function refusalFrom(status, body) {
63
+ const parts = []
64
+ if (body && typeof body.message === 'string') parts.push(body.message)
65
+ if (body && Array.isArray(body.errors)) {
66
+ for (const e of body.errors) {
67
+ if (typeof e === 'string') parts.push(e)
68
+ else if (e && (e.message || e.code)) parts.push([e.field, e.message || e.code].filter(Boolean).join(': '))
69
+ }
70
+ }
71
+ const joined = parts.length ? parts.join('; ') : `HTTP ${status}`
72
+ return new GitHubRefusal(`GitHub refused the request: ${joined}`, { status, errors: body && body.errors })
73
+ }
74
+
75
+ // GitHub's rate limits: a 429, or a 403 that says it is one. A plain 403 —
76
+ // "Resource not accessible by personal access token" — is NOT retried: it is a
77
+ // permissions answer, and waiting changes nothing.
78
+ function isLimited(res) {
79
+ if (res.status === 429) return true
80
+ if (res.status !== 403) return false
81
+ const get = res.headers && typeof res.headers.get === 'function' ? (h) => res.headers.get(h) : () => null
82
+ return get('retry-after') != null || get('x-ratelimit-remaining') === '0'
83
+ }
84
+
85
+ // Accept `#12`, `12`, 12, or a normalised issue. Anything else is a caller bug,
86
+ // said plainly rather than sent to GitHub as `/issues/NaN`.
87
+ function numberOf(ref) {
88
+ if (ref && typeof ref === 'object') return numberOf(ref.number != null ? ref.number : ref.id)
89
+ const m = /^#?(\d+)$/.exec(String(ref == null ? '' : ref).trim())
90
+ if (!m) throw new Error(`not a GitHub issue reference: ${JSON.stringify(ref)} (expected #123 or 123)`)
91
+ return Number(m[1])
92
+ }
93
+
94
+ const identifierOf = (number) => `#${number}`
95
+
96
+ const BOARD_FRAGMENT = `
97
+ fragment Board on ProjectV2 {
98
+ id
99
+ title
100
+ url
101
+ fields(first: 50) {
102
+ nodes {
103
+ ... on ProjectV2SingleSelectField { id name options { id name } }
104
+ ... on ProjectV2FieldCommon { id name }
105
+ }
106
+ }
107
+ }`
108
+
109
+ const BOARD_QUERY = `
110
+ query($owner: String!, $number: Int!) {
111
+ repositoryOwner(login: $owner) {
112
+ __typename
113
+ ... on User { projectV2(number: $number) { ...Board } }
114
+ ... on Organization { projectV2(number: $number) { ...Board } }
115
+ }
116
+ }
117
+ ${BOARD_FRAGMENT}`
118
+
119
+ const ISSUE_QUERY = `
120
+ query($owner: String!, $repo: String!, $number: Int!, $status: String!) {
121
+ repository(owner: $owner, name: $repo) {
122
+ issue(number: $number) {
123
+ id
124
+ databaseId
125
+ number
126
+ title
127
+ body
128
+ url
129
+ state
130
+ stateReason
131
+ assignees(first: 10) { nodes { login name } }
132
+ labels(first: 30) { nodes { name } }
133
+ parent { number }
134
+ subIssues(first: 100) { nodes { number title state } }
135
+ projectItems(first: 20) {
136
+ nodes {
137
+ id
138
+ project { id number owner { __typename ... on User { login } ... on Organization { login } } }
139
+ fieldValueByName(name: $status) { ... on ProjectV2ItemFieldSingleSelectValue { name optionId } }
140
+ }
141
+ }
142
+ }
143
+ }
144
+ }`
145
+
146
+ // This repo's issues WITH their board item, by search rather than by the
147
+ // board's own `items` connection. On the first live run of this provider that
148
+ // connection read totalCount 0 for over an hour — during a GitHub incident
149
+ // degrading Issues — while every item was readable by id and from
150
+ // `issue.projectItems`, and it recovered on its own. GitHub also has an open
151
+ // report of the same symptom outside an incident (community discussion
152
+ // #188487). Reading each issue's own `projectItems` is the side that stayed
153
+ // correct throughout.
154
+ const REPO_ISSUES = `
155
+ query($q: String!, $status: String!, $after: String) {
156
+ search(query: $q, type: ISSUE, first: 100, after: $after) {
157
+ pageInfo { hasNextPage endCursor }
158
+ nodes {
159
+ ... on Issue {
160
+ number title url state
161
+ repository { nameWithOwner }
162
+ parent { number }
163
+ projectItems(first: 20) {
164
+ nodes {
165
+ id
166
+ project { number owner { __typename ... on User { login } ... on Organization { login } } }
167
+ fieldValueByName(name: $status) { ... on ProjectV2ItemFieldSingleSelectValue { name } }
168
+ }
169
+ }
170
+ }
171
+ }
172
+ }
173
+ }`
174
+
175
+ const ADD_ITEM = `
176
+ mutation($project: ID!, $content: ID!) {
177
+ addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } }
178
+ }`
179
+
180
+ const SET_OPTION = `
181
+ mutation($project: ID!, $item: ID!, $field: ID!, $option: String!) {
182
+ updateProjectV2ItemFieldValue(
183
+ input: { projectId: $project, itemId: $item, fieldId: $field, value: { singleSelectOptionId: $option } }
184
+ ) { projectV2Item { id } }
185
+ }`
186
+
187
+ /**
188
+ * Wrap a token and a repo into the typed ops the engine uses. Injected `fetch`
189
+ * and `sleep` make every op testable offline.
190
+ *
191
+ * @param {{ owner, repo, project, statusField?, token, apiUrl?, fetch?, sleep?, maxRetries?, now? }} opts
192
+ */
193
+ function makeApiAdapter({
194
+ owner,
195
+ repo,
196
+ project,
197
+ statusField = 'Status',
198
+ deployedField = 'Deployed',
199
+ token,
200
+ apiUrl = API_URL,
201
+ fetch: fetchImpl,
202
+ sleep,
203
+ now,
204
+ maxRetries = MAX_RETRIES,
205
+ }) {
206
+ const doFetch = fetchImpl || globalThis.fetch
207
+ if (typeof doFetch !== 'function') {
208
+ throw new Error('no fetch available — Node 18+ is required for the API transport')
209
+ }
210
+ if (!owner || !repo) {
211
+ throw new Error('no GitHub repo configured — set github.owner and github.repo in specs/.core/github.config.json')
212
+ }
213
+ const base = String(apiUrl).replace(/\/+$/, '')
214
+ const repoPath = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`
215
+
216
+ async function send(method, url, body) {
217
+ const { response: res, exhausted } = await withRateLimitRetry(
218
+ async () => {
219
+ try {
220
+ return await doFetch(url, {
221
+ method,
222
+ headers: {
223
+ Authorization: `Bearer ${token}`,
224
+ Accept: 'application/vnd.github+json',
225
+ 'X-GitHub-Api-Version': API_VERSION,
226
+ 'User-Agent': 'skitterspec',
227
+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
228
+ },
229
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
230
+ })
231
+ } catch (cause) {
232
+ throw new Error(`GitHub unreachable: ${cause && cause.message ? cause.message : cause}`)
233
+ }
234
+ },
235
+ { sleep, maxRetries, isLimited, now },
236
+ )
237
+ if (res.status === 401) {
238
+ throw new Error('GitHub rejected the token (HTTP 401) — check it is valid and has not expired')
239
+ }
240
+ if (exhausted) {
241
+ throw new GitHubRefusal(`GitHub rate-limited this request and did not recover after ${maxRetries} retries`, {
242
+ status: res.status,
243
+ retryable: true,
244
+ })
245
+ }
246
+ return res
247
+ }
248
+
249
+ async function parse(res) {
250
+ if (res.status === 204) return {}
251
+ try {
252
+ return await res.json()
253
+ } catch {
254
+ return null
255
+ }
256
+ }
257
+
258
+ // REST. `allow404` turns a 404 into null — for READS only (see the header).
259
+ async function rest(method, pathname, { query, body, allow404 = false, withHeaders = false } = {}) {
260
+ const url = new URL(base + pathname)
261
+ for (const [k, v] of Object.entries(query || {})) if (v != null) url.searchParams.set(k, String(v))
262
+ const res = await send(method, url.toString(), body)
263
+ if (res.status === 404 && allow404) return withHeaders ? { body: null, headers: res.headers } : null
264
+ const parsed = await parse(res)
265
+ if (res.status === 404) {
266
+ throw new GitHubRefusal(
267
+ `GitHub answered 404 for ${method} ${pathname} — the issue or repo does not exist, ` +
268
+ 'or this token cannot see it (GitHub answers 404 for both). Check github.owner/repo and the token\'s `repo` scope.',
269
+ { status: 404 },
270
+ )
271
+ }
272
+ if (!res.ok) throw refusalFrom(res.status, parsed)
273
+ return withHeaders ? { body: parsed, headers: res.headers } : parsed
274
+ }
275
+
276
+ // Every page of a list endpoint, bounded (`MAX_PAGES`).
277
+ async function restAll(pathname, query = {}) {
278
+ const out = []
279
+ for (let page = 1; page <= MAX_PAGES; page++) {
280
+ const got = await rest('GET', pathname, { query: { ...query, per_page: PAGE, page } })
281
+ const items = Array.isArray(got) ? got : []
282
+ out.push(...items)
283
+ if (items.length < PAGE) break
284
+ }
285
+ return out
286
+ }
287
+
288
+ // GraphQL. A NOT_FOUND error with `allowMissing` resolves to the data as far
289
+ // as it got (the missing node is null there); every other error is a refusal.
290
+ async function graphql(query, variables, { allowMissing = false } = {}) {
291
+ const res = await send('POST', `${base}/graphql`, { query, variables })
292
+ const parsed = await parse(res)
293
+ if (!res.ok) throw refusalFrom(res.status, parsed)
294
+ const errors = (parsed && Array.isArray(parsed.errors) && parsed.errors) || []
295
+ const fatal = errors.filter((e) => !(allowMissing && e && e.type === 'NOT_FOUND'))
296
+ if (fatal.length) {
297
+ const scopes = fatal.some((e) => e && e.type === 'INSUFFICIENT_SCOPES')
298
+ throw new GitHubRefusal(
299
+ `GitHub refused the request: ${fatal.map((e) => (e && e.message) || String(e)).join('; ')}` +
300
+ (scopes ? ' — a classic token needs the `repo` and `project` scopes' : ''),
301
+ { errors: fatal },
302
+ )
303
+ }
304
+ return (parsed && parsed.data) || {}
305
+ }
306
+
307
+ const sameLogin = (a, b) => String(a || '').toLowerCase() === String(b || '').toLowerCase()
308
+
309
+ // The board item for THIS repo's board among an issue's project items:
310
+ // matched by number AND owner, because two owners can each have a board 7.
311
+ function boardItemOf(raw) {
312
+ const items = (raw && raw.projectItems && raw.projectItems.nodes) || []
313
+ return (
314
+ items.find(
315
+ (n) => n && n.project && n.project.number === project && n.project.owner && sameLogin(n.project.owner.login, owner),
316
+ ) || null
317
+ )
318
+ }
319
+
320
+ function normalizeIssue(raw) {
321
+ if (!raw || raw.number == null) return null
322
+ const item = boardItemOf(raw)
323
+ const status = item && item.fieldValueByName && item.fieldValueByName.name != null ? item.fieldValueByName.name : null
324
+ const assignee = raw.assignees && raw.assignees.nodes && raw.assignees.nodes[0]
325
+ return {
326
+ id: String(raw.number),
327
+ number: raw.number,
328
+ identifier: identifierOf(raw.number),
329
+ url: raw.url || null,
330
+ nodeId: raw.id || null,
331
+ databaseId: raw.databaseId != null ? raw.databaseId : null,
332
+ title: raw.title != null ? raw.title : null,
333
+ // An empty body comes back null; to the engine that is the empty text,
334
+ // not an unknown.
335
+ description: raw.body == null ? '' : String(raw.body),
336
+ state: status != null ? { name: status } : null,
337
+ open: raw.state === 'OPEN',
338
+ stateReason: raw.stateReason ? String(raw.stateReason).toLowerCase() : null,
339
+ onBoard: !!item,
340
+ boardItemId: item ? item.id : null,
341
+ assignee: assignee ? { id: assignee.login, name: assignee.name || assignee.login } : null,
342
+ labels: ((raw.labels && raw.labels.nodes) || []).map((l) => l && l.name).filter(Boolean),
343
+ parent: raw.parent && raw.parent.number != null ? { id: String(raw.parent.number), identifier: identifierOf(raw.parent.number) } : null,
344
+ subtasks: ((raw.subIssues && raw.subIssues.nodes) || []).map((s) => ({
345
+ id: String(s.number),
346
+ identifier: identifierOf(s.number),
347
+ title: s.title != null ? s.title : null,
348
+ open: s.state === 'OPEN',
349
+ })),
350
+ }
351
+ }
352
+
353
+ // The REST create payload from engine-shaped input. Only PRESENT keys are
354
+ // sent — `undefined` means "say nothing", `null` means "clear it" (assignee).
355
+ function issuePayload(input, { forCreate = false } = {}) {
356
+ const body = {}
357
+ if (input.title !== undefined) body.title = input.title
358
+ if (input.description !== undefined) {
359
+ assertBodyFits(input.description, input.title ? `"${input.title}"` : 'this issue body')
360
+ body.body = input.description == null ? '' : input.description
361
+ }
362
+ if (input.assigneeId !== undefined) body.assignees = input.assigneeId == null ? [] : [input.assigneeId]
363
+ if (input.labels !== undefined) body.labels = input.labels || []
364
+ // Issue types exist on org-owned repos only; sending one elsewhere is a
365
+ // 422, so it is sent only when the caller names one.
366
+ if (forCreate && input.type) body.type = input.type
367
+ return body
368
+ }
369
+
370
+ const created = (raw) => ({
371
+ id: String(raw.number),
372
+ identifier: identifierOf(raw.number),
373
+ url: raw.html_url || null,
374
+ nodeId: raw.node_id || null,
375
+ databaseId: raw.id != null ? raw.id : null,
376
+ })
377
+
378
+ let boardCache = null
379
+
380
+ const releaseOf = (raw) =>
381
+ raw && raw.id != null
382
+ ? { id: raw.id, tag: raw.tag_name, url: raw.html_url || null, body: raw.body == null ? '' : String(raw.body), prerelease: !!raw.prerelease }
383
+ : null
384
+
385
+ async function resolveBoard() {
386
+ if (boardCache) return boardCache
387
+ if (!project) {
388
+ throw new GitHubRefusal('no board configured — set github.project to the board number from its URL')
389
+ }
390
+ const data = await graphql(BOARD_QUERY, { owner, number: project }, { allowMissing: true })
391
+ const ownerNode = data.repositoryOwner
392
+ const board = ownerNode && ownerNode.projectV2
393
+ if (!board || !board.id) {
394
+ throw new GitHubRefusal(
395
+ `no board ${project} owned by ${owner} that this token can see — check github.project ` +
396
+ '(the number in the board URL) and that the token has the `project` scope',
397
+ )
398
+ }
399
+ boardCache = {
400
+ id: board.id,
401
+ title: board.title || null,
402
+ url: board.url || null,
403
+ fields: ((board.fields && board.fields.nodes) || [])
404
+ .filter((f) => f && f.id && f.name)
405
+ .map((f) => ({ id: f.id, name: f.name, options: Array.isArray(f.options) ? f.options.map((o) => ({ id: o.id, name: o.name })) : null })),
406
+ }
407
+ return boardCache
408
+ }
409
+
410
+ async function singleSelect(fieldName) {
411
+ const board = await resolveBoard()
412
+ const want = String(fieldName || '').toLowerCase().trim()
413
+ const field = board.fields.find((f) => String(f.name).toLowerCase().trim() === want)
414
+ if (!field || !field.options) {
415
+ const singles = board.fields.filter((f) => f.options).map((f) => `"${f.name}"`).join(', ') || '(none)'
416
+ throw new GitHubRefusal(
417
+ `the board has no single-select field "${fieldName}" — single-select fields: ${singles}. ` +
418
+ 'Create it on the board, or point github.statusField at the right one.',
419
+ )
420
+ }
421
+ return { board, field }
422
+ }
423
+
424
+ async function optionFor(fieldName, optionName) {
425
+ const { board, field } = await singleSelect(fieldName)
426
+ const want = String(optionName || '').toLowerCase().trim()
427
+ const option = field.options.find((o) => String(o.name).toLowerCase().trim() === want)
428
+ if (!option) {
429
+ const names = field.options.map((o) => `"${o.name}"`).join(', ') || '(none)'
430
+ throw new GitHubRefusal(
431
+ `the board's "${field.name}" field has no option "${optionName}" — options: ${names}. ` +
432
+ 'Add the option on the board, or fix the name in github.config.json `states`.',
433
+ )
434
+ }
435
+ return { board, field, option }
436
+ }
437
+
438
+ async function readRaw(ref) {
439
+ const data = await graphql(ISSUE_QUERY, { owner, repo, number: numberOf(ref), status: statusField }, { allowMissing: true })
440
+ return (data.repository && data.repository.issue) || null
441
+ }
442
+
443
+ const adapter = {
444
+ async readIssue(ref) {
445
+ return normalizeIssue(await readRaw(ref))
446
+ },
447
+
448
+ async createIssue({ title, description, assigneeId, labels, type }) {
449
+ const raw = await rest('POST', `${repoPath}/issues`, {
450
+ body: issuePayload({ title, description, assigneeId, labels, type }, { forCreate: true }),
451
+ })
452
+ if (!raw || raw.number == null) throw new Error('GitHub returned no issue for the create')
453
+ return created(raw)
454
+ },
455
+
456
+ /**
457
+ * Create an issue and link it under `parentRef` as a sub-issue — two
458
+ * calls, because GitHub has no create-as-child. A link that fails AFTER
459
+ * the create leaves a real, unlinked issue behind, so the refusal carries
460
+ * it as `orphan` and names it: a silent orphan is exactly what a re-run
461
+ * would mint a twin of.
462
+ */
463
+ async createSubIssue(parentRef, { title, description, assigneeId, labels, type }) {
464
+ const child = await adapter.createIssue({ title, description, assigneeId, labels, type })
465
+ try {
466
+ await rest('POST', `${repoPath}/issues/${numberOf(parentRef)}/sub_issues`, {
467
+ body: { sub_issue_id: child.databaseId },
468
+ })
469
+ } catch (error) {
470
+ throw new GitHubRefusal(
471
+ `created ${child.identifier} but could not link it under ${identifierOf(numberOf(parentRef))}: ` +
472
+ `${error && error.message ? error.message : error}. Link it by hand (or close it) before pushing again.`,
473
+ { status: error && error.status, orphan: child },
474
+ )
475
+ }
476
+ return child
477
+ },
478
+
479
+ async updateIssue(ref, updates) {
480
+ const body = issuePayload(updates || {})
481
+ if (!Object.keys(body).length) return {}
482
+ return rest('PATCH', `${repoPath}/issues/${numberOf(ref)}`, { body })
483
+ },
484
+
485
+ /**
486
+ * Open or close the issue itself. `reason` is `completed` / `not_planned`
487
+ * when closing; reopening sends `reopened`, which is what GitHub records.
488
+ */
489
+ async setIssueOpen(ref, { open, reason = null }) {
490
+ const body = open ? { state: 'open', state_reason: 'reopened' } : { state: 'closed', ...(reason ? { state_reason: reason } : {}) }
491
+ return rest('PATCH', `${repoPath}/issues/${numberOf(ref)}`, { body })
492
+ },
493
+
494
+ async listSubIssues(ref) {
495
+ const raw = await restAll(`${repoPath}/issues/${numberOf(ref)}/sub_issues`)
496
+ return raw.map((s) => ({
497
+ id: String(s.number),
498
+ identifier: identifierOf(s.number),
499
+ title: s.title != null ? s.title : null,
500
+ open: s.state === 'open',
501
+ }))
502
+ },
503
+
504
+ /**
505
+ * Issues in this repo whose title contains `query` — the twin-mint guard's
506
+ * lookup. BLIND SPOT: search is eventually consistent, so an issue created
507
+ * seconds ago may not be found. The guard treats "not found" as "mint",
508
+ * which is the harmless branch only because a twin is recoverable and a
509
+ * refused push is not what the caller asked for.
510
+ */
511
+ async searchIssues({ query, limit = 50 }) {
512
+ const quoted = String(query || '').replace(/"/g, '')
513
+ const q = [`repo:${owner}/${repo}`, 'is:issue', quoted ? `in:title "${quoted}"` : null].filter(Boolean).join(' ')
514
+ const raw = await rest('GET', '/search/issues', { query: { q, per_page: Math.min(limit, PAGE) } })
515
+ return ((raw && raw.items) || []).map((i) => ({
516
+ id: String(i.number),
517
+ identifier: identifierOf(i.number),
518
+ title: i.title != null ? i.title : null,
519
+ state: null,
520
+ parent: null,
521
+ }))
522
+ },
523
+
524
+ resolveBoard,
525
+
526
+ /**
527
+ * Every issue of THIS repo that is on the board, with its Status — the
528
+ * listing `spec-sync list` shows. Found by search and each issue's own
529
+ * board item (see `REPO_ISSUES` for why not the board's `items`), so an
530
+ * issue off the board is simply absent, and other repos' items, drafts and
531
+ * PRs never appear at all. `label` narrows the search (the spec label).
532
+ *
533
+ * BLIND SPOT: search is eventually consistent, so an issue created seconds
534
+ * ago may be missing from one listing. A listing is a convenience; nothing
535
+ * decides on it.
536
+ */
537
+ async listBoardItems({ label = '' } = {}) {
538
+ if (!project) throw new GitHubRefusal('no board configured — set github.project to the board number from its URL')
539
+ const q = [`repo:${owner}/${repo}`, 'is:issue', label ? `label:"${String(label).replace(/"/g, '')}"` : null].filter(Boolean).join(' ')
540
+ const out = []
541
+ let after = null
542
+ for (let page = 0; page < MAX_PAGES; page++) {
543
+ const data = await graphql(REPO_ISSUES, { q, status: statusField, after })
544
+ const res = data.search || { nodes: [], pageInfo: {} }
545
+ for (const c of res.nodes || []) {
546
+ if (!c || c.number == null) continue
547
+ if (!c.repository || !sameLogin(c.repository.nameWithOwner, `${owner}/${repo}`)) continue
548
+ const item = boardItemOf(c)
549
+ if (!item) continue
550
+ out.push({
551
+ id: String(c.number),
552
+ identifier: identifierOf(c.number),
553
+ title: c.title != null ? c.title : null,
554
+ url: c.url || null,
555
+ open: c.state === 'OPEN',
556
+ state: item.fieldValueByName && item.fieldValueByName.name != null ? { name: item.fieldValueByName.name } : null,
557
+ parent: c.parent && c.parent.number != null ? { id: String(c.parent.number), identifier: identifierOf(c.parent.number) } : null,
558
+ })
559
+ }
560
+ if (!res.pageInfo || !res.pageInfo.hasNextPage) break
561
+ after = res.pageInfo.endCursor
562
+ }
563
+ return out.sort((a, b) => Number(a.id) - Number(b.id))
564
+ },
565
+
566
+ /**
567
+ * Open issues in this repo carrying every label in `labels` — the intake
568
+ * inbox. Pull requests come back from this endpoint too and are dropped.
569
+ */
570
+ async listIssues({ labels = [], state = 'open' } = {}) {
571
+ const query = { state }
572
+ if (labels.length) query.labels = labels.join(',')
573
+ const raw = await restAll(`${repoPath}/issues`, query)
574
+ return raw
575
+ .filter((i) => i && !i.pull_request)
576
+ .map((i) => ({
577
+ id: String(i.number),
578
+ identifier: identifierOf(i.number),
579
+ title: i.title != null ? i.title : null,
580
+ url: i.html_url || null,
581
+ open: i.state === 'open',
582
+ labels: (i.labels || []).map((l) => (typeof l === 'string' ? l : l && l.name)).filter(Boolean),
583
+ author: i.user && i.user.login ? i.user.login : null,
584
+ }))
585
+ },
586
+
587
+ /**
588
+ * The Status field's option names — what `states` validation checks the
589
+ * config against, in the shape the kit's state gate takes.
590
+ */
591
+ async listIssueStates() {
592
+ const { field } = await singleSelect(statusField)
593
+ return field.options.map((o) => ({ id: o.id, name: o.name, category: null }))
594
+ },
595
+
596
+ /**
597
+ * Put the issue on the board. `addProjectV2ItemById` returns the EXISTING
598
+ * item when the issue is already there, so this is idempotent by GitHub's
599
+ * own contract — no read is needed to avoid a duplicate.
600
+ */
601
+ async addToBoard(issueOrRef) {
602
+ const issue = issueOrRef && issueOrRef.nodeId ? issueOrRef : await adapter.readIssue(issueOrRef)
603
+ if (!issue || !issue.nodeId) throw new GitHubRefusal(`no issue ${JSON.stringify(issueOrRef)} to add to the board`)
604
+ if (issue.boardItemId) return { itemId: issue.boardItemId, added: false }
605
+ const board = await resolveBoard()
606
+ const data = await graphql(ADD_ITEM, { project: board.id, content: issue.nodeId })
607
+ const item = data.addProjectV2ItemById && data.addProjectV2ItemById.item
608
+ if (!item || !item.id) throw new GitHubRefusal(`GitHub did not return a board item for ${issue.identifier}`)
609
+ return { itemId: item.id, added: true }
610
+ },
611
+
612
+ /**
613
+ * Set a single-select field on the issue's board item by option NAME,
614
+ * adding the issue to the board first if it is not on it. `{ changed:
615
+ * false }` when the Status is already that option — the idempotent case.
616
+ * Pass a normalised issue to save the read.
617
+ */
618
+ async setFieldOption(issueOrRef, fieldName, optionName) {
619
+ const { board, field, option } = await optionFor(fieldName, optionName)
620
+ const issue = issueOrRef && issueOrRef.nodeId ? issueOrRef : await adapter.readIssue(issueOrRef)
621
+ if (!issue) throw new GitHubRefusal(`no issue ${JSON.stringify(issueOrRef)} to set "${field.name}" on`)
622
+ const isStatus = String(field.name).toLowerCase() === String(statusField).toLowerCase()
623
+ if (isStatus && issue.state && String(issue.state.name).toLowerCase() === String(option.name).toLowerCase()) {
624
+ return { changed: false }
625
+ }
626
+ const { itemId } = await adapter.addToBoard(issue)
627
+ await graphql(SET_OPTION, { project: board.id, item: itemId, field: field.id, option: option.id })
628
+ return { changed: true }
629
+ },
630
+
631
+ async setStatus(issueOrRef, optionName) {
632
+ return adapter.setFieldOption(issueOrRef, statusField, optionName)
633
+ },
634
+
635
+ /**
636
+ * Who the token is, and what it may do. `scopes` comes from the
637
+ * `X-OAuth-Scopes` header — present for classic tokens, ABSENT for
638
+ * fine-grained ones, so `null` means "cannot tell", never "no scopes".
639
+ */
640
+ async readViewer() {
641
+ const { body, headers } = await rest('GET', '/user', { withHeaders: true })
642
+ if (!body || !body.login) return null
643
+ const header = headers && typeof headers.get === 'function' ? headers.get('x-oauth-scopes') : null
644
+ return {
645
+ id: body.login,
646
+ login: body.login,
647
+ name: body.name || body.login,
648
+ email: body.email || null,
649
+ scopes: header == null ? null : header.split(',').map((s) => s.trim()).filter(Boolean),
650
+ }
651
+ },
652
+
653
+ /**
654
+ * People who can be ASSIGNED in this repo — GitHub's `assignees` list, which
655
+ * is the right set rather than "everyone": assigning anyone else is refused.
656
+ * Filtered here by login, case-insensitively; GitHub's endpoint takes no
657
+ * query. Shaped like the Linear provider's page (`{ users, nextCursor }`).
658
+ */
659
+ async searchUsers(query = '', { limit = 50 } = {}) {
660
+ const raw = await restAll(`${repoPath}/assignees`)
661
+ const want = String(query || '').toLowerCase().trim()
662
+ const users = raw
663
+ .filter((u) => u && u.login)
664
+ .filter((u) => !want || String(u.login).toLowerCase().includes(want))
665
+ .slice(0, limit)
666
+ .map((u) => ({ id: u.login, login: u.login, name: u.login, email: null, active: true }))
667
+ return { users, nextCursor: null }
668
+ },
669
+
670
+ /**
671
+ * Can `login` be assigned in this repo? GitHub answers 204 for yes and 404
672
+ * for no — a POSITIVE answer either way — so `true` / `false`. Anything
673
+ * else (a 5xx, the network) is a cannot-tell and throws, for the caller to
674
+ * route to the harmless branch.
675
+ */
676
+ async checkAssignable(login) {
677
+ const res = await send('GET', `${base}${repoPath}/assignees/${encodeURIComponent(login)}`)
678
+ if (res.status === 204) return true
679
+ if (res.status === 404) return false
680
+ throw new GitHubRefusal(`GitHub answered ${res.status} when asked whether ${login} is assignable`, { status: res.status })
681
+ },
682
+
683
+ // --- releases (the kit's release seam, `provider-kit/src/releases.js`) ---
684
+
685
+ /**
686
+ * Is the tag on GitHub? Asked before a create because GitHub, handed a
687
+ * `tag_name` it lacks, CREATES the tag at the default branch's head — a
688
+ * release pointing at a commit nobody tagged. 200 yes, 404 no; anything
689
+ * else throws (cannot tell).
690
+ */
691
+ async releaseTagExists(tag) {
692
+ const res = await send('GET', `${base}${repoPath}/git/ref/tags/${encodeURIComponent(tag)}`)
693
+ if (res.status === 200) return true
694
+ if (res.status === 404) return false
695
+ throw new GitHubRefusal(`GitHub answered ${res.status} when asked for tag ${tag}`, { status: res.status })
696
+ },
697
+
698
+ /**
699
+ * The release for a tag, or null. A 404 is GitHub positively answering
700
+ * "no release for this tag"; any other failure throws, and the kit refuses
701
+ * rather than create on a lookup it could not make.
702
+ */
703
+ async releaseFind(tag) {
704
+ const raw = await rest('GET', `${repoPath}/releases/tags/${encodeURIComponent(tag)}`, { allow404: true })
705
+ return raw ? releaseOf(raw) : null
706
+ },
707
+
708
+ async releaseCreate({ tag, name, body, prerelease = true }) {
709
+ assertBodyFits(body, `the ${tag} release`)
710
+ // `make_latest: false` while staged: a release still on its way through
711
+ // test must not become the one GitHub shows as Latest.
712
+ const raw = await rest('POST', `${repoPath}/releases`, {
713
+ body: { tag_name: tag, name, body, prerelease, make_latest: prerelease ? 'false' : 'true' },
714
+ })
715
+ return releaseOf(raw)
716
+ },
717
+
718
+ async releaseUpdate(release, { name, body }) {
719
+ assertBodyFits(body, `the ${release.tag} release`)
720
+ const raw = await rest('PATCH', `${repoPath}/releases/${release.id}`, { body: { name, body } })
721
+ Object.assign(release, releaseOf(raw) || {})
722
+ return release
723
+ },
724
+
725
+ /**
726
+ * Note the release on each issue it carries — one comment per issue, found
727
+ * again by its marker, so a CI retry adds nothing.
728
+ */
729
+ async releaseAttach(release, tickets) {
730
+ const marker = `<!-- skitterspec:released ${release.tag} -->`
731
+ let attached = 0
732
+ let already = 0
733
+ for (const t of tickets) {
734
+ const comments = await adapter.listComments(t.ref)
735
+ if (comments.some((c) => c.body.includes(marker))) {
736
+ already++
737
+ continue
738
+ }
739
+ await adapter.createComment(t.ref, `Shipped in [${release.tag}](${release.url || ''})\n\n${marker}`)
740
+ attached++
741
+ }
742
+ return { attached, already }
743
+ },
744
+
745
+ /**
746
+ * Set the board's Deployed option on every issue the release carries. The
747
+ * option is resolved before the first write, so an unknown name refuses
748
+ * with nothing changed.
749
+ */
750
+ async releaseStage(release, optionName, tickets) {
751
+ await optionFor(deployedField, optionName)
752
+ let set = 0
753
+ for (const t of tickets) {
754
+ const r = await adapter.setFieldOption(t.ref, deployedField, optionName)
755
+ if (r && r.changed !== false) set++
756
+ }
757
+ return { set }
758
+ },
759
+
760
+ async releaseComplete(release) {
761
+ const raw = await rest('PATCH', `${repoPath}/releases/${release.id}`, { body: { prerelease: false, make_latest: 'true' } })
762
+ Object.assign(release, releaseOf(raw) || {})
763
+ return release
764
+ },
765
+
766
+ async listLabels() {
767
+ const raw = await restAll(`${repoPath}/labels`)
768
+ return raw.map((l) => ({ name: l.name, color: l.color || null }))
769
+ },
770
+
771
+ async listComments(ref) {
772
+ const raw = await restAll(`${repoPath}/issues/${numberOf(ref)}/comments`)
773
+ return raw.map((c) => ({ id: String(c.id), body: c.body == null ? '' : String(c.body) }))
774
+ },
775
+
776
+ async createComment(ref, mdBody) {
777
+ assertBodyFits(mdBody, 'this comment')
778
+ const raw = await rest('POST', `${repoPath}/issues/${numberOf(ref)}/comments`, { body: { body: mdBody } })
779
+ return raw && raw.id != null ? { id: String(raw.id) } : null
780
+ },
781
+ }
782
+
783
+ return adapter
784
+ }
785
+
786
+ module.exports = { makeApiAdapter, GitHubRefusal, numberOf, identifierOf, isLimited, API_URL }