@defrex/autobuild 1.4.1 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/SPEC.md +440 -95
- package/bin/ab-dispatch-kernel.ts +1 -0
- package/docs/accounts.md +9 -0
- package/docs/agent-runtimes.md +1 -0
- package/docs/answering-blocked-builds.md +2 -1
- package/docs/architecture.md +290 -130
- package/docs/assets/headline-wide.png +0 -0
- package/docs/build-store.md +33 -3
- package/docs/cli.md +2 -1
- package/docs/configuration-overview.md +9 -0
- package/docs/configuration.md +166 -101
- package/docs/dispatcher-hosting.md +19 -3
- package/docs/dispatcher.md +9 -4
- package/docs/integration-overview.md +2 -2
- package/docs/integration-tree.md +91 -28
- package/docs/merge-policy.md +28 -9
- package/docs/operator-api.md +43 -18
- package/docs/operator-surfaces.md +1 -1
- package/docs/plugin-authoring.md +85 -8
- package/docs/remote-store-protocol.md +25 -7
- package/docs/remote-ticket-protocol.md +126 -12
- package/docs/restacking.md +20 -6
- package/docs/seams.md +2 -2
- package/docs/setup.md +19 -13
- package/docs/spec-standard.md +2 -1
- package/docs/ticket-dependencies.md +26 -8
- package/docs/ticket-migration.md +70 -7
- package/docs/ticket-sources.md +82 -5
- package/docs/tickets.md +34 -2
- package/docs/troubleshooting.md +2 -2
- package/docs/verification.md +5 -5
- package/docs/website.md +8 -0
- package/docs/workspaces.md +1 -1
- package/package.json +5 -4
- package/packages/core/src/accounts/hosted-readiness.ts +21 -0
- package/packages/core/src/cli/attention.ts +1 -0
- package/packages/core/src/cli/build-control.ts +36 -12
- package/packages/core/src/cli/connect.ts +9 -18
- package/packages/core/src/cli/context.ts +44 -0
- package/packages/core/src/cli/dashboard/configuration.ts +11 -0
- package/packages/core/src/cli/dashboard/model.ts +40 -10
- package/packages/core/src/cli/dashboard/queue.ts +21 -0
- package/packages/core/src/cli/dashboard/render.ts +40 -22
- package/packages/core/src/cli/dispatch-frontend.ts +63 -30
- package/packages/core/src/cli/dispatch-mode.ts +35 -16
- package/packages/core/src/cli/dispatch-repository-feed.ts +40 -11
- package/packages/core/src/cli/dispatch.ts +154 -47
- package/packages/core/src/cli/help.ts +59 -22
- package/packages/core/src/cli/init-hosted-accounts.ts +54 -0
- package/packages/core/src/cli/init-readiness-remote.ts +16 -3
- package/packages/core/src/cli/init-validation.ts +144 -42
- package/packages/core/src/cli/issue-links.ts +67 -0
- package/packages/core/src/cli/main.ts +32 -15
- package/packages/core/src/cli/pr-summary-publication.ts +38 -7
- package/packages/core/src/cli/publication-settlement.ts +36 -24
- package/packages/core/src/cli/repository-status.ts +201 -49
- package/packages/core/src/cli/status.ts +41 -3
- package/packages/core/src/cli/terminals.ts +37 -2
- package/packages/core/src/cli/ticket-editor.ts +20 -6
- package/packages/core/src/cli/ticket.ts +264 -46
- package/packages/core/src/cli/triage-count-sampler.ts +59 -0
- package/packages/core/src/cli/watch.ts +4 -0
- package/packages/core/src/config/live.ts +45 -4
- package/packages/core/src/config/load.ts +9 -0
- package/packages/core/src/config/pipeline-source.ts +6 -2
- package/packages/core/src/config/ready-assignee.ts +86 -0
- package/packages/core/src/config/schema.ts +164 -36
- package/packages/core/src/distribution-packaging.ts +1 -1
- package/packages/core/src/events/catalog.ts +5 -0
- package/packages/core/src/events/compatibility.ts +2 -1
- package/packages/core/src/events/payloads.ts +70 -0
- package/packages/core/src/events/policy.ts +8 -0
- package/packages/core/src/events/repository.ts +91 -28
- package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +41 -0
- package/packages/core/src/kernel/build-identity.ts +12 -0
- package/packages/core/src/kernel/change-presence.ts +139 -6
- package/packages/core/src/kernel/dispatch-capacity.ts +80 -14
- package/packages/core/src/kernel/dispatch-status.ts +10 -1
- package/packages/core/src/kernel/dispatch-upgrade.ts +104 -5
- package/packages/core/src/kernel/engine.ts +4 -2
- package/packages/core/src/kernel/finalize-pr-rejection.ts +95 -0
- package/packages/core/src/kernel/generators/repository-journals.ts +15 -1
- package/packages/core/src/kernel/harvest.ts +4 -1
- package/packages/core/src/kernel/integration-completeness.ts +104 -17
- package/packages/core/src/kernel/integration-landing.ts +17 -0
- package/packages/core/src/kernel/integration-state.ts +17 -0
- package/packages/core/src/kernel/issue-keywords.ts +202 -0
- package/packages/core/src/kernel/janitor-failure.ts +11 -0
- package/packages/core/src/kernel/kernel-git.ts +87 -0
- package/packages/core/src/kernel/landing-readiness.ts +25 -17
- package/packages/core/src/kernel/log-index.ts +1 -1
- package/packages/core/src/kernel/node-issue-links.ts +142 -0
- package/packages/core/src/kernel/node-parent.ts +6 -0
- package/packages/core/src/kernel/node-restack-transaction.ts +2 -0
- package/packages/core/src/kernel/pr-summary.ts +24 -0
- package/packages/core/src/kernel/read-deferrals.ts +75 -12
- package/packages/core/src/kernel/read-facts.ts +32 -1
- package/packages/core/src/kernel/reconcile-restack.ts +1 -1
- package/packages/core/src/kernel/reducer-registry.ts +31 -1
- package/packages/core/src/kernel/reducer.ts +90 -2
- package/packages/core/src/kernel/ticket-preparation.ts +12 -0
- package/packages/core/src/kernel/verify-budget.ts +43 -0
- package/packages/core/src/operator/index.ts +3 -1
- package/packages/core/src/operator/presentation.ts +3 -0
- package/packages/core/src/operator/protocol.ts +38 -2
- package/packages/core/src/operator/query.ts +66 -29
- package/packages/core/src/operator/registry.ts +47 -26
- package/packages/core/src/operator/tickets.ts +77 -10
- package/packages/core/src/plugin-sdk/index.ts +13 -0
- package/packages/core/src/plugins/manifest.ts +1 -1
- package/packages/core/src/plugins/registry.ts +1 -0
- package/packages/core/src/ports/forge/contract.ts +69 -0
- package/packages/core/src/ports/forge/create.ts +5 -0
- package/packages/core/src/ports/forge/fake.ts +184 -3
- package/packages/core/src/ports/forge/git-rewrite.ts +4 -2
- package/packages/core/src/ports/forge/github.ts +175 -38
- package/packages/core/src/ports/forge/local-git.ts +14 -0
- package/packages/core/src/ports/forge/readiness.ts +10 -0
- package/packages/core/src/ports/forge-failure.ts +43 -0
- package/packages/core/src/ports/runner/claude.ts +7 -1
- package/packages/core/src/ports/runner/codex.ts +7 -2
- package/packages/core/src/ports/runner/native-cli-fixture.ts +2 -1
- package/packages/core/src/ports/runner/pi.ts +7 -1
- package/packages/core/src/ports/runner/runtime.ts +3 -0
- package/packages/core/src/ports/runner/start-prompt.ts +37 -0
- package/packages/core/src/ports/tickets/contract.ts +320 -7
- package/packages/core/src/ports/tickets/create.ts +72 -17
- package/packages/core/src/ports/tickets/fake.ts +18 -0
- package/packages/core/src/ports/tickets/file-codec.ts +20 -0
- package/packages/core/src/ports/tickets/file.ts +43 -1
- package/packages/core/src/ports/tickets/github-fake.ts +1123 -0
- package/packages/core/src/ports/tickets/github-issues.ts +431 -0
- package/packages/core/src/ports/tickets/github-validators.ts +194 -0
- package/packages/core/src/ports/tickets/github.ts +2029 -0
- package/packages/core/src/ports/tickets/hosted-index.ts +34 -3
- package/packages/core/src/ports/tickets/issue-links.ts +86 -0
- package/packages/core/src/ports/tickets/lifecycle.ts +60 -4
- package/packages/core/src/ports/tickets/linear.ts +66 -6
- package/packages/core/src/ports/tickets/migration.ts +290 -68
- package/packages/core/src/ports/tickets/operations.ts +98 -12
- package/packages/core/src/ports/tickets/priority.ts +55 -0
- package/packages/core/src/ports/tickets/remote-protocol.ts +195 -29
- package/packages/core/src/ports/tickets/remote.ts +188 -13
- package/packages/core/src/ports/tickets/revision.ts +22 -1
- package/packages/core/src/ports/tickets/states.ts +43 -0
- package/packages/core/src/ports/tickets/tree.ts +58 -12
- package/packages/core/src/ports/tickets/update.ts +12 -2
- package/packages/core/src/ports/types.ts +194 -11
- package/packages/core/src/ports/workspace/commit-preservation.ts +135 -13
- package/packages/core/src/ports/workspace/git-worktree.ts +3 -1
- package/packages/core/src/ports/workspace/vercel-sandbox.ts +132 -27
- package/packages/core/src/processes/build-runner.ts +99 -21
- package/packages/core/src/processes/dispatcher.ts +1080 -533
- package/packages/core/src/processes/execution-no-progress.ts +5 -0
- package/packages/core/src/processes/harvest-runner.ts +17 -8
- package/packages/core/src/processes/harvest.ts +5 -8
- package/packages/core/src/processes/tick-publication.ts +12 -2
- package/packages/core/src/processes/ticket-scan-schedule.ts +78 -0
- package/packages/core/src/processes/workspace-preservation.ts +37 -2
- package/packages/core/src/runtime-identity.ts +10 -2
- package/packages/core/src/scenarios/harness.ts +4 -0
- package/packages/core/src/store/adapter.ts +7 -1
- package/packages/core/src/store/contract.ts +83 -2
- package/packages/core/src/store/digest.ts +32 -1
- package/packages/core/src/store/reducer-value-shapes.json +4187 -3391
- package/packages/core/src/store/remote/protocol.ts +2 -0
- package/packages/core/src/store/remote/released-clients.json +22 -0
- package/packages/core/src/store/remote/released-reducer-values/1.5.0.json +26924 -0
- package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
- package/packages/core/src/store/repo-state-events.ts +2 -0
- package/packages/core/src/store/types.ts +5 -0
- package/packages/core/src/testing/dispatch-read-budget.ts +729 -123
- package/packages/core/src/testing/index.ts +18 -1
- package/packages/core/src/testing/presence-history.ts +79 -0
- package/packages/core/src/testing/reduced-read-budget.ts +1197 -31
- package/packages/core/src/testing/upgrade-generations.ts +77 -0
- package/skills/code-review/SKILL.md +4 -3
- package/skills/finalize/SKILL.md +18 -2
- package/skills/guide/SKILL.md +382 -139
- package/skills/guide/references/accounts.md +9 -0
- package/skills/guide/references/integration-tree.md +91 -28
- package/skills/guide/references/merge-policy.md +28 -9
- package/skills/guide/references/operator-api.md +43 -18
- package/skills/guide/references/plugin-authoring.md +85 -8
- package/skills/guide/references/remote-store-protocol.md +25 -7
- package/skills/guide/references/remote-ticket-protocol.md +126 -12
- package/skills/guide/references/restacking.md +20 -6
- package/skills/guide/references/setup.md +19 -13
- package/skills/guide/references/spec-standard.md +2 -1
- package/skills/guide/references/ticket-dependencies.md +26 -8
- package/skills/guide/references/ticket-migration.md +70 -7
- package/skills/harvest-review/SKILL.md +4 -3
- package/skills/implement/SKILL.md +20 -1
- package/skills/operate/SKILL.md +103 -28
- package/skills/plan/SKILL.md +1 -1
- package/skills/reconcile/SKILL.md +5 -4
- package/skills/spec/SKILL.md +15 -2
- package/skills/tickets/SKILL.md +114 -37
- package/templates/autobuild.toml +5 -0
- package/templates/hosted-service/package.json +2 -2
|
@@ -0,0 +1,2029 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub TicketSource (SPEC §3.2, §13): the issues of the forge repository
|
|
3
|
+
* are the tickets. REST over the shared `GitHubRequest` transport seam, plus
|
|
4
|
+
* GraphQL for bounded counts and the bounded reopen check, so tests run
|
|
5
|
+
* offline against `FakeGitHubIssues`.
|
|
6
|
+
*
|
|
7
|
+
* States are `autobuild:<state>` labels and closing reasons (see
|
|
8
|
+
* `github-issues.ts`); blockers are GitHub's native issue dependencies; a
|
|
9
|
+
* node is the exact `node` label and a target is the sub-issue relation to a
|
|
10
|
+
* node's issue; assets stay in the BuildStore through the generic CLI path;
|
|
11
|
+
* there are no guarded writes. `get` carries no comment history;
|
|
12
|
+
* export and import read it explicitly through `readComments`. Import remaps
|
|
13
|
+
* every id (`allocatesIds`) and adopts committed creates by creation key.
|
|
14
|
+
*
|
|
15
|
+
* Cost (CLAUDE.md "Store read cost is a correctness property", applied to
|
|
16
|
+
* GitHub budget): the source holds no BuildStore handle. Recurring reads
|
|
17
|
+
* (the ready listing, candidates' blockers, reopen checks and parent issues,
|
|
18
|
+
* dependency reads, `get`, the label registry, and `listTargeting`'s node,
|
|
19
|
+
* sub-issue and child reads) are conditional through a durable validator
|
|
20
|
+
* store, so an unchanged repository answers a tick with 304s. Counts are one
|
|
21
|
+
* fresh, bounded GraphQL request per call and are never cached. Explicit
|
|
22
|
+
* history reads (export snapshots and comment history), the keyed-create scan, the claim read and every
|
|
23
|
+
* write store nothing.
|
|
24
|
+
* A `readyAssignee` narrows the ready read itself
|
|
25
|
+
* (its `assignee` query parameter); `"me"` costs one `GET /user` per
|
|
26
|
+
* dispatcher start, sent by `prepareReadyAssignee` before the loop and never
|
|
27
|
+
* during a tick.
|
|
28
|
+
*/
|
|
29
|
+
import { z } from 'zod'
|
|
30
|
+
import {
|
|
31
|
+
GitHubApiError,
|
|
32
|
+
githubRateLimitUntil,
|
|
33
|
+
type GitHubRequest,
|
|
34
|
+
type GitHubRequestOpts,
|
|
35
|
+
} from '../forge/github-transport'
|
|
36
|
+
import type {
|
|
37
|
+
DependencyState,
|
|
38
|
+
ExportSnapshotOptions,
|
|
39
|
+
IssueLink,
|
|
40
|
+
Ticket,
|
|
41
|
+
TicketComment,
|
|
42
|
+
TicketCreateOptions,
|
|
43
|
+
TicketCriteria,
|
|
44
|
+
TicketDraft,
|
|
45
|
+
TicketListing,
|
|
46
|
+
TicketSource,
|
|
47
|
+
TicketStateCount,
|
|
48
|
+
TicketStateInfo,
|
|
49
|
+
TicketUpdate,
|
|
50
|
+
} from '../types'
|
|
51
|
+
import { TicketSourceRateLimitError } from '../types'
|
|
52
|
+
import {
|
|
53
|
+
type CreationIntent,
|
|
54
|
+
effectiveLabels,
|
|
55
|
+
encodeCreationMarker,
|
|
56
|
+
type GitHubIssue,
|
|
57
|
+
githubIssueSchema,
|
|
58
|
+
githubLabelSchema,
|
|
59
|
+
githubTimelineNodeSchema,
|
|
60
|
+
isClosedCompleted,
|
|
61
|
+
isLinkLabel,
|
|
62
|
+
isStateLabel,
|
|
63
|
+
issueLinksOf,
|
|
64
|
+
issueState,
|
|
65
|
+
isNode,
|
|
66
|
+
labelNames,
|
|
67
|
+
lifecycleNames,
|
|
68
|
+
linkLabel,
|
|
69
|
+
linkLabelsFor,
|
|
70
|
+
mergeIssueLinks,
|
|
71
|
+
NODE_LABEL,
|
|
72
|
+
NOT_PLANNED_STATE,
|
|
73
|
+
needsReopenCheck,
|
|
74
|
+
parentOf,
|
|
75
|
+
parseIssueId,
|
|
76
|
+
type ReopenVerdict,
|
|
77
|
+
rejectedStateOf,
|
|
78
|
+
reopenVerdict,
|
|
79
|
+
representableState,
|
|
80
|
+
splitCreationMarker,
|
|
81
|
+
STATE_LABEL_PREFIX,
|
|
82
|
+
stateLabel,
|
|
83
|
+
stateLabelsOf,
|
|
84
|
+
ticketLabelsOf,
|
|
85
|
+
validCreationKey,
|
|
86
|
+
writeForState,
|
|
87
|
+
} from './github-issues'
|
|
88
|
+
import { GITHUB_READY_ASSIGNEE } from '../../config/ready-assignee'
|
|
89
|
+
import { type GitHubValidatorStore, MemoryGitHubValidatorStore } from './github-validators'
|
|
90
|
+
import { normalizeIssueLinks } from './issue-links'
|
|
91
|
+
import { holdsState, type TicketLifecycle } from './lifecycle'
|
|
92
|
+
import { ticketRevision } from './revision'
|
|
93
|
+
import {
|
|
94
|
+
matchStateNames,
|
|
95
|
+
orderStates,
|
|
96
|
+
resolveState,
|
|
97
|
+
validateStateName,
|
|
98
|
+
validateStatePurpose,
|
|
99
|
+
} from './states'
|
|
100
|
+
import { validateTicketTree } from './tree'
|
|
101
|
+
import { validateTicketUpdate } from './update'
|
|
102
|
+
|
|
103
|
+
const SOURCE = 'github ticket source'
|
|
104
|
+
const PAGE = '100'
|
|
105
|
+
/** A keyed create scans issues created since this long before the key's
|
|
106
|
+
* reservation, which covers clock skew between the caller and GitHub. */
|
|
107
|
+
export const CREATION_SCAN_SKEW_MS = 10 * 60 * 1000
|
|
108
|
+
/** Timeline window of the reopen check; GitHub's connection maximum. */
|
|
109
|
+
export const REOPEN_WINDOW = 100
|
|
110
|
+
const LABEL_COLOR = 'ededed'
|
|
111
|
+
/** Repository roles GitHub lets set issue labels. */
|
|
112
|
+
const LABEL_ROLES = ['triage', 'push', 'maintain', 'admin']
|
|
113
|
+
const STATE_LABEL_DESCRIPTION = 'Autobuild ticket state'
|
|
114
|
+
const LINK_LABEL_DESCRIPTION = 'Autobuild issue link'
|
|
115
|
+
const NODE_LABEL_DESCRIPTION = 'Autobuild integration node'
|
|
116
|
+
/** GitHub limits a label description to 100 characters. */
|
|
117
|
+
const LABEL_DESCRIPTION_MAX = 100
|
|
118
|
+
|
|
119
|
+
/** A keyed create reached the source without the key's reservation time. */
|
|
120
|
+
export class TicketCreationKeyReservationRequired extends Error {
|
|
121
|
+
constructor() {
|
|
122
|
+
super(
|
|
123
|
+
'github create: a creation key requires idempotencyKeyReservedAt (the earliest time the key could first have been used)',
|
|
124
|
+
)
|
|
125
|
+
this.name = 'TicketCreationKeyReservationRequired'
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface GitHubTicketSourceOptions {
|
|
130
|
+
transport: GitHubRequest
|
|
131
|
+
repository: { owner: string; name: string }
|
|
132
|
+
lifecycle: TicketLifecycle
|
|
133
|
+
/** Labels every ready issue must also carry; `[]` removes the gate. */
|
|
134
|
+
readyLabels: string[]
|
|
135
|
+
validators?: GitHubValidatorStore
|
|
136
|
+
now?: () => number
|
|
137
|
+
/** Init validation: the reason no credential was found, if none was. */
|
|
138
|
+
credentialMiss?: () => Promise<string | undefined>
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
interface Response {
|
|
142
|
+
json: unknown
|
|
143
|
+
link?: string
|
|
144
|
+
etag?: string
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
interface Hydrated {
|
|
148
|
+
ticket: Ticket
|
|
149
|
+
/** False when the issue must be left out of listings (no resolved state). */
|
|
150
|
+
listed: boolean
|
|
151
|
+
diagnostics: string[]
|
|
152
|
+
/** Listing-time fact: every blocker is in this repository and done. */
|
|
153
|
+
blockersResolved: boolean
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
interface HydrateOptions {
|
|
157
|
+
remember: boolean
|
|
158
|
+
etag?: string
|
|
159
|
+
/** The listing batch by number, so a parent in it needs no read. */
|
|
160
|
+
parents?: Map<number, GitHubIssue>
|
|
161
|
+
/** Parent reads that missed the batch, deduplicated within one call. */
|
|
162
|
+
parentReads?: Map<number, Promise<GitHubIssue | null>>
|
|
163
|
+
/** A target already known (a node's own sub-issue list); skips resolution. */
|
|
164
|
+
target?: string | null
|
|
165
|
+
/** False for reads that never return a target (dependency states). */
|
|
166
|
+
resolveTarget?: boolean
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
interface Blockers {
|
|
170
|
+
ids: string[]
|
|
171
|
+
resolved: boolean
|
|
172
|
+
issues: GitHubIssue[]
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function statusOf(error: unknown): number | undefined {
|
|
176
|
+
const cause = error instanceof GitHubApiError ? error : (error as { cause?: unknown })?.cause
|
|
177
|
+
return cause instanceof GitHubApiError ? cause.status : undefined
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** The API error's message and response body, for classifying a refusal. */
|
|
181
|
+
function apiDetail(error: unknown): string {
|
|
182
|
+
const cause = error instanceof GitHubApiError ? error : (error as { cause?: unknown })?.cause
|
|
183
|
+
if (!(cause instanceof GitHubApiError)) return message(error)
|
|
184
|
+
return `${cause.message} ${JSON.stringify(cause.body ?? null)}`
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function message(error: unknown): string {
|
|
188
|
+
return error instanceof Error ? error.message : String(error)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function nextPage(link: string | undefined): string | undefined {
|
|
192
|
+
if (link === undefined) return undefined
|
|
193
|
+
for (const part of link.split(',')) {
|
|
194
|
+
const match = /<([^>]+)>\s*;\s*rel="next"/.exec(part)
|
|
195
|
+
if (match) return new URL(match[1]!).searchParams.get('page') ?? undefined
|
|
196
|
+
}
|
|
197
|
+
return undefined
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The issue read's ETag as a hydration option, so a reopen check keys its
|
|
201
|
+
* verdict by this read instead of reading the issue again. */
|
|
202
|
+
function etagOf(read: { etag?: string }): { etag?: string } {
|
|
203
|
+
return read.etag !== undefined ? { etag: read.etag } : {}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function blockerList(ids: string[]): string {
|
|
207
|
+
return ids.length > 0 ? ids.map((id) => `"${id}"`).join(', ') : 'none'
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const githubCommentSchema = z
|
|
211
|
+
.object({
|
|
212
|
+
body: z.string().nullable().optional(),
|
|
213
|
+
created_at: z.string(),
|
|
214
|
+
user: z.object({ login: z.string() }).passthrough().nullable().optional(),
|
|
215
|
+
})
|
|
216
|
+
.passthrough()
|
|
217
|
+
/** Who the credential belongs to, as `prepareReadyAssignee` found it. */
|
|
218
|
+
type Viewer = { login: string } | { noUser: true } | { failed: string }
|
|
219
|
+
|
|
220
|
+
const NO_USER_ASSIGNEE =
|
|
221
|
+
'github tickets: [tickets].readyAssignee = "me" but the GitHub credential has no user (a GitHub App installation token has none) — set readyAssignee to a GitHub username'
|
|
222
|
+
|
|
223
|
+
export class GitHubTicketSource implements TicketSource {
|
|
224
|
+
readonly name = 'github'
|
|
225
|
+
readonly issueLinks = true
|
|
226
|
+
readonly allocatesIds = true
|
|
227
|
+
readonly readyAssignee = true
|
|
228
|
+
readonly integrationTree = true
|
|
229
|
+
|
|
230
|
+
private readonly transport: GitHubRequest
|
|
231
|
+
private readonly owner: string
|
|
232
|
+
private readonly repo: string
|
|
233
|
+
private readonly lifecycle: TicketLifecycle
|
|
234
|
+
private readonly readyLabels: string[]
|
|
235
|
+
private readonly validators: GitHubValidatorStore
|
|
236
|
+
private readonly now: () => number
|
|
237
|
+
private readonly credentialMiss?: () => Promise<string | undefined>
|
|
238
|
+
private cooldown?: TicketSourceRateLimitError
|
|
239
|
+
/** Exact label name (lowercased) → the one registry write in progress. */
|
|
240
|
+
private readonly pendingLabels = new Map<string, Promise<void>>()
|
|
241
|
+
/** Labels this instance created or saw created, lowercased. */
|
|
242
|
+
private readonly knownLabels = new Set<string>()
|
|
243
|
+
/** Creation markers seen by keyed creates: every issue created since
|
|
244
|
+
* `floor`, up to issue number `newest`, scanned once. Keys and numbers only. */
|
|
245
|
+
private creationScan?: { floor: number; newest: number; keys: Map<string, number> }
|
|
246
|
+
/** The credential's owner, memoized for the instance's lifetime. */
|
|
247
|
+
private viewer?: Viewer
|
|
248
|
+
|
|
249
|
+
constructor(opts: GitHubTicketSourceOptions) {
|
|
250
|
+
for (const label of opts.readyLabels) {
|
|
251
|
+
if (label.includes(','))
|
|
252
|
+
throw new Error(`${SOURCE}: readyLabels entry "${label}" contains a comma`)
|
|
253
|
+
if (isStateLabel(label) || isLinkLabel(label))
|
|
254
|
+
throw new Error(
|
|
255
|
+
`${SOURCE}: readyLabels entry "${label}" uses a reserved prefix (${STATE_LABEL_PREFIX} or autobuild-link:); states are configured with readyState`,
|
|
256
|
+
)
|
|
257
|
+
}
|
|
258
|
+
this.transport = opts.transport
|
|
259
|
+
this.owner = opts.repository.owner
|
|
260
|
+
this.repo = opts.repository.name
|
|
261
|
+
this.lifecycle = opts.lifecycle
|
|
262
|
+
this.readyLabels = [...opts.readyLabels]
|
|
263
|
+
this.validators = opts.validators ?? new MemoryGitHubValidatorStore()
|
|
264
|
+
this.now = opts.now ?? Date.now
|
|
265
|
+
if (opts.credentialMiss !== undefined) this.credentialMiss = opts.credentialMiss
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
private get fullName(): string {
|
|
269
|
+
return `${this.owner}/${this.repo}`
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
private path(rest = ''): string {
|
|
273
|
+
return `repos/${this.owner}/${this.repo}${rest}`
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// ── Transport ─────────────────────────────────────────────────────────────
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* One request. A remembered GET sends the saved ETag and answers a 304 from
|
|
280
|
+
* the saved JSON. 404 and 410 are `null` when `missing` is set. Rate limits
|
|
281
|
+
* become a cooldown that refuses every request until the reset; nothing
|
|
282
|
+
* ever falls back to a broader read.
|
|
283
|
+
*/
|
|
284
|
+
private async request(
|
|
285
|
+
operation: string,
|
|
286
|
+
method: string,
|
|
287
|
+
path: string,
|
|
288
|
+
opts: {
|
|
289
|
+
query?: Record<string, string>
|
|
290
|
+
body?: unknown
|
|
291
|
+
remember?: boolean
|
|
292
|
+
missing?: boolean
|
|
293
|
+
} = {},
|
|
294
|
+
): Promise<Response | null> {
|
|
295
|
+
if (this.cooldown !== undefined) {
|
|
296
|
+
if (this.now() < this.cooldown.resetAt) throw this.cooldown
|
|
297
|
+
this.cooldown = undefined
|
|
298
|
+
}
|
|
299
|
+
const remember = opts.remember === true && method === 'GET'
|
|
300
|
+
const key = remember
|
|
301
|
+
? `GET ${path}?${new URLSearchParams(
|
|
302
|
+
Object.entries(opts.query ?? {}).sort(([a], [b]) => a.localeCompare(b)),
|
|
303
|
+
).toString()}`
|
|
304
|
+
: undefined
|
|
305
|
+
const saved = key === undefined ? undefined : await this.validators.get(key)
|
|
306
|
+
const request: GitHubRequestOpts = {
|
|
307
|
+
...(opts.query !== undefined ? { query: opts.query } : {}),
|
|
308
|
+
...(opts.body !== undefined ? { body: opts.body } : {}),
|
|
309
|
+
...(saved !== undefined ? { headers: { 'If-None-Match': saved.etag } } : {}),
|
|
310
|
+
}
|
|
311
|
+
let response: Awaited<ReturnType<GitHubRequest>>
|
|
312
|
+
try {
|
|
313
|
+
response = await this.transport(method, path, request)
|
|
314
|
+
} catch (error) {
|
|
315
|
+
this.rateLimited(error)
|
|
316
|
+
const status = statusOf(error)
|
|
317
|
+
if (opts.missing && (status === 404 || status === 410)) return null
|
|
318
|
+
throw new Error(`github ${operation}: ${message(error)}`, { cause: error })
|
|
319
|
+
}
|
|
320
|
+
if (response.status === 304 && saved !== undefined && key !== undefined) {
|
|
321
|
+
await this.validators.touch(key)
|
|
322
|
+
return {
|
|
323
|
+
json: saved.json,
|
|
324
|
+
etag: saved.etag,
|
|
325
|
+
...(saved.link !== undefined ? { link: saved.link } : {}),
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
const etag = response.headers.etag
|
|
329
|
+
const link = response.headers.link
|
|
330
|
+
if (key !== undefined && etag !== undefined)
|
|
331
|
+
await this.validators.set(key, {
|
|
332
|
+
etag,
|
|
333
|
+
json: response.json,
|
|
334
|
+
...(link !== undefined ? { link } : {}),
|
|
335
|
+
})
|
|
336
|
+
return {
|
|
337
|
+
json: response.json,
|
|
338
|
+
...(etag !== undefined ? { etag } : {}),
|
|
339
|
+
...(link !== undefined ? { link } : {}),
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
private async must(
|
|
344
|
+
operation: string,
|
|
345
|
+
method: string,
|
|
346
|
+
path: string,
|
|
347
|
+
opts: { query?: Record<string, string>; body?: unknown; remember?: boolean } = {},
|
|
348
|
+
): Promise<Response> {
|
|
349
|
+
return (await this.request(operation, method, path, opts)) as Response
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Record and throw a documented rate limit; anything else returns. */
|
|
353
|
+
private rateLimited(error: unknown): void {
|
|
354
|
+
const resetAt = githubRateLimitUntil(error, this.now())
|
|
355
|
+
if (resetAt === undefined) return
|
|
356
|
+
this.cooldown = new TicketSourceRateLimitError('github', Date.parse(resetAt))
|
|
357
|
+
throw this.cooldown
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
private async graphql<T>(
|
|
361
|
+
operation: string,
|
|
362
|
+
query: string,
|
|
363
|
+
variables: Record<string, unknown>,
|
|
364
|
+
): Promise<T> {
|
|
365
|
+
const response = await this.must(operation, 'POST', 'graphql', { body: { query, variables } })
|
|
366
|
+
const payload = (response.json ?? {}) as {
|
|
367
|
+
data?: T | null
|
|
368
|
+
errors?: Array<{ message?: string; type?: string }>
|
|
369
|
+
}
|
|
370
|
+
if (Array.isArray(payload.errors) && payload.errors.length > 0) {
|
|
371
|
+
const failure = new GitHubApiError(
|
|
372
|
+
200,
|
|
373
|
+
payload.errors.map((e) => e.message ?? 'GraphQL error').join('; '),
|
|
374
|
+
payload,
|
|
375
|
+
)
|
|
376
|
+
this.rateLimited(failure)
|
|
377
|
+
throw new Error(`github ${operation}: GraphQL errors — ${failure.message}`, {
|
|
378
|
+
cause: failure,
|
|
379
|
+
})
|
|
380
|
+
}
|
|
381
|
+
if (payload.data === undefined || payload.data === null)
|
|
382
|
+
throw new Error(`github ${operation}: response has no data`)
|
|
383
|
+
return payload.data
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
private parseIssue(operation: string, json: unknown): GitHubIssue {
|
|
387
|
+
const parsed = githubIssueSchema.safeParse(json)
|
|
388
|
+
if (!parsed.success)
|
|
389
|
+
throw new Error(`github ${operation}: unexpected issue shape — ${parsed.error.message}`)
|
|
390
|
+
return parsed.data
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
private async readIssue(
|
|
394
|
+
operation: string,
|
|
395
|
+
number: number,
|
|
396
|
+
remember: boolean,
|
|
397
|
+
): Promise<{ issue: GitHubIssue; etag?: string } | null> {
|
|
398
|
+
const response = await this.request(operation, 'GET', this.path(`/issues/${number}`), {
|
|
399
|
+
remember,
|
|
400
|
+
missing: true,
|
|
401
|
+
})
|
|
402
|
+
if (response === null) return null
|
|
403
|
+
const issue = this.parseIssue(operation, response.json)
|
|
404
|
+
if (issue.pull_request !== undefined) return null
|
|
405
|
+
// A transferred issue answers 301 and the transport follows it, so the
|
|
406
|
+
// body can be another repository's issue under another number. It is no
|
|
407
|
+
// longer a ticket here: callers see an unknown ticket and write nothing.
|
|
408
|
+
if (!this.isLocalIssue(issue, number)) return null
|
|
409
|
+
return { issue, ...(response.etag !== undefined ? { etag: response.etag } : {}) }
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Every issue a listing query matches, in GitHub order, PRs skipped. */
|
|
413
|
+
private async listIssues(
|
|
414
|
+
operation: string,
|
|
415
|
+
query: Record<string, string>,
|
|
416
|
+
remember: boolean,
|
|
417
|
+
): Promise<GitHubIssue[]> {
|
|
418
|
+
const issues: GitHubIssue[] = []
|
|
419
|
+
let page: string | undefined = '1'
|
|
420
|
+
while (page !== undefined) {
|
|
421
|
+
const response = await this.must(operation, 'GET', this.path('/issues'), {
|
|
422
|
+
query: { ...query, per_page: PAGE, page },
|
|
423
|
+
remember,
|
|
424
|
+
})
|
|
425
|
+
for (const json of z.array(z.unknown()).parse(response.json)) {
|
|
426
|
+
const issue = this.parseIssue(operation, json)
|
|
427
|
+
if (issue.pull_request === undefined) issues.push(issue)
|
|
428
|
+
}
|
|
429
|
+
page = nextPage(response.link)
|
|
430
|
+
}
|
|
431
|
+
return issues
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
private async patchIssue(
|
|
435
|
+
operation: string,
|
|
436
|
+
number: number,
|
|
437
|
+
body: Record<string, unknown>,
|
|
438
|
+
): Promise<GitHubIssue> {
|
|
439
|
+
const response = await this.request(operation, 'PATCH', this.path(`/issues/${number}`), {
|
|
440
|
+
body,
|
|
441
|
+
missing: true,
|
|
442
|
+
})
|
|
443
|
+
if (response === null) throw new Error(`github ${operation}: unknown ticket "${number}"`)
|
|
444
|
+
const issue = this.parseIssue(operation, response.json)
|
|
445
|
+
// Without push access GitHub answers a label change with success and
|
|
446
|
+
// keeps the old labels, so a write is applied only if they came back.
|
|
447
|
+
if (Array.isArray(body.labels)) {
|
|
448
|
+
const wanted = new Set((body.labels as string[]).map((name) => name.toLowerCase()))
|
|
449
|
+
const held = new Set(labelNames(issue).map((name) => name.toLowerCase()))
|
|
450
|
+
if (wanted.size !== held.size || [...wanted].some((name) => !held.has(name)))
|
|
451
|
+
throw new Error(
|
|
452
|
+
`github ${operation}: token lacks push access; label changes were dropped on #${number} (${issue.html_url})`,
|
|
453
|
+
)
|
|
454
|
+
}
|
|
455
|
+
return issue
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// ── Labels ────────────────────────────────────────────────────────────────
|
|
459
|
+
|
|
460
|
+
/** The repository's labels through the remembered conditional read. Grows
|
|
461
|
+
* with label count, so only explicit state discovery and the unknown-state
|
|
462
|
+
* refusal call it; recurring writes look labels up by exact name. */
|
|
463
|
+
private async labelRegistry(): Promise<Array<{ name: string; description?: string }>> {
|
|
464
|
+
const labels: Array<{ name: string; description?: string }> = []
|
|
465
|
+
let page: string | undefined = '1'
|
|
466
|
+
while (page !== undefined) {
|
|
467
|
+
const response = await this.must('labels', 'GET', this.path('/labels'), {
|
|
468
|
+
query: { per_page: PAGE, page },
|
|
469
|
+
remember: true,
|
|
470
|
+
})
|
|
471
|
+
for (const json of z.array(z.unknown()).parse(response.json)) {
|
|
472
|
+
const label = githubLabelSchema.parse(json)
|
|
473
|
+
labels.push({
|
|
474
|
+
name: label.name,
|
|
475
|
+
...(label.description ? { description: label.description } : {}),
|
|
476
|
+
})
|
|
477
|
+
}
|
|
478
|
+
page = nextPage(response.link)
|
|
479
|
+
}
|
|
480
|
+
for (const label of labels) this.knownLabels.add(label.name.toLowerCase())
|
|
481
|
+
return labels
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** One label by exact name (GitHub matches it ignoring case), or `null`. */
|
|
485
|
+
private async readLabel(
|
|
486
|
+
operation: string,
|
|
487
|
+
name: string,
|
|
488
|
+
remember: boolean,
|
|
489
|
+
): Promise<{ name: string } | null> {
|
|
490
|
+
const response = await this.request(
|
|
491
|
+
operation,
|
|
492
|
+
'GET',
|
|
493
|
+
this.path(`/labels/${encodeURIComponent(name)}`),
|
|
494
|
+
{ remember, missing: true },
|
|
495
|
+
)
|
|
496
|
+
if (response === null) return null
|
|
497
|
+
const label = githubLabelSchema.parse(response.json)
|
|
498
|
+
this.knownLabels.add(label.name.toLowerCase())
|
|
499
|
+
return { name: label.name }
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** Create every missing label, one exact lookup each; the registry is never
|
|
503
|
+
* listed, so the cost follows the names asked for, not the label count. */
|
|
504
|
+
private async ensureLabels(operation: string, names: readonly string[]): Promise<void> {
|
|
505
|
+
const missing = [...new Set(names.map((name) => name.toLowerCase()))]
|
|
506
|
+
.filter((key) => !this.knownLabels.has(key))
|
|
507
|
+
.map((key) => names.find((name) => name.toLowerCase() === key)!)
|
|
508
|
+
await Promise.all(
|
|
509
|
+
missing.map(async (name) => {
|
|
510
|
+
if ((await this.readLabel(operation, name, true)) === null)
|
|
511
|
+
await this.createLabel(operation, name)
|
|
512
|
+
}),
|
|
513
|
+
)
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
private createLabel(operation: string, name: string, description?: string): Promise<void> {
|
|
517
|
+
const key = name.toLowerCase()
|
|
518
|
+
const pending = this.pendingLabels.get(key)
|
|
519
|
+
if (pending !== undefined) return pending
|
|
520
|
+
const write = (async () => {
|
|
521
|
+
try {
|
|
522
|
+
await this.must(operation, 'POST', this.path('/labels'), {
|
|
523
|
+
body: {
|
|
524
|
+
name,
|
|
525
|
+
color: LABEL_COLOR,
|
|
526
|
+
description:
|
|
527
|
+
description ??
|
|
528
|
+
(isStateLabel(name)
|
|
529
|
+
? STATE_LABEL_DESCRIPTION
|
|
530
|
+
: isLinkLabel(name)
|
|
531
|
+
? LINK_LABEL_DESCRIPTION
|
|
532
|
+
: ''),
|
|
533
|
+
},
|
|
534
|
+
})
|
|
535
|
+
} catch (error) {
|
|
536
|
+
// A 422 is success only when the label now reads back: someone else
|
|
537
|
+
// created it between the lookup and the write.
|
|
538
|
+
if (statusOf(error) !== 422 || (await this.readLabel(operation, name, false)) === null)
|
|
539
|
+
throw error
|
|
540
|
+
}
|
|
541
|
+
this.knownLabels.add(key)
|
|
542
|
+
})()
|
|
543
|
+
this.pendingLabels.set(key, write)
|
|
544
|
+
return write.finally(() => this.pendingLabels.delete(key))
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
private refuseManagedLabels(operation: string, labels: readonly string[]): void {
|
|
548
|
+
const managed = labels.filter((label) => isStateLabel(label) || isLinkLabel(label))
|
|
549
|
+
if (managed.length > 0)
|
|
550
|
+
throw new Error(
|
|
551
|
+
`github ${operation}: ${managed.map((label) => `"${label}"`).join(', ')} ${managed.length === 1 ? 'is a' : 'are'} managed label${managed.length === 1 ? '' : 's'}; move tickets with \`ab ticket move\` and set links with --issues — nothing was written`,
|
|
552
|
+
)
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// ── State names ───────────────────────────────────────────────────────────
|
|
556
|
+
|
|
557
|
+
/** Count-free state names: the configured lifecycle, `not-planned` without
|
|
558
|
+
* a rejected role, then every `autobuild:` label from the remembered label
|
|
559
|
+
* registry. Never sends GraphQL or search. */
|
|
560
|
+
private async stateNames(): Promise<string[]> {
|
|
561
|
+
const names = this.configuredStates()
|
|
562
|
+
for (const label of await this.labelRegistry()) {
|
|
563
|
+
if (!isStateLabel(label.name)) continue
|
|
564
|
+
const name = label.name.slice(STATE_LABEL_PREFIX.length)
|
|
565
|
+
if (!names.some((known) => holdsState(known, name))) names.push(name)
|
|
566
|
+
}
|
|
567
|
+
return names
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
private configuredStates(): string[] {
|
|
571
|
+
const names = lifecycleNames(this.lifecycle)
|
|
572
|
+
if (this.lifecycle.rejected === undefined) names.push(NOT_PLANNED_STATE)
|
|
573
|
+
return names
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** Resolve a write's target state without listing the label registry: a
|
|
577
|
+
* configured state matches by name, any other by one exact label lookup.
|
|
578
|
+
* Only an unknown state lists the registry, to name the known states. */
|
|
579
|
+
private async resolveTarget(operation: string, state: string): Promise<string> {
|
|
580
|
+
const configured = this.configuredStates()
|
|
581
|
+
if (configured.some((known) => holdsState(known, state)))
|
|
582
|
+
return resolveState(state, configured, SOURCE)
|
|
583
|
+
const label = state === '' ? null : await this.readLabel(operation, stateLabel(state), true)
|
|
584
|
+
if (label !== null && isStateLabel(label.name))
|
|
585
|
+
return label.name.slice(STATE_LABEL_PREFIX.length)
|
|
586
|
+
return resolveState(state, await this.stateNames(), SOURCE)
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
private lifecycleOrder(): string[] {
|
|
590
|
+
return [
|
|
591
|
+
this.lifecycle.triage,
|
|
592
|
+
this.lifecycle.ready,
|
|
593
|
+
this.lifecycle.doing,
|
|
594
|
+
this.lifecycle.done,
|
|
595
|
+
...(this.lifecycle.backlog !== undefined ? [this.lifecycle.backlog] : []),
|
|
596
|
+
rejectedStateOf(this.lifecycle),
|
|
597
|
+
]
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// ── Hydration ─────────────────────────────────────────────────────────────
|
|
601
|
+
|
|
602
|
+
/** One bounded GraphQL timeline read decides whether a reopened issue's
|
|
603
|
+
* state label predates the reopen; the verdict is saved keyed by the
|
|
604
|
+
* issue's ETag, so an unchanged issue never asks again. */
|
|
605
|
+
private async reopenCheck(
|
|
606
|
+
issue: GitHubIssue,
|
|
607
|
+
remember: boolean,
|
|
608
|
+
etag?: string,
|
|
609
|
+
): Promise<ReopenVerdict> {
|
|
610
|
+
let tag = etag
|
|
611
|
+
if (tag === undefined) {
|
|
612
|
+
const read = await this.request('reopen check', 'GET', this.path(`/issues/${issue.number}`), {
|
|
613
|
+
remember,
|
|
614
|
+
missing: true,
|
|
615
|
+
})
|
|
616
|
+
tag = read?.etag
|
|
617
|
+
}
|
|
618
|
+
const key = `reopen-verdict:${issue.number}`
|
|
619
|
+
const saved = tag === undefined ? undefined : await this.validators.get(key)
|
|
620
|
+
if (
|
|
621
|
+
saved !== undefined &&
|
|
622
|
+
saved.etag === tag &&
|
|
623
|
+
(saved.json === 'fresh' || saved.json === 'stale' || saved.json === 'undecidable')
|
|
624
|
+
) {
|
|
625
|
+
await this.validators.touch(key)
|
|
626
|
+
return saved.json
|
|
627
|
+
}
|
|
628
|
+
const data = await this.graphql<{
|
|
629
|
+
repository: { issue: { timelineItems: { nodes: unknown[] } } | null } | null
|
|
630
|
+
}>(
|
|
631
|
+
'reopen check',
|
|
632
|
+
`query ReopenCheck($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { timelineItems(last: ${REOPEN_WINDOW}, itemTypes: [REOPENED_EVENT, LABELED_EVENT]) { nodes { __typename ... on LabeledEvent { label { name } } } } } } }`,
|
|
633
|
+
{ owner: this.owner, name: this.repo, number: issue.number },
|
|
634
|
+
)
|
|
635
|
+
const nodes = z
|
|
636
|
+
.array(githubTimelineNodeSchema)
|
|
637
|
+
.parse(data.repository?.issue?.timelineItems.nodes ?? [])
|
|
638
|
+
const verdict = reopenVerdict(nodes, stateLabelsOf(issue)[0]!)
|
|
639
|
+
if (tag !== undefined && remember) await this.validators.set(key, { etag: tag, json: verdict })
|
|
640
|
+
return verdict
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** Strip a stale pre-reopen state label. Best-effort: only a rate limit
|
|
644
|
+
* fails the read. */
|
|
645
|
+
private async heal(issue: GitHubIssue): Promise<void> {
|
|
646
|
+
try {
|
|
647
|
+
await this.patchIssue('heal', issue.number, {
|
|
648
|
+
labels: labelNames(issue).filter((name) => !isStateLabel(name)),
|
|
649
|
+
})
|
|
650
|
+
} catch (error) {
|
|
651
|
+
if (error instanceof TicketSourceRateLimitError) throw error
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
private async blockers(issue: GitHubIssue, remember: boolean): Promise<Blockers> {
|
|
656
|
+
const summary = issue.issue_dependencies_summary
|
|
657
|
+
const total = summary?.total_blocked_by ?? summary?.blocked_by
|
|
658
|
+
if (total === 0) return { ids: [], resolved: true, issues: [] }
|
|
659
|
+
const issues: GitHubIssue[] = []
|
|
660
|
+
let page: string | undefined = '1'
|
|
661
|
+
while (page !== undefined) {
|
|
662
|
+
const response = await this.must(
|
|
663
|
+
'blockers',
|
|
664
|
+
'GET',
|
|
665
|
+
this.path(`/issues/${issue.number}/dependencies/blocked_by`),
|
|
666
|
+
{ query: { per_page: PAGE, page }, remember },
|
|
667
|
+
)
|
|
668
|
+
for (const json of z.array(z.unknown()).parse(response.json))
|
|
669
|
+
issues.push(this.parseIssue('blockers', json))
|
|
670
|
+
page = nextPage(response.link)
|
|
671
|
+
}
|
|
672
|
+
const ids: string[] = []
|
|
673
|
+
let resolved = true
|
|
674
|
+
for (const blocker of issues) {
|
|
675
|
+
const repo = this.repositoryOf(blocker)
|
|
676
|
+
const local = repo === undefined || repo.toLowerCase() === this.fullName.toLowerCase()
|
|
677
|
+
ids.push(local ? String(blocker.number) : `${repo}#${blocker.number}`)
|
|
678
|
+
if (!local || !isClosedCompleted(blocker)) resolved = false
|
|
679
|
+
}
|
|
680
|
+
return { ids: [...new Set(ids)], resolved, issues }
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/** Whether `issue` is issue `number` of the configured repository. */
|
|
684
|
+
private isLocalIssue(issue: GitHubIssue, number: number): boolean {
|
|
685
|
+
if (issue.number !== number) return false
|
|
686
|
+
const repo = this.repositoryOf(issue)
|
|
687
|
+
return repo === undefined || repo.toLowerCase() === this.fullName.toLowerCase()
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
private repositoryOf(issue: GitHubIssue): string | undefined {
|
|
691
|
+
const match = /\/repos\/([^/]+\/[^/]+)$/.exec(issue.repository_url ?? '')
|
|
692
|
+
return match?.[1]
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/** The number of the issue's parent when it is in this repository. */
|
|
696
|
+
private localParent(issue: GitHubIssue): number | undefined {
|
|
697
|
+
const parent = parentOf(issue)
|
|
698
|
+
if (parent === undefined || parent.repo.toLowerCase() !== this.fullName.toLowerCase())
|
|
699
|
+
return undefined
|
|
700
|
+
return parent.number
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
private isLocalChild(issue: GitHubIssue): boolean {
|
|
704
|
+
const repo = this.repositoryOf(issue)
|
|
705
|
+
return (
|
|
706
|
+
issue.pull_request === undefined &&
|
|
707
|
+
(repo === undefined || repo.toLowerCase() === this.fullName.toLowerCase())
|
|
708
|
+
)
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* A ticket's target: its local parent issue, only when that parent carries
|
|
713
|
+
* the exact `node` label. Any other parent (a non-node, another
|
|
714
|
+
* repository's issue, a transferred or deleted one) is grouping. The
|
|
715
|
+
* parent's label is read from the parent itself, because relabelling it
|
|
716
|
+
* leaves the child's own ETag unchanged.
|
|
717
|
+
*/
|
|
718
|
+
private async targetOf(issue: GitHubIssue, opts: HydrateOptions): Promise<string | undefined> {
|
|
719
|
+
if (opts.target !== undefined) return opts.target ?? undefined
|
|
720
|
+
if (opts.resolveTarget === false) return undefined
|
|
721
|
+
const number = this.localParent(issue)
|
|
722
|
+
if (number === undefined) return undefined
|
|
723
|
+
let parent: GitHubIssue | null | undefined = opts.parents?.get(number)
|
|
724
|
+
if (parent === undefined) {
|
|
725
|
+
const reads = opts.parentReads ?? new Map<number, Promise<GitHubIssue | null>>()
|
|
726
|
+
let read = reads.get(number)
|
|
727
|
+
if (read === undefined) {
|
|
728
|
+
read = this.readIssue('parent', number, opts.remember).then((r) => r?.issue ?? null)
|
|
729
|
+
reads.set(number, read)
|
|
730
|
+
}
|
|
731
|
+
parent = await read
|
|
732
|
+
}
|
|
733
|
+
return parent !== null && isNode(parent) ? String(number) : undefined
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
private async hydrate(issue: GitHubIssue, opts: HydrateOptions): Promise<Hydrated> {
|
|
737
|
+
const diagnostics: string[] = []
|
|
738
|
+
const n = issue.number
|
|
739
|
+
const links = issueLinksOf(issue)
|
|
740
|
+
for (const name of links.invalid)
|
|
741
|
+
diagnostics.push(
|
|
742
|
+
`github #${n}: ignoring malformed issue link label "${name}" — expected autobuild-link:closes #<n> or autobuild-link:refs #<n>`,
|
|
743
|
+
)
|
|
744
|
+
let current = issue
|
|
745
|
+
let state: string | undefined
|
|
746
|
+
const read = issueState(issue, this.lifecycle)
|
|
747
|
+
if ('malformed' in read) {
|
|
748
|
+
diagnostics.push(
|
|
749
|
+
`github #${n}: has ${read.malformed.length} state labels (${read.malformed.join(', ')}); a ticket holds one state — remove all but one`,
|
|
750
|
+
)
|
|
751
|
+
} else {
|
|
752
|
+
state = read.state
|
|
753
|
+
if (needsReopenCheck(issue)) {
|
|
754
|
+
const verdict = await this.reopenCheck(issue, opts.remember, opts.etag)
|
|
755
|
+
if (verdict === 'stale') {
|
|
756
|
+
await this.heal(issue)
|
|
757
|
+
current = {
|
|
758
|
+
...issue,
|
|
759
|
+
labels: labelNames(issue).filter((name) => !isStateLabel(name)),
|
|
760
|
+
}
|
|
761
|
+
state = this.lifecycle.triage
|
|
762
|
+
} else if (verdict === 'undecidable') {
|
|
763
|
+
diagnostics.push(
|
|
764
|
+
`github #${n}: reopened with ${stateLabelsOf(issue)[0]}, but neither the reopen nor that label's event is among its last ${REOPEN_WINDOW} label or reopen events; remove and re-add the label`,
|
|
765
|
+
)
|
|
766
|
+
state = undefined
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
const blockers = await this.blockers(issue, opts.remember)
|
|
771
|
+
const target = await this.targetOf(issue, opts)
|
|
772
|
+
return {
|
|
773
|
+
ticket: this.toTicket(current, state, blockers.ids, links.links, target),
|
|
774
|
+
listed: state !== undefined,
|
|
775
|
+
diagnostics,
|
|
776
|
+
blockersResolved: blockers.resolved,
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
private toTicket(
|
|
781
|
+
issue: GitHubIssue,
|
|
782
|
+
state: string | undefined,
|
|
783
|
+
blockedBy: string[],
|
|
784
|
+
issueLinks: IssueLink[],
|
|
785
|
+
target: string | undefined,
|
|
786
|
+
): Ticket {
|
|
787
|
+
const { body, marker } = splitCreationMarker(issue.body)
|
|
788
|
+
const ticket: Ticket = {
|
|
789
|
+
kind: isNode(issue) ? 'node' : 'work',
|
|
790
|
+
...(target !== undefined ? { target } : {}),
|
|
791
|
+
revision: '',
|
|
792
|
+
ref: { source: this.name, id: String(issue.number), url: issue.html_url, title: issue.title },
|
|
793
|
+
...(marker !== undefined ? { creationKey: marker.key } : {}),
|
|
794
|
+
title: issue.title,
|
|
795
|
+
body,
|
|
796
|
+
...(state !== undefined ? { state } : {}),
|
|
797
|
+
resolved: state !== undefined && isClosedCompleted(issue),
|
|
798
|
+
labels: ticketLabelsOf(issue),
|
|
799
|
+
...(blockedBy.length > 0 ? { blockedBy } : {}),
|
|
800
|
+
issueLinks,
|
|
801
|
+
}
|
|
802
|
+
ticket.revision = ticketRevision(ticket)
|
|
803
|
+
return ticket
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// ── Reads ─────────────────────────────────────────────────────────────────
|
|
807
|
+
|
|
808
|
+
async get(id: string): Promise<Ticket | null> {
|
|
809
|
+
const number = parseIssueId(id)
|
|
810
|
+
if (number === null) return null
|
|
811
|
+
const read = await this.readIssue('get', number, true)
|
|
812
|
+
if (read === null) return null
|
|
813
|
+
return (await this.hydrate(read.issue, { remember: true, ...etagOf(read) })).ticket
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// ── Export and import ─────────────────────────────────────────────────────
|
|
817
|
+
|
|
818
|
+
/** Comment history, oldest first, through GitHub's "List issue comments"
|
|
819
|
+
* route. An explicit history read for export and import only: stores
|
|
820
|
+
* nothing and never runs on a recurring path. */
|
|
821
|
+
async readComments(id: string): Promise<TicketComment[] | null> {
|
|
822
|
+
const number = parseIssueId(id)
|
|
823
|
+
if (number === null) return null
|
|
824
|
+
if ((await this.readIssue('comments', number, false)) === null) return null
|
|
825
|
+
return this.listComments(number)
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/** One issue's comment pages; `null` when the issue is gone. */
|
|
829
|
+
private async listComments(number: number): Promise<TicketComment[] | null> {
|
|
830
|
+
const comments: TicketComment[] = []
|
|
831
|
+
let page: string | undefined = '1'
|
|
832
|
+
while (page !== undefined) {
|
|
833
|
+
const response = await this.request(
|
|
834
|
+
'comments',
|
|
835
|
+
'GET',
|
|
836
|
+
this.path(`/issues/${number}/comments`),
|
|
837
|
+
{ query: { per_page: PAGE, page }, missing: true },
|
|
838
|
+
)
|
|
839
|
+
if (response === null) return null
|
|
840
|
+
for (const json of z.array(z.unknown()).parse(response.json)) {
|
|
841
|
+
const comment = githubCommentSchema.parse(json)
|
|
842
|
+
comments.push({
|
|
843
|
+
body: comment.body ?? '',
|
|
844
|
+
createdAt: comment.created_at,
|
|
845
|
+
...(comment.user?.login ? { author: comment.user.login } : {}),
|
|
846
|
+
})
|
|
847
|
+
}
|
|
848
|
+
page = nextPage(response.link)
|
|
849
|
+
}
|
|
850
|
+
return comments
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/** Every issue, closed included, with blockers, link labels and comment
|
|
854
|
+
* history. Unremembered; an issue that cannot be read as a ticket fails
|
|
855
|
+
* the export rather than leaving it out. */
|
|
856
|
+
async readExportSnapshot(opts: ExportSnapshotOptions = {}): Promise<Ticket[]> {
|
|
857
|
+
opts.signal?.throwIfAborted()
|
|
858
|
+
const issues = await this.listIssues('export', { state: 'all' }, false)
|
|
859
|
+
const tickets: Ticket[] = []
|
|
860
|
+
const diagnostics: string[] = []
|
|
861
|
+
for (const issue of issues) {
|
|
862
|
+
opts.signal?.throwIfAborted()
|
|
863
|
+
const hydrated = await this.hydrate(issue, { remember: false })
|
|
864
|
+
diagnostics.push(...hydrated.diagnostics)
|
|
865
|
+
if (!hydrated.listed && hydrated.diagnostics.length === 0)
|
|
866
|
+
diagnostics.push(`github #${issue.number}: has no readable state`)
|
|
867
|
+
if (diagnostics.length > 0) continue
|
|
868
|
+
opts.signal?.throwIfAborted()
|
|
869
|
+
const comments =
|
|
870
|
+
(issue as { comments?: unknown }).comments === 0
|
|
871
|
+
? []
|
|
872
|
+
: await this.listComments(issue.number)
|
|
873
|
+
if (comments === null) throw new Error(`ticket disappeared: ${issue.number}`)
|
|
874
|
+
tickets.push({ ...hydrated.ticket, comments })
|
|
875
|
+
opts.progress?.({ completed: tickets.length, total: issues.length })
|
|
876
|
+
}
|
|
877
|
+
if (diagnostics.length > 0)
|
|
878
|
+
throw new Error(`incomplete ticket scan:\n${[...new Set(diagnostics)].join('\n')}`)
|
|
879
|
+
return tickets
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/** What an import would refuse, all at once and before any write: states
|
|
883
|
+
* GitHub cannot hold as `autobuild:` labels or a closing reason, labels
|
|
884
|
+
* that collide with the managed prefixes, and creation keys the marker
|
|
885
|
+
* cannot carry. */
|
|
886
|
+
async importProblems(input: {
|
|
887
|
+
states: string[]
|
|
888
|
+
labels: string[]
|
|
889
|
+
creationKeys: string[]
|
|
890
|
+
}): Promise<string[]> {
|
|
891
|
+
const problems: string[] = []
|
|
892
|
+
const configured = lifecycleNames(this.lifecycle)
|
|
893
|
+
for (const state of input.states) {
|
|
894
|
+
if (this.lifecycle.rejected === undefined && holdsState(state, NOT_PLANNED_STATE))
|
|
895
|
+
problems.push(
|
|
896
|
+
`state "${state}": closed-as-not-planned holds no movable state on GitHub; configure [tickets].rejectedState`,
|
|
897
|
+
)
|
|
898
|
+
else if (!configured.some((name) => holdsState(name, state)) && !representableState(state))
|
|
899
|
+
problems.push(
|
|
900
|
+
`state "${state}" cannot be a GitHub state: "${stateLabel(state)}" must be a lowercase state name of at most 40 characters that Autobuild does not apply itself`,
|
|
901
|
+
)
|
|
902
|
+
}
|
|
903
|
+
for (const label of input.labels)
|
|
904
|
+
if (isStateLabel(label) || isLinkLabel(label))
|
|
905
|
+
problems.push(
|
|
906
|
+
`label "${label}" would collide with an ${isStateLabel(label) ? `${STATE_LABEL_PREFIX} state` : 'autobuild-link: issue link'} label`,
|
|
907
|
+
)
|
|
908
|
+
for (const key of input.creationKeys)
|
|
909
|
+
if (!validCreationKey(key))
|
|
910
|
+
problems.push(
|
|
911
|
+
`creation key "${key}" must be 1-200 letters, digits, dots, colons, underscores or hyphens`,
|
|
912
|
+
)
|
|
913
|
+
return [...new Set(problems)].sort()
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
async listAll(): Promise<TicketListing> {
|
|
917
|
+
return this.listing(
|
|
918
|
+
await this.listIssues('listAll', { state: 'all' }, false),
|
|
919
|
+
() => true,
|
|
920
|
+
false,
|
|
921
|
+
)
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
async listReady(criteria: TicketCriteria): Promise<TicketListing> {
|
|
925
|
+
const labels = criteria.labels ?? []
|
|
926
|
+
for (const label of labels)
|
|
927
|
+
if (label.includes(',')) throw new Error(`${SOURCE}: label "${label}" contains a comma`)
|
|
928
|
+
const login =
|
|
929
|
+
criteria.assignee !== undefined ? await this.assigneeLogin(criteria.assignee) : undefined
|
|
930
|
+
const labelQuery = (extra: string[] = []): Record<string, string> => {
|
|
931
|
+
const all = [...extra, ...labels]
|
|
932
|
+
return {
|
|
933
|
+
...(all.length > 0 ? { labels: all.join(',') } : {}),
|
|
934
|
+
...(login !== undefined ? { assignee: login } : {}),
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
// GitHub narrows the read server-side; the explicit membership check
|
|
938
|
+
// keeps "ready when the user is one of several assignees" independent of
|
|
939
|
+
// that, and drops issues before hydration reads their blockers.
|
|
940
|
+
const listIssues = async (
|
|
941
|
+
operation: string,
|
|
942
|
+
query: Record<string, string>,
|
|
943
|
+
remember: boolean,
|
|
944
|
+
): Promise<GitHubIssue[]> => {
|
|
945
|
+
const issues = await this.listIssues(operation, query, remember)
|
|
946
|
+
if (login === undefined) return issues
|
|
947
|
+
const wanted = login.toLowerCase()
|
|
948
|
+
return issues.filter((issue) =>
|
|
949
|
+
(issue.assignees ?? []).some((assignee) => assignee.login.toLowerCase() === wanted),
|
|
950
|
+
)
|
|
951
|
+
}
|
|
952
|
+
if (criteria.state === undefined)
|
|
953
|
+
return this.listing(
|
|
954
|
+
await listIssues('list', { state: 'all', ...labelQuery() }, false),
|
|
955
|
+
() => true,
|
|
956
|
+
false,
|
|
957
|
+
)
|
|
958
|
+
const wanted = criteria.state
|
|
959
|
+
const holds = (ticket: Ticket) => holdsState(ticket.state, wanted)
|
|
960
|
+
if (
|
|
961
|
+
holdsState(wanted, this.lifecycle.done) ||
|
|
962
|
+
holdsState(wanted, rejectedStateOf(this.lifecycle))
|
|
963
|
+
)
|
|
964
|
+
return this.listing(
|
|
965
|
+
await listIssues('list', { state: 'closed', ...labelQuery() }, false),
|
|
966
|
+
holds,
|
|
967
|
+
false,
|
|
968
|
+
)
|
|
969
|
+
if (holdsState(wanted, this.lifecycle.triage))
|
|
970
|
+
return this.listing(
|
|
971
|
+
await listIssues('list', { state: 'open', ...labelQuery() }, false),
|
|
972
|
+
holds,
|
|
973
|
+
false,
|
|
974
|
+
)
|
|
975
|
+
// A label state: the ready listing is the recurring dispatcher read, so
|
|
976
|
+
// it alone is remembered, oldest first for a stable order.
|
|
977
|
+
const recurring = holdsState(wanted, this.lifecycle.ready)
|
|
978
|
+
return this.listing(
|
|
979
|
+
await listIssues(
|
|
980
|
+
'listReady',
|
|
981
|
+
{
|
|
982
|
+
state: 'open',
|
|
983
|
+
sort: 'created',
|
|
984
|
+
direction: 'asc',
|
|
985
|
+
...labelQuery([stateLabel(wanted)]),
|
|
986
|
+
},
|
|
987
|
+
recurring,
|
|
988
|
+
),
|
|
989
|
+
holds,
|
|
990
|
+
recurring,
|
|
991
|
+
)
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
private async listing(
|
|
995
|
+
issues: GitHubIssue[],
|
|
996
|
+
keep: (ticket: Ticket) => boolean,
|
|
997
|
+
remember: boolean,
|
|
998
|
+
): Promise<TicketListing> {
|
|
999
|
+
const parents = new Map(issues.map((issue) => [issue.number, issue]))
|
|
1000
|
+
const parentReads = new Map<number, Promise<GitHubIssue | null>>()
|
|
1001
|
+
return this.collect(issues, keep, { remember, parents, parentReads })
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
private async collect(
|
|
1005
|
+
issues: GitHubIssue[],
|
|
1006
|
+
keep: (ticket: Ticket) => boolean,
|
|
1007
|
+
opts: HydrateOptions,
|
|
1008
|
+
): Promise<TicketListing> {
|
|
1009
|
+
const tickets: Ticket[] = []
|
|
1010
|
+
const diagnostics: string[] = []
|
|
1011
|
+
for (const issue of issues) {
|
|
1012
|
+
const hydrated = await this.hydrate(issue, opts)
|
|
1013
|
+
diagnostics.push(...hydrated.diagnostics)
|
|
1014
|
+
if (!hydrated.listed || !keep(hydrated.ticket)) continue
|
|
1015
|
+
tickets.push({ ...hydrated.ticket, blockersResolved: hydrated.blockersResolved })
|
|
1016
|
+
}
|
|
1017
|
+
return { tickets, diagnostics }
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* The tickets targeting one node, read from the node's side: the node
|
|
1022
|
+
* issue, then (unless its summary counts none) its paginated sub-issues,
|
|
1023
|
+
* all conditional. Every local sub-issue of a node targets it, so this
|
|
1024
|
+
* equals `listAll` filtered by target at a cost that follows the node's
|
|
1025
|
+
* children, not the repository.
|
|
1026
|
+
*/
|
|
1027
|
+
async listTargeting(nodeId: string): Promise<TicketListing> {
|
|
1028
|
+
const empty: TicketListing = { tickets: [], diagnostics: [] }
|
|
1029
|
+
const number = parseIssueId(nodeId)
|
|
1030
|
+
if (number === null) return empty
|
|
1031
|
+
const read = await this.readIssue('listTargeting', number, true)
|
|
1032
|
+
if (read === null || !isNode(read.issue)) return empty
|
|
1033
|
+
if (read.issue.sub_issues_summary?.total === 0) return empty
|
|
1034
|
+
const children = (await this.subIssues('listTargeting', number, true)).filter((child) =>
|
|
1035
|
+
this.isLocalChild(child),
|
|
1036
|
+
)
|
|
1037
|
+
return this.collect(children, () => true, { remember: true, target: String(number) })
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/** Every sub-issue of issue `number`, exhausting pagination. */
|
|
1041
|
+
private async subIssues(
|
|
1042
|
+
operation: string,
|
|
1043
|
+
number: number,
|
|
1044
|
+
remember: boolean,
|
|
1045
|
+
): Promise<GitHubIssue[]> {
|
|
1046
|
+
const issues: GitHubIssue[] = []
|
|
1047
|
+
let page: string | undefined = '1'
|
|
1048
|
+
while (page !== undefined) {
|
|
1049
|
+
const response = await this.must(
|
|
1050
|
+
operation,
|
|
1051
|
+
'GET',
|
|
1052
|
+
this.path(`/issues/${number}/sub_issues`),
|
|
1053
|
+
{
|
|
1054
|
+
query: { per_page: PAGE, page },
|
|
1055
|
+
remember,
|
|
1056
|
+
},
|
|
1057
|
+
)
|
|
1058
|
+
for (const json of z.array(z.unknown()).parse(response.json))
|
|
1059
|
+
issues.push(this.parseIssue(operation, json))
|
|
1060
|
+
page = nextPage(response.link)
|
|
1061
|
+
}
|
|
1062
|
+
return issues
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
async dependencyStates(ids: string[]): Promise<DependencyState[]> {
|
|
1066
|
+
const results: DependencyState[] = []
|
|
1067
|
+
for (const id of ids) {
|
|
1068
|
+
const foreign = /^([^/\s#]+\/[^/\s#]+)#([1-9][0-9]*)$/.exec(id)
|
|
1069
|
+
if (foreign && foreign[1]!.toLowerCase() !== this.fullName.toLowerCase()) {
|
|
1070
|
+
// GitHub allows cross-repository dependencies; they never resolve here.
|
|
1071
|
+
results.push({ id, exists: true, resolved: false, blockedBy: [] })
|
|
1072
|
+
continue
|
|
1073
|
+
}
|
|
1074
|
+
const number = foreign ? Number(foreign[2]) : parseIssueId(id)
|
|
1075
|
+
const read = number === null ? null : await this.readIssue('dependencyStates', number, true)
|
|
1076
|
+
if (read === null) {
|
|
1077
|
+
results.push({ id, exists: false, resolved: false, blockedBy: [] })
|
|
1078
|
+
continue
|
|
1079
|
+
}
|
|
1080
|
+
const { ticket } = await this.hydrate(read.issue, {
|
|
1081
|
+
remember: true,
|
|
1082
|
+
resolveTarget: false,
|
|
1083
|
+
...etagOf(read),
|
|
1084
|
+
})
|
|
1085
|
+
results.push({
|
|
1086
|
+
id,
|
|
1087
|
+
exists: true,
|
|
1088
|
+
resolved: ticket.resolved,
|
|
1089
|
+
...(ticket.state !== undefined ? { state: ticket.state } : {}),
|
|
1090
|
+
blockedBy: ticket.blockedBy ?? [],
|
|
1091
|
+
})
|
|
1092
|
+
}
|
|
1093
|
+
return results
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
// ── Claim and projections ─────────────────────────────────────────────────
|
|
1097
|
+
|
|
1098
|
+
/**
|
|
1099
|
+
* Claim-before-launch (SPEC §12): a fresh, unconditional read re-checks the
|
|
1100
|
+
* issue is open, in the ready state and carries every ready label; then the
|
|
1101
|
+
* ready label becomes the claimed one. The pair is not transactional, which
|
|
1102
|
+
* the single-writer dispatcher (§12) makes acceptable.
|
|
1103
|
+
*/
|
|
1104
|
+
async claim(id: string): Promise<boolean> {
|
|
1105
|
+
const number = parseIssueId(id)
|
|
1106
|
+
if (number === null) return false
|
|
1107
|
+
const read = await this.readIssue('claim', number, false)
|
|
1108
|
+
if (read === null) return false
|
|
1109
|
+
const { issue } = read
|
|
1110
|
+
if (issue.state !== 'open') return false
|
|
1111
|
+
const current = issueState(issue, this.lifecycle)
|
|
1112
|
+
if ('malformed' in current || !holdsState(current.state, this.lifecycle.ready)) return false
|
|
1113
|
+
const labels = ticketLabelsOf(issue).map((label) => label.toLowerCase())
|
|
1114
|
+
if (!this.readyLabels.every((label) => labels.includes(label.toLowerCase()))) return false
|
|
1115
|
+
if (needsReopenCheck(issue)) {
|
|
1116
|
+
const verdict = await this.reopenCheck(issue, true, read.etag)
|
|
1117
|
+
if (verdict === 'stale') await this.heal(issue)
|
|
1118
|
+
if (verdict !== 'fresh') return false
|
|
1119
|
+
}
|
|
1120
|
+
await this.ensureLabels('claim', [stateLabel(this.lifecycle.doing)])
|
|
1121
|
+
await this.patchIssue('claim', number, {
|
|
1122
|
+
labels: [
|
|
1123
|
+
...labelNames(issue).filter((name) => !isStateLabel(name)),
|
|
1124
|
+
stateLabel(this.lifecycle.doing),
|
|
1125
|
+
],
|
|
1126
|
+
})
|
|
1127
|
+
return true
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
async comment(id: string, body: string): Promise<void> {
|
|
1131
|
+
const number = parseIssueId(id)
|
|
1132
|
+
const response =
|
|
1133
|
+
number === null
|
|
1134
|
+
? null
|
|
1135
|
+
: await this.request('comment', 'POST', this.path(`/issues/${number}/comments`), {
|
|
1136
|
+
body: { body },
|
|
1137
|
+
missing: true,
|
|
1138
|
+
})
|
|
1139
|
+
if (response === null) throw new Error(`github comment: unknown ticket "${id}"`)
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
async transition(id: string, state: string): Promise<void> {
|
|
1143
|
+
const number = parseIssueId(id)
|
|
1144
|
+
if (number === null) throw new Error(`github transition: unknown ticket "${id}"`)
|
|
1145
|
+
const target = await this.resolveTarget('transition', state)
|
|
1146
|
+
const read = await this.readIssue('transition', number, false)
|
|
1147
|
+
if (read === null) throw new Error(`github transition: unknown ticket "${id}"`)
|
|
1148
|
+
await this.applyState('transition', read.issue, target)
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
/**
|
|
1152
|
+
* Put an issue in `state`. Reopening into a label state strips state labels
|
|
1153
|
+
* on the reopen and adds the target label in a second write, so a `labeled`
|
|
1154
|
+
* event always follows the `reopened` one and the label reads as fresh.
|
|
1155
|
+
*/
|
|
1156
|
+
private async applyState(operation: string, issue: GitHubIssue, state: string): Promise<void> {
|
|
1157
|
+
const write = writeForState(state, this.lifecycle, labelNames(issue))
|
|
1158
|
+
const target = write.labels.filter(isStateLabel)
|
|
1159
|
+
await this.ensureLabels(operation, target)
|
|
1160
|
+
if (write.state === 'closed') {
|
|
1161
|
+
// GitHub ignores state_reason unless the state changes, so a closed
|
|
1162
|
+
// issue whose completion differs from the target's is reopened first.
|
|
1163
|
+
const completed = write.state_reason === 'completed'
|
|
1164
|
+
if (issue.state === 'closed' && isClosedCompleted(issue) !== completed)
|
|
1165
|
+
await this.patchIssue(operation, issue.number, {
|
|
1166
|
+
state: 'open',
|
|
1167
|
+
labels: write.labels,
|
|
1168
|
+
})
|
|
1169
|
+
await this.patchIssue(operation, issue.number, {
|
|
1170
|
+
state: 'closed',
|
|
1171
|
+
state_reason: write.state_reason,
|
|
1172
|
+
labels: write.labels,
|
|
1173
|
+
})
|
|
1174
|
+
return
|
|
1175
|
+
}
|
|
1176
|
+
const kept = write.labels.filter((name) => !isStateLabel(name))
|
|
1177
|
+
const reopening = issue.state === 'closed'
|
|
1178
|
+
const relabel =
|
|
1179
|
+
issue.state === 'open' &&
|
|
1180
|
+
needsReopenCheck(issue) &&
|
|
1181
|
+
target.some((name) =>
|
|
1182
|
+
stateLabelsOf(issue).some((held) => held.toLowerCase() === name.toLowerCase()),
|
|
1183
|
+
)
|
|
1184
|
+
if (reopening || relabel) {
|
|
1185
|
+
await this.patchIssue(operation, issue.number, {
|
|
1186
|
+
...(reopening ? { state: 'open' } : {}),
|
|
1187
|
+
labels: kept,
|
|
1188
|
+
})
|
|
1189
|
+
if (target.length > 0)
|
|
1190
|
+
await this.patchIssue(operation, issue.number, { labels: write.labels })
|
|
1191
|
+
return
|
|
1192
|
+
}
|
|
1193
|
+
const before = labelNames(issue)
|
|
1194
|
+
.map((name) => name.toLowerCase())
|
|
1195
|
+
.sort()
|
|
1196
|
+
const after = write.labels.map((name) => name.toLowerCase()).sort()
|
|
1197
|
+
if (before.join('\n') === after.join('\n')) return
|
|
1198
|
+
await this.patchIssue(operation, issue.number, { labels: write.labels })
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
// ── Create ────────────────────────────────────────────────────────────────
|
|
1202
|
+
|
|
1203
|
+
async create(draft: TicketDraft, opts: TicketCreateOptions = {}): Promise<Ticket> {
|
|
1204
|
+
if (opts.requestedId !== undefined) throw new Error('github does not support requested ids')
|
|
1205
|
+
let labels: string[]
|
|
1206
|
+
try {
|
|
1207
|
+
labels = effectiveLabels(draft.kind, draft.labels, []) ?? []
|
|
1208
|
+
} catch (error) {
|
|
1209
|
+
throw new Error(
|
|
1210
|
+
`github create: ticket "${draft.title}": ${message(error)} — nothing was written`,
|
|
1211
|
+
)
|
|
1212
|
+
}
|
|
1213
|
+
this.refuseManagedLabels('create', labels)
|
|
1214
|
+
const links = mergeIssueLinks(normalizeIssueLinks(draft.issueLinks ?? []))
|
|
1215
|
+
const blockedBy = [...new Set(draft.blockedBy ?? [])]
|
|
1216
|
+
for (const blocker of blockedBy)
|
|
1217
|
+
if (parseIssueId(blocker) === null)
|
|
1218
|
+
throw new Error(
|
|
1219
|
+
`github create: blocker "${blocker}" is not an issue number in ${this.fullName} — nothing was written`,
|
|
1220
|
+
)
|
|
1221
|
+
const key = opts.idempotencyKey
|
|
1222
|
+
let reservedAt: number | undefined
|
|
1223
|
+
if (key !== undefined) {
|
|
1224
|
+
if (!validCreationKey(key))
|
|
1225
|
+
throw new Error(
|
|
1226
|
+
`github create: creation key "${key}" must be 1-200 letters, digits, dots, colons, underscores or hyphens`,
|
|
1227
|
+
)
|
|
1228
|
+
reservedAt =
|
|
1229
|
+
opts.idempotencyKeyReservedAt === undefined
|
|
1230
|
+
? Number.NaN
|
|
1231
|
+
: Date.parse(opts.idempotencyKeyReservedAt)
|
|
1232
|
+
if (!Number.isFinite(reservedAt)) throw new TicketCreationKeyReservationRequired()
|
|
1233
|
+
}
|
|
1234
|
+
const state = await this.resolveTarget('create', opts.state ?? this.lifecycle.create)
|
|
1235
|
+
const target =
|
|
1236
|
+
draft.target === undefined || draft.target === null
|
|
1237
|
+
? undefined
|
|
1238
|
+
: await this.validateTarget('create', undefined, draft.title, draft.target)
|
|
1239
|
+
if (labels.includes(NODE_LABEL)) await this.ensureNodeLabel('create')
|
|
1240
|
+
const write = writeForState(state, this.lifecycle, [...labels, ...links.map(linkLabel)])
|
|
1241
|
+
if (key !== undefined && reservedAt !== undefined) {
|
|
1242
|
+
const adopted = await this.findByCreationKey(key, reservedAt)
|
|
1243
|
+
if (adopted !== undefined) return this.adopt(adopted, blockedBy)
|
|
1244
|
+
}
|
|
1245
|
+
// A closing create state opens the issue without a state label and
|
|
1246
|
+
// closes it as a follow-up.
|
|
1247
|
+
const initial = write.labels
|
|
1248
|
+
await this.ensureLabels('create', initial)
|
|
1249
|
+
const intent: CreationIntent = {
|
|
1250
|
+
state,
|
|
1251
|
+
issueLinks: links,
|
|
1252
|
+
blockedBy,
|
|
1253
|
+
...(target !== undefined ? { target } : {}),
|
|
1254
|
+
}
|
|
1255
|
+
const response = await this.must('create', 'POST', this.path('/issues'), {
|
|
1256
|
+
body: {
|
|
1257
|
+
title: draft.title,
|
|
1258
|
+
body: key === undefined ? draft.body : encodeCreationMarker(draft.body, key, intent),
|
|
1259
|
+
labels: initial,
|
|
1260
|
+
},
|
|
1261
|
+
})
|
|
1262
|
+
const issue = this.parseIssue('create', response.json)
|
|
1263
|
+
const held = labelNames(issue).map((name) => name.toLowerCase())
|
|
1264
|
+
if (!initial.every((name) => held.includes(name.toLowerCase())))
|
|
1265
|
+
throw new Error(
|
|
1266
|
+
`github create: token lacks push access; labels were dropped on #${issue.number} (${issue.html_url})`,
|
|
1267
|
+
)
|
|
1268
|
+
return this.finishCreate(issue, intent, key, false)
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
/**
|
|
1272
|
+
* The issue a creation key opened, among issues created since the key's
|
|
1273
|
+
* reservation (less clock skew), through the consistent list endpoint
|
|
1274
|
+
* newest first; search lags writes. The first call scans back to the floor
|
|
1275
|
+
* and indexes every marker it sees. Later calls with the same or a later
|
|
1276
|
+
* floor page newest first only down to the newest issue already indexed:
|
|
1277
|
+
* issue numbers increase with creation, so nothing is missed, whoever
|
|
1278
|
+
* created it. An import of N tickets therefore costs one scan plus one list
|
|
1279
|
+
* page per create, not N full scans. A hit is re-read, because a follow-up
|
|
1280
|
+
* may have rewritten its marker since it was indexed.
|
|
1281
|
+
*/
|
|
1282
|
+
private async findByCreationKey(
|
|
1283
|
+
key: string,
|
|
1284
|
+
reservedAt: number,
|
|
1285
|
+
): Promise<GitHubIssue | undefined> {
|
|
1286
|
+
const floor = reservedAt - CREATION_SCAN_SKEW_MS
|
|
1287
|
+
const scan =
|
|
1288
|
+
this.creationScan !== undefined && this.creationScan.floor <= floor
|
|
1289
|
+
? this.creationScan
|
|
1290
|
+
: { floor, newest: 0, keys: new Map<string, number>() }
|
|
1291
|
+
let newest = scan.newest
|
|
1292
|
+
let page: string | undefined = '1'
|
|
1293
|
+
scanning: while (page !== undefined) {
|
|
1294
|
+
const response = await this.must('create', 'GET', this.path('/issues'), {
|
|
1295
|
+
query: {
|
|
1296
|
+
state: 'all',
|
|
1297
|
+
sort: 'created',
|
|
1298
|
+
direction: 'desc',
|
|
1299
|
+
per_page: PAGE,
|
|
1300
|
+
page,
|
|
1301
|
+
},
|
|
1302
|
+
})
|
|
1303
|
+
for (const json of z.array(z.unknown()).parse(response.json)) {
|
|
1304
|
+
const issue = this.parseIssue('create', json)
|
|
1305
|
+
if (issue.number <= scan.newest) break scanning
|
|
1306
|
+
newest = Math.max(newest, issue.number)
|
|
1307
|
+
if (issue.pull_request !== undefined) continue
|
|
1308
|
+
if (issue.created_at !== undefined && Date.parse(issue.created_at) < scan.floor)
|
|
1309
|
+
break scanning
|
|
1310
|
+
const marker = splitCreationMarker(issue.body).marker?.key
|
|
1311
|
+
if (marker !== undefined && !scan.keys.has(marker)) scan.keys.set(marker, issue.number)
|
|
1312
|
+
}
|
|
1313
|
+
page = nextPage(response.link)
|
|
1314
|
+
}
|
|
1315
|
+
scan.newest = newest
|
|
1316
|
+
this.creationScan = scan
|
|
1317
|
+
const number = scan.keys.get(key)
|
|
1318
|
+
if (number === undefined) return undefined
|
|
1319
|
+
const read = await this.readIssue('create', number, false)
|
|
1320
|
+
if (read === null || splitCreationMarker(read.issue.body).marker?.key !== key) {
|
|
1321
|
+
scan.keys.delete(key)
|
|
1322
|
+
return undefined
|
|
1323
|
+
}
|
|
1324
|
+
return read.issue
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
/** A retry found the issue its key opened. A pending marker finishes the
|
|
1328
|
+
* first attempt's recorded intent; a plain one reconciles only missing
|
|
1329
|
+
* blockers from this retry, as Linear does. */
|
|
1330
|
+
private async adopt(issue: GitHubIssue, retryBlockers: string[]): Promise<Ticket> {
|
|
1331
|
+
const marker = splitCreationMarker(issue.body).marker!
|
|
1332
|
+
if (marker.pending !== undefined)
|
|
1333
|
+
return this.finishCreate(issue, marker.pending, marker.key, true)
|
|
1334
|
+
if (retryBlockers.length > 0) await this.recordBlockers(issue, retryBlockers, true, true)
|
|
1335
|
+
return this.fresh('create', issue.number)
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
/**
|
|
1339
|
+
* The create's follow-ups, shared by a first attempt and a recovery so both
|
|
1340
|
+
* run the same idempotent steps: the closure, any missing link labels, the
|
|
1341
|
+
* blockers, then the marker rewritten to its plain (complete) form.
|
|
1342
|
+
*/
|
|
1343
|
+
private async finishCreate(
|
|
1344
|
+
issue: GitHubIssue,
|
|
1345
|
+
intent: CreationIntent,
|
|
1346
|
+
key: string | undefined,
|
|
1347
|
+
adopting: boolean,
|
|
1348
|
+
): Promise<Ticket> {
|
|
1349
|
+
let current = issue
|
|
1350
|
+
const write = intent.state === '' ? undefined : writeForState(intent.state, this.lifecycle, [])
|
|
1351
|
+
if (write?.state === 'closed' && current.state === 'open') {
|
|
1352
|
+
// A recovery never undoes a person's reopen: close only an issue that
|
|
1353
|
+
// has never been closed.
|
|
1354
|
+
const neverClosed = !adopting || (await this.closedEvents(current.number)) === 0
|
|
1355
|
+
if (neverClosed)
|
|
1356
|
+
current = await this.patchIssue('create', current.number, {
|
|
1357
|
+
state: 'closed',
|
|
1358
|
+
state_reason: write.state_reason,
|
|
1359
|
+
labels: labelNames(current).filter((name) => !isStateLabel(name)),
|
|
1360
|
+
})
|
|
1361
|
+
}
|
|
1362
|
+
if (adopting) {
|
|
1363
|
+
const wanted = linkLabelsFor(current.number, intent.issueLinks)
|
|
1364
|
+
const held = labelNames(current)
|
|
1365
|
+
const missing = wanted.filter(
|
|
1366
|
+
(name) => !held.some((label) => label.toLowerCase() === name.toLowerCase()),
|
|
1367
|
+
)
|
|
1368
|
+
if (missing.length > 0) {
|
|
1369
|
+
await this.ensureLabels('create', missing)
|
|
1370
|
+
current = await this.patchIssue('create', current.number, { labels: [...held, ...missing] })
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
if (intent.target !== undefined)
|
|
1374
|
+
await this.recordTarget(current, intent.target, adopting, key !== undefined)
|
|
1375
|
+
if (intent.blockedBy.length > 0)
|
|
1376
|
+
await this.recordBlockers(current, intent.blockedBy, adopting, key !== undefined)
|
|
1377
|
+
if (key !== undefined) {
|
|
1378
|
+
const { body } = splitCreationMarker(current.body)
|
|
1379
|
+
await this.patchIssue('create', current.number, { body: encodeCreationMarker(body, key) })
|
|
1380
|
+
}
|
|
1381
|
+
return this.fresh('create', current.number)
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
private async closedEvents(number: number): Promise<number> {
|
|
1385
|
+
const data = await this.graphql<{
|
|
1386
|
+
repository: { issue: { timelineItems: { totalCount: number } } | null } | null
|
|
1387
|
+
}>(
|
|
1388
|
+
'create',
|
|
1389
|
+
'query ClosedEvents($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { timelineItems(itemTypes: [CLOSED_EVENT], first: 1) { totalCount } } } }',
|
|
1390
|
+
{ owner: this.owner, name: this.repo, number },
|
|
1391
|
+
)
|
|
1392
|
+
return data.repository?.issue?.timelineItems.totalCount ?? 0
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
/** Record blockers on a created issue. Every failure says the issue exists,
|
|
1396
|
+
* and which blockers were and were not recorded, so a retry adopts it
|
|
1397
|
+
* rather than duplicating it. */
|
|
1398
|
+
private async recordBlockers(
|
|
1399
|
+
issue: GitHubIssue,
|
|
1400
|
+
requested: string[],
|
|
1401
|
+
readExisting: boolean,
|
|
1402
|
+
retryableByKey: boolean,
|
|
1403
|
+
): Promise<void> {
|
|
1404
|
+
const recorded: string[] = []
|
|
1405
|
+
try {
|
|
1406
|
+
if (readExisting) recorded.push(...(await this.blockers(issue, false)).ids)
|
|
1407
|
+
for (const blocker of requested) {
|
|
1408
|
+
if (recorded.includes(blocker)) continue
|
|
1409
|
+
await this.postBlocker('create', issue.number, blocker)
|
|
1410
|
+
recorded.push(blocker)
|
|
1411
|
+
}
|
|
1412
|
+
} catch (error) {
|
|
1413
|
+
if (error instanceof TicketSourceRateLimitError && recorded.length === 0 && !retryableByKey)
|
|
1414
|
+
throw error
|
|
1415
|
+
const unrecorded = requested.filter((id) => !recorded.includes(id))
|
|
1416
|
+
throw new Error(
|
|
1417
|
+
`github create: ticket "${issue.number}" ${retryableByKey ? 'already exists' : 'was created'} at ${issue.html_url}, ` +
|
|
1418
|
+
'but its blockers were not all recorded. ' +
|
|
1419
|
+
`Blockers recorded: ${blockerList(requested.filter((id) => recorded.includes(id)))}. ` +
|
|
1420
|
+
`Blockers not recorded: ${blockerList(unrecorded)}. ` +
|
|
1421
|
+
(retryableByKey
|
|
1422
|
+
? 'Retry with the same creation key; GitHub will adopt this ticket and finish only what is missing. '
|
|
1423
|
+
: 'Do not rerun ticket creation; repair the blockers on the existing ticket. ') +
|
|
1424
|
+
`Underlying failure: ${message(error)}`,
|
|
1425
|
+
{ cause: error },
|
|
1426
|
+
)
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
/** Make a created issue a sub-issue of its target. A recovery leaves a
|
|
1431
|
+
* parent a person has set since alone, and revalidates the recorded target
|
|
1432
|
+
* before writing it, since the target may have changed since the first
|
|
1433
|
+
* attempt. A failure says the issue exists, so a retry adopts it rather
|
|
1434
|
+
* than duplicating it. */
|
|
1435
|
+
private async recordTarget(
|
|
1436
|
+
issue: GitHubIssue,
|
|
1437
|
+
target: string,
|
|
1438
|
+
adopting: boolean,
|
|
1439
|
+
retryableByKey: boolean,
|
|
1440
|
+
): Promise<void> {
|
|
1441
|
+
const parent = parentOf(issue)
|
|
1442
|
+
if (parent !== undefined && (adopting || this.localParent(issue) === Number(target))) return
|
|
1443
|
+
if (adopting) {
|
|
1444
|
+
try {
|
|
1445
|
+
await this.checkTarget('create', String(issue.number), target)
|
|
1446
|
+
} catch (error) {
|
|
1447
|
+
throw new Error(
|
|
1448
|
+
`github create: ticket "${issue.number}" already exists at ${issue.html_url}, ` +
|
|
1449
|
+
`but its recorded target #${target} is no longer valid, so it was not recorded: ${message(error)}. ` +
|
|
1450
|
+
`Make #${target} a node again and retry with the same creation key, or choose a target with \`ab ticket update ${issue.number} --target <node>\`.`,
|
|
1451
|
+
{ cause: error },
|
|
1452
|
+
)
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
try {
|
|
1456
|
+
await this.setParent('create', issue, Number(target), false)
|
|
1457
|
+
} catch (error) {
|
|
1458
|
+
throw new Error(
|
|
1459
|
+
`github create: ticket "${issue.number}" ${retryableByKey ? 'already exists' : 'was created'} at ${issue.html_url}, ` +
|
|
1460
|
+
`but its target #${target} was not recorded. ` +
|
|
1461
|
+
(retryableByKey
|
|
1462
|
+
? 'Retry with the same creation key; GitHub will adopt this ticket and finish only what is missing. '
|
|
1463
|
+
: `Do not rerun ticket creation; set it with \`ab ticket update ${issue.number} --target ${target}\`. `) +
|
|
1464
|
+
`Underlying failure: ${message(error)}`,
|
|
1465
|
+
{ cause: error },
|
|
1466
|
+
)
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
private async fresh(operation: string, number: number): Promise<Ticket> {
|
|
1471
|
+
const ticket = await this.readTicket(operation, number)
|
|
1472
|
+
if (ticket === null) throw new Error(`github ${operation}: issue #${number} disappeared`)
|
|
1473
|
+
return ticket
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
/** A fresh, unconditional read of a ticket, or `null` when there is none. */
|
|
1477
|
+
private async readTicket(operation: string, number: number | null): Promise<Ticket | null> {
|
|
1478
|
+
const read = number === null ? null : await this.readIssue(operation, number, false)
|
|
1479
|
+
if (read === null) return null
|
|
1480
|
+
return (await this.hydrate(read.issue, { remember: false })).ticket
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
// ── Integration tree ──────────────────────────────────────────────────────
|
|
1484
|
+
|
|
1485
|
+
/** The shared target checks (exists, is a node, no cycle) over fresh reads;
|
|
1486
|
+
* returns the canonical target id. */
|
|
1487
|
+
private async validateTarget(
|
|
1488
|
+
operation: string,
|
|
1489
|
+
id: string | undefined,
|
|
1490
|
+
name: string,
|
|
1491
|
+
target: string,
|
|
1492
|
+
): Promise<string> {
|
|
1493
|
+
try {
|
|
1494
|
+
return await this.checkTarget(operation, id, target)
|
|
1495
|
+
} catch (error) {
|
|
1496
|
+
throw new Error(
|
|
1497
|
+
`github ${operation}: ticket "${name}": ${message(error)} — nothing was written`,
|
|
1498
|
+
{
|
|
1499
|
+
cause: error,
|
|
1500
|
+
},
|
|
1501
|
+
)
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
private async checkTarget(
|
|
1506
|
+
operation: string,
|
|
1507
|
+
id: string | undefined,
|
|
1508
|
+
target: string,
|
|
1509
|
+
): Promise<string> {
|
|
1510
|
+
const canonical = await validateTicketTree(
|
|
1511
|
+
{
|
|
1512
|
+
name: this.name,
|
|
1513
|
+
get: (ticket) => this.readTicket(operation, parseIssueId(ticket)),
|
|
1514
|
+
listAll: () => this.listAll(),
|
|
1515
|
+
},
|
|
1516
|
+
id,
|
|
1517
|
+
{ target },
|
|
1518
|
+
)
|
|
1519
|
+
return canonical as string
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
/** A node keeps its kind while any local sub-issue targets it; the node's
|
|
1523
|
+
* own sub-issue list, fully paginated, says whether one does. */
|
|
1524
|
+
private async refuseDemotion(operation: string, id: string, issue: GitHubIssue): Promise<void> {
|
|
1525
|
+
if (issue.sub_issues_summary?.total === 0) return
|
|
1526
|
+
const child = (await this.subIssues(operation, issue.number, false)).find((sub) =>
|
|
1527
|
+
this.isLocalChild(sub),
|
|
1528
|
+
)
|
|
1529
|
+
if (child !== undefined)
|
|
1530
|
+
throw new Error(
|
|
1531
|
+
`github ${operation}: cannot change node ${id} to work: ticket ${child.number} targets it — nothing was written`,
|
|
1532
|
+
)
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
/** The repository's `node` label, created on demand. GitHub label names are
|
|
1536
|
+
* unique ignoring case, so a label cased otherwise would stand in for it
|
|
1537
|
+
* and every node would read as work: that is refused. */
|
|
1538
|
+
private async ensureNodeLabel(operation: string): Promise<void> {
|
|
1539
|
+
const label = await this.readLabel(operation, NODE_LABEL, true)
|
|
1540
|
+
if (label === null) {
|
|
1541
|
+
await this.createLabel(operation, NODE_LABEL, NODE_LABEL_DESCRIPTION)
|
|
1542
|
+
return
|
|
1543
|
+
}
|
|
1544
|
+
if (label.name !== NODE_LABEL)
|
|
1545
|
+
throw new Error(
|
|
1546
|
+
`github ${operation}: repository label "${label.name}" stands in for the ${NODE_LABEL} label; rename it to "${NODE_LABEL}" on GitHub — nothing was written`,
|
|
1547
|
+
)
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
/** Make `child` a sub-issue of issue `target`. GitHub answers 422 both for
|
|
1551
|
+
* an existing relation and for a refused one (the child cap, the depth
|
|
1552
|
+
* limit); only the child's parent, read back, says the write already holds. */
|
|
1553
|
+
private async setParent(
|
|
1554
|
+
operation: string,
|
|
1555
|
+
child: GitHubIssue,
|
|
1556
|
+
target: number,
|
|
1557
|
+
replace: boolean,
|
|
1558
|
+
): Promise<void> {
|
|
1559
|
+
try {
|
|
1560
|
+
await this.must(operation, 'POST', this.path(`/issues/${target}/sub_issues`), {
|
|
1561
|
+
body: { sub_issue_id: child.id, ...(replace ? { replace_parent: true } : {}) },
|
|
1562
|
+
})
|
|
1563
|
+
} catch (error) {
|
|
1564
|
+
if (statusOf(error) !== 422) throw error
|
|
1565
|
+
const read = await this.readIssue(operation, child.number, false)
|
|
1566
|
+
if (read === null || this.localParent(read.issue) !== target) throw error
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
private async clearParent(operation: string, child: GitHubIssue, parent: number): Promise<void> {
|
|
1571
|
+
try {
|
|
1572
|
+
await this.must(operation, 'DELETE', this.path(`/issues/${parent}/sub_issue`), {
|
|
1573
|
+
body: { sub_issue_id: child.id },
|
|
1574
|
+
})
|
|
1575
|
+
} catch (error) {
|
|
1576
|
+
if (statusOf(error) !== 404) throw error
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
// ── Grooming writes ───────────────────────────────────────────────────────
|
|
1581
|
+
|
|
1582
|
+
async update(id: string, patch: TicketUpdate): Promise<void> {
|
|
1583
|
+
const validated = validateTicketUpdate(patch)
|
|
1584
|
+
const number = parseIssueId(id)
|
|
1585
|
+
if (number === null) throw new Error(`github update: unknown ticket "${id}"`)
|
|
1586
|
+
if (validated.labels !== undefined) this.refuseManagedLabels('update', validated.labels)
|
|
1587
|
+
const links =
|
|
1588
|
+
validated.issueLinks === undefined ? undefined : mergeIssueLinks(validated.issueLinks)
|
|
1589
|
+
if (links?.some((link) => link.issue === number && link.intent === 'refs'))
|
|
1590
|
+
throw new Error(
|
|
1591
|
+
`github update: ticket "${id}" is issue #${number}, which it always closes; it cannot also only refer to it — nothing was written`,
|
|
1592
|
+
)
|
|
1593
|
+
const read = await this.readIssue('update', number, false)
|
|
1594
|
+
if (read === null) throw new Error(`github update: unknown ticket "${id}"`)
|
|
1595
|
+
const { issue } = read
|
|
1596
|
+
const held = labelNames(issue)
|
|
1597
|
+
// Every kind and target check runs before any write.
|
|
1598
|
+
let ticketLabels = validated.labels
|
|
1599
|
+
let parentWrite: { set: number; replace: boolean } | { clear: number } | undefined
|
|
1600
|
+
if (
|
|
1601
|
+
validated.kind !== undefined ||
|
|
1602
|
+
validated.target !== undefined ||
|
|
1603
|
+
validated.labels !== undefined
|
|
1604
|
+
) {
|
|
1605
|
+
try {
|
|
1606
|
+
ticketLabels = effectiveLabels(validated.kind, validated.labels, ticketLabelsOf(issue))
|
|
1607
|
+
} catch (error) {
|
|
1608
|
+
throw new Error(`github update: ticket "${id}": ${message(error)} — nothing was written`)
|
|
1609
|
+
}
|
|
1610
|
+
const currentKind = isNode(issue) ? 'node' : 'work'
|
|
1611
|
+
const effectiveKind =
|
|
1612
|
+
ticketLabels === undefined
|
|
1613
|
+
? currentKind
|
|
1614
|
+
: ticketLabels.includes(NODE_LABEL)
|
|
1615
|
+
? 'node'
|
|
1616
|
+
: 'work'
|
|
1617
|
+
if (currentKind === 'node' && effectiveKind === 'work')
|
|
1618
|
+
await this.refuseDemotion('update', id, issue)
|
|
1619
|
+
if (validated.target !== undefined) {
|
|
1620
|
+
const parent = parentOf(issue)
|
|
1621
|
+
const local = this.localParent(issue)
|
|
1622
|
+
const parentIssue =
|
|
1623
|
+
local === undefined ? null : await this.readIssue('update', local, false)
|
|
1624
|
+
const parentIsNode = parentIssue !== null && isNode(parentIssue.issue)
|
|
1625
|
+
if (validated.target === null) {
|
|
1626
|
+
// A grouping parent is no target, so there is nothing to clear.
|
|
1627
|
+
if (parentIsNode) parentWrite = { clear: local! }
|
|
1628
|
+
} else {
|
|
1629
|
+
const canonical = Number(await this.validateTarget('update', id, id, validated.target))
|
|
1630
|
+
if (parent !== undefined && !parentIsNode) {
|
|
1631
|
+
const named = local !== undefined ? `#${local}` : `${parent.repo}#${parent.number}`
|
|
1632
|
+
throw new Error(
|
|
1633
|
+
`github update: ticket "${id}" is a sub-issue of ${named}, which is not a node; remove it from ${named} or label ${named} ${NODE_LABEL} on GitHub — nothing was written`,
|
|
1634
|
+
)
|
|
1635
|
+
}
|
|
1636
|
+
if (local !== canonical) parentWrite = { set: canonical, replace: parentIsNode }
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
if (ticketLabels?.includes(NODE_LABEL) && !held.includes(NODE_LABEL))
|
|
1640
|
+
await this.ensureNodeLabel('update')
|
|
1641
|
+
}
|
|
1642
|
+
const body: Record<string, unknown> = {}
|
|
1643
|
+
if (validated.title !== undefined) body.title = validated.title
|
|
1644
|
+
if (validated.body !== undefined) {
|
|
1645
|
+
const { body: stored } = splitCreationMarker(issue.body)
|
|
1646
|
+
const marker = (issue.body ?? '').slice(stored.length)
|
|
1647
|
+
body.body = validated.body + marker
|
|
1648
|
+
}
|
|
1649
|
+
if (ticketLabels !== undefined || links !== undefined) {
|
|
1650
|
+
const labels = [
|
|
1651
|
+
...(ticketLabels ?? held.filter((name) => !isStateLabel(name) && !isLinkLabel(name))),
|
|
1652
|
+
...held.filter(isStateLabel),
|
|
1653
|
+
...(links === undefined ? held.filter(isLinkLabel) : linkLabelsFor(number, links)),
|
|
1654
|
+
]
|
|
1655
|
+
await this.ensureLabels('update', labels)
|
|
1656
|
+
body.labels = [...new Set(labels)]
|
|
1657
|
+
}
|
|
1658
|
+
const fields = Object.keys(body)
|
|
1659
|
+
if (fields.length > 0) await this.patchIssue('update', number, body)
|
|
1660
|
+
if (parentWrite === undefined) return
|
|
1661
|
+
try {
|
|
1662
|
+
if ('set' in parentWrite)
|
|
1663
|
+
await this.setParent('update', issue, parentWrite.set, parentWrite.replace)
|
|
1664
|
+
else await this.clearParent('update', issue, parentWrite.clear)
|
|
1665
|
+
} catch (error) {
|
|
1666
|
+
if (fields.length === 0) throw error
|
|
1667
|
+
const change = 'set' in parentWrite ? `target #${parentWrite.set}` : 'target removal'
|
|
1668
|
+
throw new Error(
|
|
1669
|
+
`github update: ticket "${id}" had ${fields.join(', ')} applied, but its ${change} was not recorded; rerun the target change. Underlying failure: ${message(error)}`,
|
|
1670
|
+
{ cause: error },
|
|
1671
|
+
)
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
async addBlocker(id: string, blockerId: string): Promise<void> {
|
|
1676
|
+
const number = parseIssueId(id)
|
|
1677
|
+
const target = number === null ? null : await this.readIssue('addBlocker', number, false)
|
|
1678
|
+
if (target === null) throw new Error(`github addBlocker: unknown ticket "${id}"`)
|
|
1679
|
+
const blocker = parseIssueId(blockerId)
|
|
1680
|
+
if (blocker === number || id === blockerId)
|
|
1681
|
+
throw new Error(`github addBlocker: ticket "${id}" cannot block itself`)
|
|
1682
|
+
if (blocker === null)
|
|
1683
|
+
throw new Error(
|
|
1684
|
+
`github addBlocker: unknown blocker "${blockerId}" — blockers are issue numbers in ${this.fullName}; add cross-repository dependencies on GitHub`,
|
|
1685
|
+
)
|
|
1686
|
+
const existing = await this.blockers(target.issue, false)
|
|
1687
|
+
if (existing.ids.includes(String(blocker))) return
|
|
1688
|
+
await this.postBlocker('addBlocker', number!, String(blocker))
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1691
|
+
private async postBlocker(operation: string, number: number, blockerId: string): Promise<void> {
|
|
1692
|
+
const blockerNumber = parseIssueId(blockerId)
|
|
1693
|
+
const blocker =
|
|
1694
|
+
blockerNumber === null ? null : await this.readIssue(operation, blockerNumber, false)
|
|
1695
|
+
if (blocker === null) throw new Error(`github ${operation}: unknown blocker "${blockerId}"`)
|
|
1696
|
+
if (blocker.issue.number === number)
|
|
1697
|
+
throw new Error(`github ${operation}: ticket "${number}" cannot block itself`)
|
|
1698
|
+
try {
|
|
1699
|
+
await this.must(operation, 'POST', this.path(`/issues/${number}/dependencies/blocked_by`), {
|
|
1700
|
+
body: { issue_id: blocker.issue.id },
|
|
1701
|
+
})
|
|
1702
|
+
} catch (error) {
|
|
1703
|
+
// GitHub answers 422 both for an existing dependency and for a refused
|
|
1704
|
+
// one; only the edge itself, read back, says the retry already holds.
|
|
1705
|
+
if (statusOf(error) !== 422) throw error
|
|
1706
|
+
if (!(await this.holdsBlocker(operation, number, blocker.issue.id))) throw error
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
/** Whether issue `number` is blocked by the issue with database id `id`,
|
|
1711
|
+
* read unconditionally from the dependency list. */
|
|
1712
|
+
private async holdsBlocker(operation: string, number: number, id: number): Promise<boolean> {
|
|
1713
|
+
let page: string | undefined = '1'
|
|
1714
|
+
while (page !== undefined) {
|
|
1715
|
+
const response = await this.must(
|
|
1716
|
+
operation,
|
|
1717
|
+
'GET',
|
|
1718
|
+
this.path(`/issues/${number}/dependencies/blocked_by`),
|
|
1719
|
+
{ query: { per_page: PAGE, page } },
|
|
1720
|
+
)
|
|
1721
|
+
for (const json of z.array(z.unknown()).parse(response.json))
|
|
1722
|
+
if (this.parseIssue(operation, json).id === id) return true
|
|
1723
|
+
page = nextPage(response.link)
|
|
1724
|
+
}
|
|
1725
|
+
return false
|
|
1726
|
+
}
|
|
1727
|
+
|
|
1728
|
+
async removeBlocker(id: string, blockerId: string): Promise<void> {
|
|
1729
|
+
const number = parseIssueId(id)
|
|
1730
|
+
const target = number === null ? null : await this.readIssue('removeBlocker', number, false)
|
|
1731
|
+
if (target === null) throw new Error(`github removeBlocker: unknown ticket "${id}"`)
|
|
1732
|
+
const existing = await this.blockers(target.issue, false)
|
|
1733
|
+
const index = existing.ids.indexOf(
|
|
1734
|
+
parseIssueId(blockerId) === null ? blockerId : String(parseIssueId(blockerId)),
|
|
1735
|
+
)
|
|
1736
|
+
if (index < 0) return
|
|
1737
|
+
const blocker = existing.issues[index]!
|
|
1738
|
+
try {
|
|
1739
|
+
await this.must(
|
|
1740
|
+
'removeBlocker',
|
|
1741
|
+
'DELETE',
|
|
1742
|
+
this.path(`/issues/${number}/dependencies/blocked_by/${blocker.id}`),
|
|
1743
|
+
)
|
|
1744
|
+
} catch (error) {
|
|
1745
|
+
if (statusOf(error) !== 404) throw error
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
// ── States and counts ─────────────────────────────────────────────────────
|
|
1750
|
+
|
|
1751
|
+
async listStates(): Promise<TicketStateInfo[]> {
|
|
1752
|
+
const counts = await this.readCounts({ open: true, closed: true, labels: true })
|
|
1753
|
+
const names = [...counts.names]
|
|
1754
|
+
const ordered = orderStates(names, this.lifecycleOrder())
|
|
1755
|
+
return ordered.map((name) => ({
|
|
1756
|
+
name,
|
|
1757
|
+
tickets: counts.count(name),
|
|
1758
|
+
...(counts.about.get(name) !== undefined ? { about: counts.about.get(name)! } : {}),
|
|
1759
|
+
}))
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
async countStates(names: readonly string[]): Promise<TicketStateCount[]> {
|
|
1763
|
+
const rejected = rejectedStateOf(this.lifecycle)
|
|
1764
|
+
const closedOnly = names.every(
|
|
1765
|
+
(name) => holdsState(name, this.lifecycle.done) || holdsState(name, rejected),
|
|
1766
|
+
)
|
|
1767
|
+
const triage = names.some((name) => holdsState(name, this.lifecycle.triage))
|
|
1768
|
+
const closed = names.some(
|
|
1769
|
+
(name) => holdsState(name, this.lifecycle.done) || holdsState(name, rejected),
|
|
1770
|
+
)
|
|
1771
|
+
if (names.length === 0) return []
|
|
1772
|
+
const counts = await this.readCounts({ open: triage, closed, labels: !closedOnly })
|
|
1773
|
+
return matchStateNames(names, counts.names).map((name) => ({
|
|
1774
|
+
name,
|
|
1775
|
+
tickets: counts.count(name),
|
|
1776
|
+
}))
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
/**
|
|
1780
|
+
* One fresh GraphQL request (plus one per further 100 `autobuild:` labels)
|
|
1781
|
+
* whose fields are bounded counts: open and closed totals, each state
|
|
1782
|
+
* label's open count, and one documented `reason:completed` search. Never
|
|
1783
|
+
* cached, never reads issue rows.
|
|
1784
|
+
*/
|
|
1785
|
+
private async readCounts(want: { open: boolean; closed: boolean; labels: boolean }): Promise<{
|
|
1786
|
+
names: string[]
|
|
1787
|
+
about: Map<string, string>
|
|
1788
|
+
count: (name: string) => number
|
|
1789
|
+
}> {
|
|
1790
|
+
const labelField = (after: boolean) =>
|
|
1791
|
+
`labels(query: "${STATE_LABEL_PREFIX}", first: 100${after ? ', after: $labelsAfter' : ''}) { nodes { name description issues(states: OPEN) { totalCount } } pageInfo { hasNextPage endCursor } }`
|
|
1792
|
+
const fields = [
|
|
1793
|
+
...(want.open ? ['open: issues(states: OPEN) { totalCount }'] : []),
|
|
1794
|
+
...(want.closed ? ['closed: issues(states: CLOSED) { totalCount }'] : []),
|
|
1795
|
+
...(want.labels ? [labelField(false)] : []),
|
|
1796
|
+
]
|
|
1797
|
+
const search = `repo:${this.fullName} is:issue is:closed reason:completed`
|
|
1798
|
+
type CountData = {
|
|
1799
|
+
repository: {
|
|
1800
|
+
open?: { totalCount: number }
|
|
1801
|
+
closed?: { totalCount: number }
|
|
1802
|
+
labels?: {
|
|
1803
|
+
nodes: Array<{
|
|
1804
|
+
name: string
|
|
1805
|
+
description?: string | null
|
|
1806
|
+
issues: { totalCount: number }
|
|
1807
|
+
}>
|
|
1808
|
+
pageInfo: { hasNextPage: boolean; endCursor: string | null }
|
|
1809
|
+
}
|
|
1810
|
+
} | null
|
|
1811
|
+
completed?: { issueCount: number }
|
|
1812
|
+
}
|
|
1813
|
+
const data = await this.graphql<CountData>(
|
|
1814
|
+
'counts',
|
|
1815
|
+
`query StateCounts($owner: String!, $name: String!${want.closed ? ', $search: String!' : ''}) { repository(owner: $owner, name: $name) { ${fields.join(' ')} }${want.closed ? ' completed: search(type: ISSUE, query: $search) { issueCount }' : ''} }`,
|
|
1816
|
+
{ owner: this.owner, name: this.repo, ...(want.closed ? { search } : {}) },
|
|
1817
|
+
)
|
|
1818
|
+
if (data.repository === null)
|
|
1819
|
+
throw new Error(`github counts: repository ${this.fullName} is not readable`)
|
|
1820
|
+
const labelNodes = [...(data.repository.labels?.nodes ?? [])]
|
|
1821
|
+
let pageInfo = data.repository.labels?.pageInfo
|
|
1822
|
+
while (pageInfo?.hasNextPage && pageInfo.endCursor) {
|
|
1823
|
+
const more = await this.graphql<CountData>(
|
|
1824
|
+
'counts',
|
|
1825
|
+
`query StateLabelCounts($owner: String!, $name: String!, $labelsAfter: String) { repository(owner: $owner, name: $name) { ${labelField(true)} } }`,
|
|
1826
|
+
{ owner: this.owner, name: this.repo, labelsAfter: pageInfo.endCursor },
|
|
1827
|
+
)
|
|
1828
|
+
labelNodes.push(...(more.repository?.labels?.nodes ?? []))
|
|
1829
|
+
pageInfo = more.repository?.labels?.pageInfo
|
|
1830
|
+
}
|
|
1831
|
+
const rejected = rejectedStateOf(this.lifecycle)
|
|
1832
|
+
const names = lifecycleNames(this.lifecycle)
|
|
1833
|
+
if (this.lifecycle.rejected === undefined) names.push(NOT_PLANNED_STATE)
|
|
1834
|
+
const labelCounts = new Map<string, number>()
|
|
1835
|
+
const about = new Map<string, string>()
|
|
1836
|
+
for (const node of labelNodes) {
|
|
1837
|
+
// `labels(query:)` also matches names merely containing the prefix.
|
|
1838
|
+
if (!isStateLabel(node.name)) continue
|
|
1839
|
+
const suffix = node.name.slice(STATE_LABEL_PREFIX.length)
|
|
1840
|
+
const name = names.find((known) => holdsState(known, suffix)) ?? suffix
|
|
1841
|
+
if (!names.includes(name)) names.push(name)
|
|
1842
|
+
labelCounts.set(name, (labelCounts.get(name) ?? 0) + node.issues.totalCount)
|
|
1843
|
+
if (node.description) about.set(name, node.description)
|
|
1844
|
+
}
|
|
1845
|
+
const completed = data.completed?.issueCount ?? 0
|
|
1846
|
+
const closedTotal = data.repository.closed?.totalCount ?? 0
|
|
1847
|
+
const openTotal = data.repository.open?.totalCount ?? 0
|
|
1848
|
+
const count = (name: string): number => {
|
|
1849
|
+
if (holdsState(name, this.lifecycle.done)) return completed
|
|
1850
|
+
if (holdsState(name, rejected)) return Math.max(0, closedTotal - completed)
|
|
1851
|
+
if (holdsState(name, this.lifecycle.triage)) {
|
|
1852
|
+
let labelled = 0
|
|
1853
|
+
for (const [state, tickets] of labelCounts)
|
|
1854
|
+
if (!holdsState(state, this.lifecycle.triage)) labelled += tickets
|
|
1855
|
+
return Math.max(0, openTotal - labelled)
|
|
1856
|
+
}
|
|
1857
|
+
return labelCounts.get(name) ?? 0
|
|
1858
|
+
}
|
|
1859
|
+
return { names, about, count }
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
async addState(
|
|
1863
|
+
name: string,
|
|
1864
|
+
opts: { about?: string } = {},
|
|
1865
|
+
): Promise<{ state: TicketStateInfo; created: boolean }> {
|
|
1866
|
+
validateStateName(name, SOURCE)
|
|
1867
|
+
if (!representableState(name))
|
|
1868
|
+
throw new Error(
|
|
1869
|
+
`${SOURCE}: "${stateLabel(name)}" is a label Autobuild itself applies, so "${name}" cannot be a state`,
|
|
1870
|
+
)
|
|
1871
|
+
const about = validateStatePurpose(opts.about, SOURCE)
|
|
1872
|
+
if (about !== undefined && about.length > LABEL_DESCRIPTION_MAX)
|
|
1873
|
+
throw new Error(
|
|
1874
|
+
`${SOURCE}: a state purpose is at most ${LABEL_DESCRIPTION_MAX} characters (GitHub's label description limit)`,
|
|
1875
|
+
)
|
|
1876
|
+
const clash = (await this.stateNames()).find((known) => holdsState(known, name))
|
|
1877
|
+
if (clash !== undefined)
|
|
1878
|
+
throw new Error(
|
|
1879
|
+
`${SOURCE}: state "${name}" already exists as "${clash}" — state names are unique ignoring letter case`,
|
|
1880
|
+
)
|
|
1881
|
+
try {
|
|
1882
|
+
await this.must('addState', 'POST', this.path('/labels'), {
|
|
1883
|
+
body: { name: stateLabel(name), color: LABEL_COLOR, description: about ?? '' },
|
|
1884
|
+
})
|
|
1885
|
+
} catch (error) {
|
|
1886
|
+
if (statusOf(error) === 422)
|
|
1887
|
+
throw new Error(`${SOURCE}: state "${name}" already exists`, { cause: error })
|
|
1888
|
+
throw error
|
|
1889
|
+
}
|
|
1890
|
+
this.knownLabels.add(stateLabel(name).toLowerCase())
|
|
1891
|
+
return { state: { name, tickets: 0, ...(about !== undefined ? { about } : {}) }, created: true }
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
// ── Ready assignee ────────────────────────────────────────────────────────
|
|
1895
|
+
|
|
1896
|
+
/** The credential's owner: one `GET /user`. A credential with no user
|
|
1897
|
+
* (an App installation token) answers 401, 403 or 404. */
|
|
1898
|
+
private async readViewer(): Promise<Viewer> {
|
|
1899
|
+
let response: Response | null
|
|
1900
|
+
try {
|
|
1901
|
+
response = await this.request('readyAssignee', 'GET', 'user', { missing: true })
|
|
1902
|
+
} catch (error) {
|
|
1903
|
+
const status = statusOf(error)
|
|
1904
|
+
if (status === 401 || status === 403) return { noUser: true }
|
|
1905
|
+
throw error
|
|
1906
|
+
}
|
|
1907
|
+
if (response === null) return { noUser: true }
|
|
1908
|
+
return { login: z.object({ login: z.string() }).passthrough().parse(response.json).login }
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
/** Dispatcher startup, before the loop: resolve the credential's owner once,
|
|
1912
|
+
* so neither a tick nor a reload ever sends `GET /user`. */
|
|
1913
|
+
async prepareReadyAssignee(): Promise<void> {
|
|
1914
|
+
if (this.viewer !== undefined && !('failed' in this.viewer)) return
|
|
1915
|
+
try {
|
|
1916
|
+
this.viewer = await this.readViewer()
|
|
1917
|
+
} catch (error) {
|
|
1918
|
+
this.viewer = { failed: message(error) }
|
|
1919
|
+
throw error
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
|
|
1923
|
+
readyAssigneeRefusal(value: string): string | undefined {
|
|
1924
|
+
if (!GITHUB_READY_ASSIGNEE.accepts(value)) return GITHUB_READY_ASSIGNEE.message
|
|
1925
|
+
if (value !== 'me') return undefined
|
|
1926
|
+
if (this.viewer === undefined || 'failed' in this.viewer)
|
|
1927
|
+
return `github tickets: [tickets].readyAssignee = "me" but the GitHub credential owner could not be resolved at dispatcher startup (${
|
|
1928
|
+
this.viewer === undefined ? 'not prepared' : this.viewer.failed
|
|
1929
|
+
}); restart dispatch to enable readyAssignee = "me"`
|
|
1930
|
+
return 'noUser' in this.viewer ? NO_USER_ASSIGNEE : undefined
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
/** The login a `readyAssignee` value names. An unprepared one-shot surface
|
|
1934
|
+
* (`ab ticket list`, init validation) resolves `"me"` once, lazily. */
|
|
1935
|
+
private async assigneeLogin(value: string): Promise<string> {
|
|
1936
|
+
if (value !== 'me') return value
|
|
1937
|
+
if (this.viewer === undefined || 'failed' in this.viewer) this.viewer = await this.readViewer()
|
|
1938
|
+
if ('noUser' in this.viewer) throw new Error(NO_USER_ASSIGNEE)
|
|
1939
|
+
return (this.viewer as { login: string }).login
|
|
1940
|
+
}
|
|
1941
|
+
|
|
1942
|
+
async describeReadyAssignee(value: string): Promise<string> {
|
|
1943
|
+
if (value === 'me') await this.prepareReadyAssignee()
|
|
1944
|
+
const refusal = this.readyAssigneeRefusal(value)
|
|
1945
|
+
if (refusal !== undefined) throw new Error(refusal)
|
|
1946
|
+
const login = await this.assigneeLogin(value)
|
|
1947
|
+
const check = await this.request(
|
|
1948
|
+
'readyAssignee',
|
|
1949
|
+
'GET',
|
|
1950
|
+
this.path(`/assignees/${encodeURIComponent(login)}`),
|
|
1951
|
+
{ missing: true },
|
|
1952
|
+
)
|
|
1953
|
+
if (check === null)
|
|
1954
|
+
throw new Error(
|
|
1955
|
+
`github tickets: [tickets].readyAssignee "${login}" cannot be assigned issues in ${this.fullName} — use a GitHub username with access to the repository, or "me"`,
|
|
1956
|
+
)
|
|
1957
|
+
return `${value} → @${login}`
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
// ── Init validation ───────────────────────────────────────────────────────
|
|
1961
|
+
|
|
1962
|
+
/** One specific message per access problem, for `ab init --validate`. */
|
|
1963
|
+
async validateAccess(): Promise<void> {
|
|
1964
|
+
const miss = await this.credentialMiss?.()
|
|
1965
|
+
if (miss !== undefined) throw new Error(`github tickets: no GitHub token — ${miss}`)
|
|
1966
|
+
let repository: Response | null
|
|
1967
|
+
try {
|
|
1968
|
+
repository = await this.request('validate', 'GET', this.path(), { missing: true })
|
|
1969
|
+
} catch (error) {
|
|
1970
|
+
if (statusOf(error) === 401 || statusOf(error) === 403)
|
|
1971
|
+
throw new Error(`github tickets: token cannot read ${this.fullName} — ${message(error)}`)
|
|
1972
|
+
throw error
|
|
1973
|
+
}
|
|
1974
|
+
if (repository === null) throw new Error(`github tickets: token cannot read ${this.fullName}`)
|
|
1975
|
+
const info = z
|
|
1976
|
+
.object({
|
|
1977
|
+
has_issues: z.boolean().optional(),
|
|
1978
|
+
permissions: z.record(z.string(), z.unknown()).optional(),
|
|
1979
|
+
})
|
|
1980
|
+
.passthrough()
|
|
1981
|
+
.parse(repository.json)
|
|
1982
|
+
if (info.has_issues === false)
|
|
1983
|
+
throw new Error(`github tickets: issues are disabled on ${this.fullName}`)
|
|
1984
|
+
try {
|
|
1985
|
+
await this.request('validate', 'GET', this.path('/issues'), { query: { per_page: '1' } })
|
|
1986
|
+
} catch (error) {
|
|
1987
|
+
const status = statusOf(error)
|
|
1988
|
+
if (status === 403 || status === 404 || status === 410)
|
|
1989
|
+
throw new Error(
|
|
1990
|
+
`github tickets: token cannot read the issues of ${this.fullName} — ${message(error)}`,
|
|
1991
|
+
)
|
|
1992
|
+
throw error
|
|
1993
|
+
}
|
|
1994
|
+
// Repository push access says nothing about a fine-grained or App token's
|
|
1995
|
+
// Issues permission, so probe issue creation itself with no title: GitHub
|
|
1996
|
+
// authorizes before it validates, so a writer is refused for the missing
|
|
1997
|
+
// title (422) and nothing is created, while a reader is refused (403/404).
|
|
1998
|
+
const readOnly = new Error(
|
|
1999
|
+
`github tickets: token cannot write the issues of ${this.fullName} — grant Issues: read and write`,
|
|
2000
|
+
)
|
|
2001
|
+
try {
|
|
2002
|
+
await this.must('validate', 'POST', this.path('/issues'), { body: {} })
|
|
2003
|
+
} catch (error) {
|
|
2004
|
+
const status = statusOf(error)
|
|
2005
|
+
if (status === 403 || status === 404) throw readOnly
|
|
2006
|
+
if (status === 422 && /title/i.test(apiDetail(error))) {
|
|
2007
|
+
this.assertLabelRole(info.permissions)
|
|
2008
|
+
return
|
|
2009
|
+
}
|
|
2010
|
+
throw new Error(
|
|
2011
|
+
`github tickets: could not confirm the token can write the issues of ${this.fullName} — ${message(error)}`,
|
|
2012
|
+
{ cause: error },
|
|
2013
|
+
)
|
|
2014
|
+
}
|
|
2015
|
+
throw new Error(
|
|
2016
|
+
`github tickets: could not confirm the token can write the issues of ${this.fullName} — GitHub accepted an issue without a title`,
|
|
2017
|
+
)
|
|
2018
|
+
}
|
|
2019
|
+
|
|
2020
|
+
// GitHub silently drops label changes from a user below triage, and ticket
|
|
2021
|
+
// states are labels. App tokens report no user permissions; their Issues
|
|
2022
|
+
// permission alone governs labels, which the write probe checks.
|
|
2023
|
+
private assertLabelRole(roles: Record<string, unknown> | undefined): void {
|
|
2024
|
+
if (roles !== undefined && !LABEL_ROLES.some((role) => roles[role] === true))
|
|
2025
|
+
throw new Error(
|
|
2026
|
+
`github tickets: token cannot set labels on ${this.fullName} — GitHub silently drops label changes without triage or push access; grant the token's user write (or triage) access`,
|
|
2027
|
+
)
|
|
2028
|
+
}
|
|
2029
|
+
}
|