Skip to main content

onetaskgraph_github_projects/
lib.rs

1//! A stateless onetaskgraph source over one GitHub Projects v2 board.
2//!
3//! **A write held to a version** (`--if-version`) is checked immediately before its first
4//! mutation and not as one step with it: GitHub takes no conditional write, so the engine reads
5//! the task through this source just before writing it, and a change landing between that read
6//! and the mutation — the time one request takes — is GitHub's residual race.
7//!
8//! **A board is a container of projects, not a project.** Its own `title`,
9//! `shortDescription` and `readme` are never read as an item's fields and are never
10//! written: nothing in this source can rename the board a user configured.
11//!
12//! **A project is an issue and its tasks are that issue's sub-issues.** GitHub's schema
13//! decides that: `Issue` exposes `parent`, `subIssues` and `subIssuesSummary`, and
14//! `DraftIssue` exposes none of them. Creating an issue needs a `repositoryId`, and a
15//! board has none, so a write without [`GitHubProjectsConfig::repository`] is refused
16//! naming the field — but that repository is the *fallback*, not the home of every item.
17//!
18//! <!-- llmlint: ignore-block[contracts_have_one_source_or_a_drift_gate] The rule's one
19//! executable source is `GitHubProjectsSource::creation_target`; this is where a reader of
20//! the module meets it, and `tests/plugin.rs` drives every arm below against the loopback
21//! board and asserts on `createIssue`'s own `repositoryId`, so the prose cannot outlive a
22//! change to the rule. -->
23//! **Which repository an issue is created in is decided by the item's own `repositories`
24//! field, under one rule.** Exactly one entry names the repository the issue is created in:
25//! a task issue is where a person finds the work from the repository it changes, and one
26//! filed in a board's nominated repository is invisible from every other. Zero entries, or
27//! two or more, name none, so a task's or a document's issue is created in the repository
28//! its parent project's issue lives in — read from the board, or from this process's own
29//! record of a project it created earlier in the same command — and a project's issue, or
30//! a task or document written with no parent, is created in the configured `repository:`.
31//! What that rule refuses, it refuses before `createIssue`, so no issue is half-created. An
32//! existing issue is never moved: the update path leaves the issue where it is and records
33//! the list in the metadata slot when it differs, so the read side's derivation and the
34//! creation rule agree by construction.
35//! <!-- llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate] -->
36//!
37//! **A document is an ordinary issue whose title begins [`DESIGN_TITLE_PREFIX`].** A
38//! board has no document type and nothing but issues to hold one in, so the title is the
39//! discriminator and it is the whole of it. The title this source *reports* is the one a
40//! person wrote, with the prefix taken off — the same way the metadata slot is taken off
41//! the body so `content` is what the person wrote — and writing a document puts the prefix
42//! back, so a round trip returns the title that went in.
43//!
44//! **Telling a document from a project from a task.** The design prefix is read **first**:
45//! a document is never a project and never a task, whatever sub-issues it has or does not
46//! have. Only then does the rest apply — a board issue is a project when *either* it has
47//! sub-issues *or* it carries [`ItemKind::METADATA_KEY`]; otherwise it is a task. A
48//! sub-issue is always a task, whatever it carries. The marker is sufficient and never
49//! necessary: it is what makes an *empty* project — the state a project copy passes
50//! through between creating the project and filing its first task — readable as a
51//! project, while the sub-issue arm lets a person author a project on the board by hand
52//! with no knowledge of this product's metadata at all. Reading the prefix later than the
53//! sub-issue rule would make a design issue with no sub-issues an empty project, which is
54//! exactly the state that rule exists to catch. Pull requests are neither a project nor a
55//! task nor a document and are ignored.
56//!
57//! **A task's comments are its issue's comments.** They are read off `Issue.comments` and
58//! written with `addComment`, `updateIssueComment` and `deleteIssueComment`, and a comment's
59//! id is GitHub's own node id for the `IssueComment`. Two things GitHub decides are refused
60//! rather than papered over: a board **draft** is not an issue and has no comments at all, so
61//! a comment call on one is refused rather than answered with an empty page; and GitHub signs
62//! every comment as the account the token belongs to, so a comment handed an author of its
63//! own is refused rather than posted under another name. GitHub's comment mutations take the
64//! comment's id and nothing else, so an edit or a delete first reads which issue that comment
65//! is on, and a comment on some other issue is one this task does not have.
66//!
67//! **Where an entity is, is a link.** Every project, task and document this source reports
68//! carries a [`Location::Url`] naming the issue's own web address — the same address the
69//! `url` field already reports, in the shape that says a reader can open it. That is the
70//! contrast the location contract exists for: a reader holding an entity from this source
71//! is handed something to link to and one holding an entity from a folder of Markdown is
72//! handed a path, and neither has to know which plugin answered. It does not replace or
73//! derive from `url`; that field goes on reporting what it always reported.
74//!
75//! **Where metadata lives.** Short typed things go to typed fields and native relations:
76//! status to the board's `Status` single-select and the issue's own state, the copy
77//! origin to a source-owned `onetaskgraph.origin` text field, and dependencies to
78//! `blockedBy` and to sub-issue links. Unbounded caller JSON goes in a trailing
79//! `<!-- onetaskgraph.metadata ... -->` comment at the end of the issue body — the same
80//! encoding `docs/metadata.md` settles for Linear, not a second one. A ProjectV2 text
81//! field is length-bounded and `shortDescription` is capped at 300 characters, which is
82//! why neither can hold a caller's own prose. Setting one caller key on its own — on a task,
83//! a project or a document alike — is one update of the issue body that changes that slot
84//! and not one byte outside it, and it is not sent at all when the key already holds the
85//! value. The link a copy records on an item it copied, `onetaskgraph.copies`, is small and
86//! is kept in that same slot, written by that same update.
87//!
88//! **A caller's value can also be projected onto a board text field**, so the board can filter
89//! on it: each [`GitHubProjectsConfig::metadata_fields`] entry names a text field, a top-level
90//! metadata key and a path inside its value. The slot stays the value's one home — every read
91//! reports metadata from it alone — and the field follows it on every write of an item, a
92//! create, an update and a copy alike: a string is written, an array of strings as one line per
93//! element and an object of string values as one `KEY: VALUE` line per entry in byte order of
94//! the keys, shortened past [`TEXT_FIELD_LIMIT`] to its leading whole lines and a line counting
95//! the rest, and none of them sent again while the field holds that text — an empty string,
96//! array or object included, which writes the empty string; nothing there or `null` clears a
97//! field holding a value; any other JSON type is refused before any mutation, the shared rule
98//! [`ProjectedValue`] decides. It rides the ordered [`graphql::UPDATE_FIELDS`]
99//! write beside `Status`, `Priority` and the origin, so it adds no request; a key set on its
100//! own moves its field first and the body last, as every write of an existing item does. A
101//! board without the field, or with a non-text field of that name, is refused before any
102//! mutation pointing at `sources fields`, whose [`GitHubProjectsSource::fields`] creates it as
103//! a text field and never changes a field that is there.
104//!
105// llmlint: ignore-block[contracts_have_one_source_or_a_drift_gate] This public module documentation is a required user-facing description; the loopback plugin tests and shared live journey drive StatusMapping resolution, both mutations, and observed read-back together.
106//! **Status.** `status_mapping` is per-instance configuration, in the shared grammar
107//! [`onetaskgraph_plugin_api::StatusMapping`] documents, from a status category to an
108//! option of the board's one `Status` field for a task and for a project: a bare name is
109//! the option for both kinds, `null` disables the category for both, and `{task, project}`
110//! names it per kind. A category the mapping does not mention keeps its shipped default for
111//! both kinds; one it mentions is exactly what it configures, so a per-kind object no longer
112//! gets the shipped default for the kind it leaves out. Two categories one kind would read
113//! back from one option are refused as the configuration is read, ignoring case, while one
114//! option may stand for different categories of the two kinds. Writes go by the kind of the
115//! item written: a status that kind has no option for, or whose option the board lacks, is
116//! refused before any mutation, naming the source, the kind, the category and the key
117//! `status_mapping.<category>.<kind>` — there is no fallback. `done` selects its mapped
118//! option and closes the issue as `COMPLETED`; `cancelled` selects its mapped option and
119//! closes it as `NOT_PLANNED`, for either kind. Every open category reopens a closed issue
120//! before selecting its option. Reads give a closed issue's reason precedence over its
121//! option, while an open issue's option decides its category through its own kind's
122//! mapping, and an option that mapping does not name reads as `unknown` under its own name.
123//! The guarded [`GitHubProjectsSource::status_options`] and
124//! [`GitHubProjectsSource::fields`] operations are the one path here that calls
125//! `updateProjectV2Field`: GitHub replaces the whole option list, so they preserve every
126//! existing option id and verify the field and item assignments immediately afterwards.
127//! They ask for both kinds' options, counting a terminal category's mapped option as
128//! configured because a terminal write refuses without it. No ordinary source read or
129//! write calls that mutation, whose
130//! `singleSelectOptions` *overwrites* a field's option set, so no addition is additive
131//! and a mistake destroys every item's status. A status this board cannot represent is a
132//! refusal naming the status and the instance instead.
133//!
134//! `unknown` has no shipped option because this source cannot preserve an open-ended
135//! status word: it writes an existing board option and never
136//! creates an option. An operator may map `unknown` to one existing option, in which case
137//! every unknown word lands on that option and reads back as `unknown` under the option's
138//! name. This differs from `local-md`, which writes and reads the original word itself.
139//!
140//! The shipped terminal options are exactly `done: Done` and `cancelled: Cancelled`.
141//! `done` also closes the issue because GitHub derives `subIssuesSummary.completed`
142//! and the board's own `Sub-issues progress` field from closed sub-issues: a plan whose
143//! finished tasks were only moved to a "Done" column would read 0% complete forever.
144// llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate]
145//!
146//! # What this source declares, field by field
147//!
148//! One verdict per field of [`Capabilities`], and what `Native` means when this source
149//! says it. *Proven* means a shared journey drives it against the real
150//! binary over this source's own row in `crates/onetaskgraph-e2e-support/src/fixtures.rs`, and
151//! `every_row_declares_exactly_what_its_plugin_reports` is what keeps this list and
152//! [`capabilities`](TaskSource::capabilities) from parting.
153//!
154//! | Field | Verdict |
155//! | --- | --- |
156//! | `projects` | **Supported and proven,** and the one predicate here that is pushed down rather than applied in process: a task's project is the issue it is a sub-issue of, so a listing scoped to one *asks that issue* for its own sub-issues. This is the field that was declared and then not applied, which silently returned another project's tasks. |
157//! | `documents` | **Supported and proven.** A board holds issues, so a document is one: the issue whose title begins [`DESIGN_TITLE_PREFIX`]. Reads, filters and paging answer on exactly the terms a task read does, and a write puts the prefix back. |
158//! | `comments` | **Supported and proven,** over the task issue's own comment connection, oldest first and paged by GitHub's own cursor; added, edited and removed through GitHub's comment mutations, paced as every other mutation is. A draft item has no comments on GitHub and is refused, and so is an author, because GitHub records the signed-in account as every comment's author. |
159//! | `assets` | **Supported and native.** Image references travel as GitHub user attachments in the repository the task or document issue lives in. Uploads are authenticated and verified before the issue body is written. |
160//! | `priority` | **Supported and proven** by an instance configured with `priority_mapping`, and declared unsupported by one without it, which reports every task's priority as `none` and sends exactly the requests it sent before priorities existed. The priority is the board's single-select `Priority` field: no value is `none`, a mapped option is its level, matched case-insensitively, and an option the mapping does not name fails the read of that task, naming the option. A write selects the mapped option, or clears the value for `none`; a board without the field or the option is refused, pointing at `sources fields`, which is the one thing that creates either. |
161//! | `assignees` | **Supported and proven when `config.assignees: true`,** unsupported otherwise, which reads no issue's assignees and sends exactly the requests it sent before assignees existed. An issue's `assignees` by login, every one it holds, selected on the reads the source already makes; a write replaces them with one login or none as one more aliased field of the document the write already sends, and a login GitHub refuses, or answers leaving off the issue, is refused for that item naming it. See [`assignees`] for the login lookup. Proven by `onetaskgraph-github-projects-e2e`'s `assignees` journeys. |
162//! | `filter_by_priority` | **Supported and proven,** over the priority each task reads as — `none` for every task of an instance without `priority_mapping`. |
163//! | `filter_by_comment_activity` | **Supported, and exact** for comments created and for comments edited at or after `commented_since`, in every repository — of any owner — the board's items live in. Applied by asking a narrower question rather than by reading the board: GitHub's issue search scoped by `project:<owner>/<number>` alone, with an `updated:>=` qualifier, names the candidates, and each candidate's own comments confirm it, so `ProjectV2.items` is never read. That rests on GitHub moving an issue's `updatedAt` when a comment on it is added **or edited**, which the credentialed journey `an_edited_comment_moves_its_issue_and_is_selected_since` re-takes on every run of this lane. The search is an index that lags a write — the credentialed lane has watched it miss a newly commented issue for thirty seconds — so an issue this process itself commented on in the same command is a candidate whatever the search says, read by its own node if the search did not name it, and has its comments read rather than being ruled out by an `updatedAt` from before the comment. A comment another process wrote is found only once the index has it, so a caller asking again from its last instant should overlap the two generously. |
164//! | `orphan_tasks` | **Supported and proven.** A task issue with no `parent` is in no project. |
165//! | `filter_by_label` | **Supported and proven,** over the issue's own labels. |
166//! | `filter_by_status` | **Supported and proven,** over the board's `Status` option and the issue's open or closed state, through this instance's own `status_mapping` for the item's kind — a task query by the task half, a project query by the project half, `unknown` included. |
167//! | `filter_by_metadata` | **Supported, and asked of GitHub** — through the body and never through a projected `metadata_fields` text field, which is the board's to filter on and not this source's to read. A query naming metadata values is one board-scoped issue search with each value a quoted phrase `in:body` — GitHub's index covers the metadata comment at the end of the body, which is where caller metadata lives — and every candidate is confirmed against its own parsed metadata comment, so only an item holding that string at that key and path is returned. **A value with no letter or digit is refused** — the empty string, whitespace or punctuation alone — before any request, as a `SourceError::Refused` (wire kind `refused`) naming the value: GitHub's index holds words, so no bounded query can find such a value, and this source neither reads the whole board for it nor answers it as empty. |
168//! | `filter_by_origin` | **Supported, and asked of GitHub without enumerating the board.** The union of three reads, each confirmed by an exact match against the item's own origin field: the board's field filter over the `onetaskgraph.origin` text field, the issue search for the id as a phrase in the body where a write of this release mirrors it, and this process's own writes. See *Where a read-after-write guarantee comes from* for the window the three leave. |
169//! | `reconcile_status` | **Supported,** and proven by `onetaskgraph-github-projects-e2e`'s `status_reconcile.rs`: the board's own `ProjectV2.items(query:)` filter, `is:closed`, read page by page and never the unfiltered items, each candidate confirmed from its own item node — a closed task whose card is not at the option the mapping gives its closure's category. |
170//! | `complete_by_issue` | **Supported,** and proven by `status_complete.rs` there and in the engine's suite: each issue a reference names read in one aliased request per fifty — its repository, its number, its first page of board memberships with each card's `Status` read by name — and nothing else of the board. |
171//! | `search_title` | **Supported, and asked of GitHub for a task,** over `Issue.title`: a task query's text is one board-scoped issue search for it as a phrase `in:title`, every candidate confirmed by the case-insensitive substring rule. GitHub matches whole words, so a task holding the text only inside a longer word is not returned — a narrowing this source declares rather than hides. **A text with no letter or digit that is not blank is refused** — `--` for one — before any request, as the same `refused` error naming the text, for the reason a metadata value like it is; a blank text is not refused, and keeps the board read it always had, confirmed by the same substring rule. A project query's text, and a document query's text when the query is scoped to no project, is that same board-scoped search for the same phrase in the same fields, refused on the same terms, every candidate confirmed by its kind and by the same substring rule, so it narrows exactly as a task's does; a document query scoped to one project sends no search, reads that project's sub-issues and confirms its text over them by the substring rule alone, so it is neither narrowed to whole words nor refused for a text with no letter or digit. A board draft is not an issue, so no text search lists one, a draft titled as a document included. |
172//! | `search_content` | **Supported,** on the same terms, `in:body`, over the visible body — the trailing metadata comment is not part of what the substring rule confirms. |
173//! | `task_dependencies` | **Supported and proven,** in both directions: `blockedBy` and `blocking`. |
174//! | `project_dependencies` | **Supported and proven,** in both directions, over the same two connections, because a project here is an issue. |
175//! | `max_page_size` | **Supported and proven.** [`MAX_PAGE_SIZE`], GitHub's own connection maximum. |
176//!
177//! Image writes use `POST https://uploads.github.com/user-attachments/assets` with `name`,
178//! `content_type` and the issue repository's numeric `repository_id` as query parameters,
179//! the source token as `Authorization: Bearer`, the image content type as `Content-Type`,
180//! and the raw bytes as the request body. The numeric repository id is read at most once
181//! per repository per source instance. A loopback API endpoint also selects the loopback
182//! uploads host; production needs no assets repository, commits or extra configuration.
183//! Every returned JSON `url` is read with the same token before a body is written: only
184//! a 2xx verification succeeds. A refusal names the asset, URL and HTTP status; an
185//! anonymous 404 does not invalidate an authenticated 200. An upload refusal names the
186//! asset and HTTP status and says the token type may not be accepted by the upload
187//! endpoint. A classic PAT was measured accepted; no acceptance claim is made about
188//! fine-grained PATs or OAuth tokens.
189//! The body keeps the authored alt text while `./<name>` becomes the attachment URL,
190//! and `onetaskgraph.assets` records `{sha256, url}` by name. A matching destination
191//! SHA-256 reuses its URL without an upload or verifying read; changed bytes are uploaded
192//! and verified afresh, in the repository the issue already lives in on an update.
193//! An uploaded image renders for the viewers GitHub lets read it, like the issue text beside it.
194//! Uploads take the same mutation spacing as content writes. Both uploads and verification
195//! reads wait out classified rate limits within the configured per-call retry budget,
196//! on the supplied clock; verifying reads take no mutation slot.
197//!
198//! Nothing here is unsupported. `documents` and `comments` are not predicates — they say this
199//! source has documents and that its tasks have comments, both of which hold — and the three
200//! facts behind the uniform `Native` on the
201//! predicates beside it are recorded below rather than re-derived, because a reader who
202//! takes `Native` to mean *the remote service filters* will read that uniformity as a
203//! lie.
204//!
205//! First, the plugin contract defines `Support::Native` as *the source applies this
206//! predicate itself*, and says nothing about where it applies it. What the declaration
207//! promises the engine is capability rule 1 — a predicate declared `Native` **is** applied
208//! — so that the engine may push it down and apply nothing of its own.
209//!
210//! Second, this source can keep that promise for every predicate at no additional API
211//! cost, because whichever of the reads below answers a query has already read every
212//! candidate that query will return before it filters anything. Filtering those items is
213//! in-process work over data already in hand.
214//!
215//! Third, six task predicates are asked of GitHub as a narrower question and the rest are
216//! applied in process over what that question returned. A project filter has a relationship — a
217//! project's tasks are that issue's sub-issues, and asking the issue for them is both cheaper
218//! and exact. Comment activity is the issue search's `updated:` qualifier. A text search, and
219//! a search for metadata values, is the board-scoped issue search carrying the text and each
220//! value as quoted phrases; an origin is the board's own field filter over its origin field
221//! beside the same search for the id. **The text search narrows, and that is this source's
222//! declared semantics:** GitHub matches whole words where the substring rule this source and
223//! the local Markdown source confirm with would match inside one, so an item holding the text
224//! only inside a longer word is never a candidate. Every item returned does contain the text.
225//! A project query's text, and a document query's scoped to no project, is that same search
226//! and narrows on the same terms, its candidates confirmed by their kind as well.
227//! GitHub's issue search offers no qualifier for a label set, a status column or a priority,
228//! so those three are applied in process over the candidates, and a query carrying none of
229//! the six narrowing predicates reads the board. Declaring one `Unsupported` would make the
230//! engine compensate for work this source has already done, and declaring `projects` native
231//! while ignoring the filter (which this source once did) silently returns another project's
232//! tasks, because the engine trusts the declaration and applies nothing locally.
233//!
234//! # The three ways this source reaches an item, and what each costs
235//!
236//! A board read is charged for what its *nested* connections could return rather than for
237//! what was asked, so one whole-board read costs the same whether the question was about
238//! one project or about all of them. That is why a question about one project is never
239//! answered by reading the board:
240//!
241//! | The question | What is sent | What it costs |
242//! | --- | --- | --- |
243//! | one item, by its own id | [`graphql::ISSUE`] — `node(id:)`, carrying the field definitions of the boards it sits on and the far ends of its `blockedBy`, which is what a write of it needs — and, when that node is a board draft, [`graphql::DRAFT`] — the draft and the one board item it is | the item |
244//! | one task with its first page of comments, for `task show` and a comment listing | [`graphql::ISSUE_DETAIL`] — the same `node(id:)` read with the issue's `comments` | the item and a page of its comments |
245//! | one board page with each task's first comments, for `TaskSource::query_task_details` | [`graphql::BOARD_WITH_COMMENTS`] — the board's own `items`, without search completion | tasks and first comment pages in one request; board consistency, with comment-activity filtering refused |
246//! | several tasks with their comments, for `task show-many` | [`graphql::ISSUE_DETAILS`] — [`DETAIL_BATCH`] aliased `node(id:)` fields per request | each item and a page of its comments |
247//! | the board's own id and field definitions, for a write whose item does not carry them | [`graphql::BOARD_FIELDS`] — the board's `id` and `fields`, and no `items` — or, for a create that needs the repository's id too, [`graphql::CREATION_CONTEXT`], both in one request | the board's fields |
248//! | one project's tasks or documents | [`graphql::SUB_ISSUES`] — that issue's own `subIssues` | that project |
249//! | which projects this board holds | [`graphql::SEARCH_ISSUES`] — an issue search scoped to the board | the board's issues, without their board items |
250//! | which projects hold a text, or which documents do when no project narrows the question | [`graphql::SEARCH_ISSUES`] — the board-scoped search with the text as one quoted phrase, `in:title`, `in:body` or both, as a task's text is sent — walked to its end in pages of twenty | the issues that match |
251//! | which tasks were commented on since an instant | [`graphql::SEARCH_ISSUES`] — the same board-scoped search with an `updated:>=` qualifier — then [`graphql::ISSUE_COMMENTS`] for each candidate it names | the issues updated since, and their comments |
252//! | which tasks hold a text, or a metadata value | [`graphql::SEARCH_ISSUES`] — the board-scoped search with the text and each value as quoted phrases, `in:title`, `in:body` or both, and an `updated:>=` qualifier too when comment activity is asked for — in pages of twenty, only as many as the caller's rows need | the issues that match |
253//! | which tasks were copied from one origin | [`graphql::ORIGIN_LOOKUP`] — the board's own `items` under its field filter on the origin field, and the same board-scoped search for the id `in:body`, in one request, each paged at three | the carriers of that origin, which is one item |
254//! | every task, every document, every label, when nothing above narrows the question | [`graphql::BOARD`] — the board's own `items` — **and** [`graphql::SEARCH_ISSUES`], because neither enumeration of a board is complete alone; see [`GitHubProjectsSource::board`] | the board, twice over |
255//! | which board item one issue is, past the page that came with it | [`graphql::ISSUE_BOARD_ITEMS`] — that issue's own `projectItems` | one issue's memberships |
256//!
257//! The following standalone-ticket requests are pinned by the real CLI fixture journeys
258//! `follow_up_writes_resolve_each_item_once_and_batch_the_copy_fields` and
259//! `a_batched_detail_read_costs_one_request_and_one_point_per_detail_batch`, as request count
260//! equal to declared points equal to the row. They include the origin lookup and the
261//! field/repository discovery a create needs. A bound re-copy changes status, priority,
262//! content and metadata; comment recount means a subsequent detail read. Each request here
263//! costs one declared point. A membership beyond the embedded page can additionally require
264//! the one-point membership recovery described above. A bound re-copy of a task filed under a
265//! project adds one read, the engine confirming that project's link by its own id once per
266//! command; and the same-source far ends a write newly names — those that do not already block
267//! the item, whose own read answered for them — are read together by their own ids,
268//! [`DETAIL_BATCH`] to one [`graphql::ISSUE_DETAILS`] request, each new edge then one
269//! [`graphql::ADD_BLOCKED_BY`]. Both additions are rows of the table below, pinned by
270//! `a_bound_recopy_adds_one_project_read_and_batches_the_dependencies_it_newly_names`.
271//!
272//! **[`DETAIL_BATCH`] is 24**: the largest batch of [`graphql::ISSUE_DETAILS`] the node-count
273//! model prices at one point. Each aliased item is six of GitHub's aggregate, so 24 are 144,
274//! which rounds to one point, and 25 are 150, which rounds to two; `tests/point_cost.rs`
275//! holds both halves.
276//!
277//! **An existing item is written body last.** A bound re-copy and a `task update` send its
278//! board fields first — the `Status` option and the `Priority` together, in one request — then
279//! its parent and its `blockedBy`, and its title, body and state in one `updateIssue` last.
280//! GitHub runs no two requests as one, and runs a document's mutation fields in order without
281//! undoing an earlier field when a later one fails, so that order is what makes a write
282//! refused part-way leave the item's body, and every metadata key in it, exactly as it stood;
283//! the one piece of metadata written before the body, an origin a copy re-points, is put back
284//! when a later write is refused — and when putting it back is refused too, the write's own
285//! refusal names that key, what it now holds and what it held. `crates/onetaskgraph-github-projects-e2e/tests/e2e/write_order.rs` refuses each
286//! of those writes in turn, whole and as one aliased field failing after the one before it.
287//!
288//! **Two facts about GitHub the write rows rest on, each read off GitHub's published schema
289//! artifact <https://docs.github.com/public/fpt/schema.docs.graphql> on 2026-10-01 and pinned
290//! in `tests/fixtures/schema.graphql`, and the first then put to GitHub itself:**
291//!
292//! - **A board is accepted at creation but its item is not answered, so a create still files
293//!   the issue itself: a new copy is 5 requests, and 4 with `--create`.**
294//!   `CreateIssueInput.projectV2Ids: [ID!]` is declared there — "An array of Node IDs for
295//!   Projects V2 associated with this issue", `@possibleTypes(concreteTypes: ["ProjectV2"])`.
296//!   The credentialed journey `real_projects_v2_contract_writes_and_leaves_no_residue` was run
297//!   against a real board on 2026-10-01 with a create sending the board there and reading the
298//!   item off the payload's `Issue.projectItems`: every one of its four creates answered with
299//!   no item on the board, so each went on to [`graphql::ADD_TO_BOARD`], and the fourth was
300//!   refused "Content already exists in this project" — GitHub had filed the issue after
301//!   answering, and refuses a second filing rather than answering with the item it holds. A
302//!   create therefore sends no `projectV2Ids` and files the issue with
303//!   `addProjectV2ItemById`, the one call whose answer names the board item. The saving that is
304//!   real is the read before it: the board's fields and the repository's id together, in
305//!   [`graphql::CREATION_CONTEXT`], at the point the repository is known.
306//! - **A comment still reads its target first, so a comment is 2 requests.**
307//!   `AddCommentInput.subjectId: ID!` is declared there with
308//!   `@possibleTypes(concreteTypes: ["Issue", "PullRequest"], abstractType:
309//!   "IssueOrPullRequest")`. A board draft is no such subject and would be refused, but a
310//!   project's issue, a document's issue, an issue on no board of this source and a pull
311//!   request all are: GitHub writes the comment, so there is no refusal to map into "that is
312//!   not a task of this board". [`graphql::ISSUE`] before [`graphql::ADD_COMMENT`] is what
313//!   refuses those by name.
314//!
315//! | Verb | Requests / points | Documents |
316//! | --- | --- | --- |
317//! | new copy | 4 | ORIGIN_LOOKUPS (the origin, the board's fields and the repository's node and numeric ids together, a page of one carrier for each origin), CREATE_ISSUE filing the issue on the board and under its project, CREATED_BOARD_ITEMS once GitHub has added it, WRITE_FIELD_VALUES |
318//! | copy --create | 4 | CREATION_CONTEXT, CREATE_ISSUE, CREATED_BOARD_ITEMS, WRITE_FIELD_VALUES: the new copy with no origin to ask about |
319//! | bound copy | 3 | ISSUE (with the board's fields and the issue's `blockedBy`, so no BOARD_FIELDS or ISSUE_DEPENDENCIES), UPDATE_FIELDS when a board field differs, then UPDATE_ISSUE last carrying only the title, body or state that differs — none, when nothing does |
320//! | bound copy, filed under a project | 4 | the bound copy's three, and one ISSUE of the destination project its link names, read once per command |
321//! | bound copy, newly naming n dependencies | + ceil(n / DETAIL_BATCH) + n | ISSUE_DETAILS for the far ends that do not already block the item, DETAIL_BATCH (24) to a request (one alone is ISSUE), then one ADD_BLOCKED_BY each; a far end already blocking it is answered by its own read and costs nothing |
322//! | comment | 2 | ISSUE, ADD_COMMENT: the target is read first, because GitHub accepts a comment on any issue or pull request (see below) |
323//! | detail | 1 | ISSUE_DETAIL: the item and its first page of comments, for `task show` and `task comment list`; `--no-comments` is ISSUE alone |
324//! | batched detail | ceil(n / DETAIL_BATCH) | ISSUE_DETAILS: `task show-many` of `n` items, DETAIL_BATCH (24) at a time, comments included or not |
325//! | copy --comments, n changed tasks | ceil(n / COPY_DETAIL_BATCH) | ISSUE_COPY_DETAILS: each task with its first page of comments and its `blockedBy`, COPY_DETAIL_BATCH (21) at a time; a task whose comments run past that page adds one ISSUE_DETAIL per further page, and a task skipped from its listing costs nothing beyond it |
326//! | recount | 1 | ISSUE_DETAIL |
327//! | status | 2 | ISSUE, UPDATE_FIELD; a terminal status additionally updates issue state |
328//! | priority | 2 | ISSUE, UPDATE_FIELD or CLEAR_FIELD, with stored priority in the mutation response |
329//! | content | 2 | ISSUE, UPDATE_ISSUE |
330//! | metadata | 2 | ISSUE, UPDATE_ISSUE |
331//! | document metadata, `--expect` a version | 2 | ISSUE, then UPDATE_ISSUE only when the issue is still at that version — the precondition GitHub's own update cannot take — primed with what the read answered |
332//! | update | 3 | `task update` naming any of title, body, metadata, status and priority — all five included: ISSUE, UPDATE_FIELDS (the status option and the priority together), UPDATE_ISSUE (title, body with its metadata slot, and state) last |
333//! | record only | 1 | ISSUE |
334//!
335//! <!-- github-search-paging:start -->
336//! Board-scoped text, metadata, project-name and comment-activity searches send every
337//! page at `first = 20` (SEARCH_PAGE_SIZE), the SEARCH_ISSUES document's one-point
338//! ceiling. A later page is sent only when `hasNextPage` is true and the caller still
339//! needs rows. A page is never resized to the rows still needed: GitHub orders one
340//! search differently at different page sizes, so one fixed size makes a paged walk
341//! send exactly the requests one whole read sends, and the answer's order is the order
342//! those pages arrive in. A page below twenty would cost the same one point, and GitHub
343//! prices this document by rows, so twenty-row pages cost per row what 100-row pages do.
344//! Project-name lookup continues until an exact match or exhaustion. A task limit bounds
345//! returned and fetched pages: a limit is sliced from the pages it needs, and local
346//! confirmation can require more candidates than matching rows. Walking all pages
347//! returns the whole answer. The opaque version-4 source cursor carries GitHub's page
348//! cursor and how far into that page the last answer stopped, and resumes in the same
349//! process or a new one, without duplicates or gaps. It carries no rows: one process
350//! sends each page's search once, and a new process re-reads only the page it resumes
351//! in, then sends a further page once, never as a re-read, only when its limit still
352//! needs rows. Every request either walk sends is the one a whole read sends for that page. Own writes replace stale index
353//! copies and complete missing rows at exhaustion. Cache entries are whole GitHub pages,
354//! so a small answer cannot truncate a wider question. Origin pages remain three; whole-board sizing is unchanged.
355//! Read-after-write is a per-process guarantee. A cursor resumed in a new process is
356//! not required to include the original process's writes still omitted by the index.
357//! <!-- github-search-paging:end -->
358//!
359//! The board half of an issue — its board item's id, its `Status` option and this
360//! source's origin text field — rides along on `Issue.projectItems` in the first three, so
361//! an item reached any of those ways resolves through the same
362//! [`GitHubProjectsSource::resolve`] the board walk uses and reports the same title, the
363//! same status, the same labels and the same qualified id. That connection comes back a
364//! *page* at a time, at `BOARD_ITEMS_PAGE_SIZE`, so the entry for this board is looked for
365//! on the page in hand and — only if that page reports more of the connection — in the
366//! last row's read of that one issue's memberships, resumed from the page's own cursor and
367//! walked to exhaustion. An issue with no entry for *this* board is not this source's to
368//! report, which is what keeps an id naming another repository's issue from being answered
369//! as an item of this board; and because the page is where the search starts rather than
370//! where it ends, that answer is one about a connection read to exhaustion and never about
371//! an unread page. Nothing costs the extra read but an issue on more boards than a page
372//! holds: an issue this board really does not hold reports no next page, so its
373//! memberships are already exhausted where they arrived.
374//!
375//! **No document here selects the board's own `Labels` field, and nothing is lost by
376//! that.** An item's labels are read from its content alone, wherever that content is
377//! reached: the three documents above select `Issue.labels` on the fragment, and
378//! [`graphql::BOARD`] selects the same connection on the `... on Issue` arm of its
379//! `content`. A board's `Labels` field is not one anybody fills in: it is a built-in
380//! `ProjectV2FieldType`, it is absent from `ProjectV2CustomFieldType` so no project can
381//! create one, and `ProjectV2FieldValue` — the whole of what
382//! `updateProjectV2ItemFieldValue` accepts — offers no way to write one. So GitHub derives
383//! it from the content, for every content type it exists on, and there is nothing it can
384//! hold that the content does not already say: for an `Issue` it *is* that issue's own
385//! labels, so selecting it beside them unions a set with itself.
386//!
387//! **A draft loses nothing by that either**, which is the reasoning this paragraph once had
388//! backwards. `DraftIssue` exposes no `labels` field, and by the three schema facts above
389//! it cannot carry a board `Labels` value to be derived from one — so a draft has nothing
390//! to select *and nothing to lose*, and reports no labels at all. A `PullRequest` item is
391//! discarded by [`GitHubProjectsSource::resolve`] before labels are read. Both halves are
392//! held to that by tests in `tests/plugin.rs`: the four ways an item is reached report one
393//! label set, and that set is the fixture issue's own, by
394//! `an_item_reports_the_same_labels_title_status_and_id_however_it_is_reached`; and a board
395//! item whose content is a draft reports an empty set, by
396//! `a_board_item_whose_content_is_a_draft_reports_no_labels_at_all`. The absence of the
397//! selection is held over [`graphql::DOCUMENTS`] by
398//! `no_document_selects_the_boards_own_labels_field`.
399//!
400//! The whole-board row is still the board's own item connection, and deliberately: a
401//! **draft** board item is not an issue, so no search can list one, and the reads that have
402//! to answer for the whole board are the ones whose cost is the board's size anyway.
403//!
404//! **A question about one item this source already names by id never lists the board.**
405//! Whether that item is on this board, and what its board fields are, is answered by reading
406//! that item — its own `Issue.projectItems`, walked to exhaustion by
407//! [`GitHubProjectsSource::resolve_issue`], or a draft's own board item — and never by
408//! looking for it in [`graphql::BOARD`]'s `items` or in a listing this command already
409//! holds. That covers a write's destination, the project a new item is filed under, a
410//! same-source far end a dependency names, a status write, the dependency slot a draft keeps,
411//! and the delete that takes back an item a copy made. What such a write needs of the board
412//! and the item does not carry — the board's id, the `Status` and origin field definitions —
413//! comes from [`graphql::BOARD_FIELDS`], which reads no item at all. The reason is evidence,
414//! not economy alone: `ProjectV2.items` is a projection that lags the membership GitHub
415//! itself reports — an issue added with `addProjectV2ItemById` can be missing from it for
416//! minutes. Scanning this host's 842-item board has refused a document copy and an update
417//! even though the items' own reads named that board. A scan there gives the wrong answer
418//! as well as paying for every page. So a `board.items` lookup does not belong on any of
419//! those paths.
420//!
421//! **What a read may return is capped too, and that cap is on the document rather than on
422//! the board.** GitHub limits the number of nodes **one query may return** to
423//! [`NODE_COUNT_LIMIT`] and refuses a query above that before executing it: the answer is
424//! an error naming the connection the count crossed at, not a slow or a partial result.
425//! Every board this source reads is refused the same way, so no board is too big for these
426//! documents and none is small enough to save one that is over.
427//!
428//! The count is arithmetic over the document's own text: each connection contributes the
429//! `first:` it asks for, counts **multiply** down a nested path and **sum** across sibling
430//! paths. Those are [GitHub's published rules][node-limits] and this workspace does not
431//! restate them — `github-graphql-node-count` implements them, and
432//! [`worst_case_node_count`] under [`largest_page_sizes`] is where every node count here
433//! comes from. `every_document_this_source_sends_stays_under_githubs_node_limit`, in
434//! `tests/node_count.rs`, recomputes every document in [`graphql::DOCUMENTS`] from that
435//! same text on every run and fails naming any that reaches the limit — so a connection
436//! added to a shared fragment is caught there rather than by GitHub.
437//!
438//! What decides those counts is the page sizes: [`MAX_PAGE_SIZE`] on the outer page,
439//! `NESTED_PAGE_SIZE` on the connections hanging off one item, and
440//! `BOARD_ITEMS_PAGE_SIZE` on the page of an issue's board memberships a read carries.
441//! `$nestedFirst` is spent twice down one path of a board read, so that constant is
442//! effectively squared there, which is why it is the one the limit is most sensitive to.
443//! `BOARD_ITEMS_PAGE_SIZE` is small for a reason of its own, recorded beside it: what a
444//! page of memberships misses is recovered by one further read rather than refused, so it
445//! buys a bound every read pays for at the price of a request only a multi-board issue
446//! pays.
447//!
448//! **`nodeCount` and `cost` are two numbers against two limits, and both are computed
449//! offline here — per document, one document at a time.** `nodeCount` is the one above: the
450//! most nodes one query may return, checked per query and bounded by [`NODE_COUNT_LIMIT`].
451//! `cost` is rate-limit points, metered per hour across everything one credential does; it
452//! is what the two limiters [`Limiter`] tells apart meter, and a document under
453//! [`NODE_COUNT_LIMIT`] still says nothing about its price. [`worst_case_point_cost`] is
454//! that second number, and `tests/point_cost.rs` pins every document in
455//! [`graphql::DOCUMENTS`] at what it costs — there being no per-call point ceiling to hold
456//! one under, the pin itself is the check. The credentialed lane reconciles both figures
457//! against GitHub's own, off a probe it already sends.
458//!
459//! **What is pinned that way is a per-document price and never a session's.** The record in
460//! `session-cost.md` measures the two quantities a whole session can be counted in offline —
461//! **requests** and **worst-case nodes** — and neither is points. What one whole session
462//! consumes of the hourly point allowance is observable only from a credentialed run's own
463//! `x-ratelimit-*` headers, which is what [`accounting`] fills its per-budget figures from
464//! and what `tests/live.rs` prints at the end of every run.
465//!
466//! [node-limits]: https://docs.github.com/en/graphql/overview/rate-limits-and-node-limits-for-the-graphql-api
467//!
468//! **Where a read-after-write guarantee comes from, since neither of GitHub's two
469//! enumerations of a board can supply one alone.** Resolving a node id is strongly
470//! consistent, so a read by id and a project's own sub-issues are already current. The
471//! other two are not, and they are behind by different amounts and in different directions:
472//!
473//! - GitHub's **issue search** is an index and answers a write made moments ago with the
474//!   value from before it — usually for a second or two.
475//! - **`ProjectV2.items`** is a projection GitHub rebuilds behind the write, and an item put
476//!   on a board with `addProjectV2ItemById` can be **absent** from it — not present with its
477//!   content withheld, absent, with the connection walked to its own `hasNextPage: false` —
478//!   for *minutes*, while `Issue.projectItems` names the same membership at once.
479//!
480//! That second one is a measurement rather than a caution. This repository's own
481//! credentialed journey writes a project and waits for the board to report it, then writes a
482//! task and waits for the same thing seconds later on the same board: the project wait is
483//! answered through the search and converged in two or three attempts in each of three runs,
484//! and the task wait is answered through `ProjectV2.items` and converged in none of them
485//! inside thirty. Separately, an item added to a second and larger board was read back by
486//! `Issue.projectItems` on that board's own id while every one of that connection's nine
487//! pages, walked to exhaustion nine minutes after the add, did not name it. Reading a board
488//! through the lagging one alone is what had a board read deny an issue that had certainly
489//! landed on it.
490//!
491//! So [`GitHubProjectsSource::board`] is the **union** of both — each search result still
492//! admitted only on this board's own strongly-consistent `Issue.projectItems`, and neither
493//! enumeration dropped, because only `ProjectV2.items` lists a board draft and only the
494//! search reports what the projection is behind on. What closes the last
495//! gap, the one where both are behind, is [`GitHubProjectsSource::created`]: every read this
496//! source answers is completed with what this process itself wrote, so an item created
497//! seconds ago is reported whether or not GitHub has caught up. Nothing else is remembered,
498//! nothing is written down, and the record dies with the process. **A wait that has to
499//! observe GitHub's own data cannot be answered from that record** — which is why the
500//! credentialed journey asks through a source built afresh, and why the union above rather
501//! than a longer wait is what makes such a wait converge.
502//!
503//! **A narrowed read is the same bargain, stated for each of the three predicates it
504//! answers.** A read carrying a text, metadata or origin predicate asks GitHub's index rather
505//! than walking the board, and every such answer is completed with what this process wrote —
506//! its [`created`](GitHubProjectsSource::created) record and every existing item it wrote,
507//! each filtered by the same predicates as the rest — so an item this command wrote a moment
508//! ago is returned by a query that matches it whether or not the index has caught up. An item
509//! a caller holds the id of is read by that id, with `node(id:)`, which is strongly
510//! consistent. What is left is stated rather than papered over:
511//!
512//! | Read | Finds | Behind by |
513//! | --- | --- | --- |
514//! | text, metadata | the issue search for the phrases | what another process wrote in the last second or two, until GitHub indexes it |
515//! | origin, first read | the board's field filter over the origin field — every carrier, whichever release wrote it | what `ProjectV2.items` is behind on, which the measurements above put in minutes |
516//! | origin, second read | the issue search for the id in the body, where a write of this release mirrors it | a second or two, as any search |
517//! | origin, third read | this process's own writes | nothing |
518//!
519//! So an origin carrier another process added within the last second or two, before either
520//! index has it, can be missing from an origin query, and one written by the release before
521//! this one — its origin in the field alone — can be missing for as long as the board's own
522//! item connection is behind on it. A copy that must not duplicate its own earlier write
523//! relies on the link it records, not on either index. **A board draft is not an issue**, so
524//! a draft is never returned by a text, metadata or origin query, whatever it holds: no search
525//! lists one, the origin lookup drops any the board's own field filter names, and one this
526//! process wrote is not added back either.
527//!
528//! **The origin lives in the board field, and the body holds a mirror of it.** A write that
529//! carries an origin writes it to the `onetaskgraph.origin` text field and also into the
530//! body's metadata slot, so the issue search can find it in seconds. The field is
531//! authoritative: this source reads an item's origin from the field alone, so a slot that
532//! disagrees with it, or holds one where the field holds none, is never read as a second
533//! origin — and the release before this one reads the slot, drops that key's copy for the
534//! field's, and sees the same one origin.
535//!
536//! Filtering happens before paging, so a page of a filtered result is a page of the
537//! survivors rather than the survivors of a page. Label matching and the substring rule a
538//! text candidate is confirmed by answer the same question the same way the local Markdown
539//! source's do; which candidates a text search has to confirm is GitHub's word match, which
540//! is the one place the two sources can answer the same text differently.
541//!
542//! <!-- llmlint: ignore[contracts_have_one_source_or_a_drift_gate] The declaration itself
543//! has one source, `capabilities`, and the note above is the reasoning behind it rather
544//! than a second copy of it: without the three facts recorded here a reader takes the
545//! uniform `Native` for a lie and reverts it. The drift gate on the declaration is this
546//! crate's own capabilities test, which pins every field of it against a fully spelled-out
547//! `Capabilities` literal — a struct with no `Default`, so a field added to the contract
548//! fails to compile there rather than going unasserted. -->
549//! The fixture-server tests above run wherever this crate is selected; the credentialed
550//! lane runs in the same required check, beside them, and can fail it — it verifies the
551//! current schema, then drives every field of the table above against the real board. It builds its own fixture there — two projects, one task filed under each,
552//! one filed under neither, a label on one of the three and a closed status on another —
553//! because that shape is what tells an honoured predicate from an ignored one: a board
554//! holding a single project answers a project filter the same way whether or not this
555//! source applies it, which is exactly how the defect above went unseen.
556//!
557//! That lane writes only to the board `GH_PROJECTS_OWNER` and `GH_PROJECTS_NUMBER` name,
558//! and the scratch repository `GH_PROJECTS_REPOSITORY` names:
559//! `nickderobertis/onetaskgraph-live-scratch`. It refuses the core repository before any
560//! session or request, independently of the live demand. Fix that variable in the machine's
561//! onetaskgraph `secrets.env` or the environment it pushes from, such as ai-orchestrator's
562//! `.env`. The targets are declared once in `onetaskgraph_github_live`, the lane's own
563//! policy crate; absent credentials or nominations otherwise skip.
564//!
565//! GitHub Actions artifacts carry `ci-<run id>-<attempt>-<micros>`, naming their writing
566//! run and attempt; invalid Actions identity refuses before writing. Other runs retain
567//! `<host>-<process>-<micros>`. Own cleanup matches the whole stamp. Machine residue stays
568//! the owning machine's lock sweep's; Linear always keeps that form and is unaffected.
569//! The hourly janitor is cleanup, never a test lane: scratch CI residue is removed only
570//! after its run reads back as `completed`, immediately before the listed-artifact batch.
571//! Failed or incomplete ownership reads preserve residue. A 24-hour waiting period
572//! is a margin, never the ownership authorisation. Cleanup leaves machine stamps
573//! and the board's `onetaskgraph.origin` field untouched.
574//!
575//! # What a session of requests costs, and where the report is
576//!
577//! This source records **every** request it sends into [`accounting::Accounting`], at
578//! `send_once` — the one place a request leaves this crate, which is why a read path added
579//! later is counted without anybody remembering to count it. That is the whole of what this
580//! crate adds to the arrangement; [`accounting`] is where what a record carries, how a
581//! session's spend is arrived at, and what it deliberately does not know are set out.
582//!
583//! What one whole session of the live journey costs, counted that way against this crate's
584//! loopback fixture board, is written down in `session-cost.md` beside this crate — with the
585//! reduction it came out of, and with what it does and does not say about rate-limit points.
586//!
587//! [`GitHubProjectsSource::accounting`] is the read: a snapshot to hold and compare, which
588//! [`accounting::Session::report`] renders the session report from. It is on the ordinary
589//! code path — no environment variable, no feature, no build configuration — because an
590//! instrument nobody switches on measures nothing, and
591//! [`Plugin::build_recording_into`] is how a caller making its own calls beside this
592//! source's counts the whole session rather than this source's share. The credentialed lane
593//! in `tests/live.rs` does exactly that, and prints the report at the end of every run,
594//! passed or failed.
595//!
596//! **A live session refuses to start unless the account can afford it.** Before it does any
597//! of the work it exists to do, the journey makes one request — `GET /rate_limit`, which
598//! GitHub documents as not counting against the REST rate limit and which answers both of
599//! its budgets at once — and starts only if, for each of them, what remains minus this
600//! session's estimated cost is still at least
601//! `onetaskgraph_live::RETAINED_BUFFER` — twenty per cent — of that budget's whole
602//! allowance. A session that cannot **declines**: it did not run, so it is
603//! neither a pass nor a failing assertion, and it says which budget was short, that budget's
604//! limit, what remained, the estimate, the buffer and when it resets — then stops, without
605//! waiting for the budget to come back. The estimate is derived offline from
606//! `tests/fixtures/session-cost.txt` and a cost model stated in `tests/journey/budget.rs`,
607//! which is also where the published rule that model rests on is cited; the accounting
608//! above records the gate's own read like any other request, and
609//! [`accounting::Session::report`] prints the estimate beside what the session really spent.
610//!
611//! **GitHub is the authority on both of its own numbers, and the credentialed lane goes and
612//! asks it.** Everything above computes `nodeCount` and `cost` offline from a document's own
613//! text, which is what lets it run on every platform and on a pull request from a fork with
614//! no credential — and that is what actually stops a regression merging. But an offline
615//! arithmetic can only ever agree with itself: if GitHub changes its rules, this workspace
616//! goes on computing the old answer and nothing notices. So `tests/live.rs` reconciles them.
617//! GitHub's schema exposes `rateLimit(dryRun: true)`, whose `nodeCount` is *"the maximum
618//! number of nodes this query may return"* and whose `cost` is what that document would
619//! spend, both for a document **without executing it**, and the lane asks it for every query
620//! document this source sends, under the largest bindings this source sends, and fails when
621//! GitHub's figure and [`worst_case_node_count`] or [`worst_case_point_cost`] disagree. A
622//! mutation is skipped, because `rateLimit` is a field of `Query` and cannot be asked about
623//! one; the offline pins still cover it. It records what those calls reported about the
624//! account's own allowance, because whether asking is free is a thing to observe rather than
625//! to assume. Two quantities, not one: [`NODE_COUNT_LIMIT`] bounds `nodeCount` per query,
626//! and `cost` is metered against an hourly allowance the accounting above reads off a
627//! credentialed run's own response headers.
628//!
629//! **GitHub has two rate limiters and this source is refused by both, so nothing here
630//! treats them as one thing.** The primary budget is the hourly allowance `gh api
631//! rate_limit` reports; the secondary limiter is a burst limiter over content-generating
632//! requests, and *nothing* reports it. Which one refused decides the operator's next step,
633//! so [`Limiter`] is a type rather than a detail, and it is what [`MIN_MUTATION_INTERVAL_MS`],
634//! [`GitHubProjectsSource::board_cache`] and [`GitHubProjectsSource::graphql`] each answer
635//! one part of.
636#![deny(missing_docs)]
637
638use std::collections::BTreeMap;
639use std::sync::{Arc, Mutex};
640use std::time::Duration;
641
642use chrono::{DateTime, Utc};
643use onetaskgraph_plugin_api::ProjectedValue;
644use onetaskgraph_plugin_api::{
645    Capabilities, Classification, ClosedAs, Comment, CommentBody, CommentOrigin, Completion,
646    ContradictedItem, Coverage, Cursor, DependencyEdge, DependencyEndpoint, DependencyKind,
647    DependencySupport, Designator, Direction, Document, DocumentQuery, DocumentVersionCoverage,
648    Health, HeldTask, IssueHolding, IssueRef, ItemKind, ItemWrite, Label, LabelFilter, Location,
649    MetadataKey, Metering, NativeId, NewComment, Page, PageRequest, Priority, Project,
650    ProjectFilter, ProjectQuery, ProjectVersionCoverage, Repository, SecretResolver, SharedClock,
651    SourceError, SourceName, SourcePlugin, Status, StatusCategory, StatusContradiction,
652    StatusMapping, Support, Task, TaskDetailRead, TaskQuery, TaskRef, TaskSource, TaskUpdate,
653    TaskUpdateOutcome, TextFields, TextQuery, UnmappedStatus, UpdatedField, VersionCoverage,
654    WaitCause, WriteJournal, WriteSupport, system_clock,
655};
656use reqwest::{Client, StatusCode, Url};
657use schemars::{Schema, schema_for};
658use secrecy::{ExposeSecret, SecretString};
659use serde::{Deserialize, Serialize};
660use serde_json::{Value, json};
661
662pub mod accounting;
663mod assets;
664mod assignees;
665mod batch;
666pub mod change_token;
667mod expected;
668pub use expected::{CONTEXT_VERSION, WHOLE_MEMBERS, context_shapes};
669mod pacing;
670mod projection;
671mod quota;
672mod relations;
673mod visibility;
674
675use accounting::Accounting;
676
677/// The registry name for this plugin.
678pub const KIND: &str = "github-projects";
679/// GitHub's maximum connection page size.
680pub const MAX_PAGE_SIZE: u32 = 100;
681/// Every page of a board-scoped narrowing search: 20 rows, one point of SEARCH_ISSUES, the
682/// most one point buys. GitHub prices that document by rows, so pages of 20 cost what pages
683/// of 100 cost per row, and a page of fewer than 20 costs the same one point.
684pub const SEARCH_PAGE_SIZE: u32 = 20;
685/// How many items one [`graphql::ISSUE_DETAILS`] request reads, each with the first page of
686/// its comments: the largest batch the node-count model prices at one point.
687///
688/// Each aliased item is resolved once, and what GitHub charges for it is the connections
689/// under it — its labels, its page of board memberships, the field values of each of those
690/// three memberships, and its comments: six requests' worth of the aggregate GitHub divides
691/// by a hundred and rounds. Twenty-four items come to 144, which rounds to one point;
692/// twenty-five come to 150, which rounds to two. `tests/point_cost.rs` prices the document at
693/// one point and fails if one item more would still be priced at one.
694pub const DETAIL_BATCH: usize = 24;
695/// How many issue references one [`graphql::ISSUES_BY_REFERENCE`] request reads.
696///
697/// Each reference asks GitHub for one connection — a page of its board memberships, each with
698/// its `Status` value read by name rather than through a connection of field values — so fifty
699/// come to fifty requests' worth of the aggregate GitHub divides by a hundred, which is its
700/// one-point minimum, and the batch a landing's closures are read in costs one point per fifty
701/// issues per source. `tests/point_cost.rs` prices the document at one point.
702pub const REFERENCE_BATCH: usize = 50;
703/// How many items one [`graphql::ISSUE_COPY_DETAILS`] request reads: each with the first page
704/// of its comments and its `blockedBy`, the largest batch the node-count model prices at one
705/// point.
706///
707/// The six requests' worth an item of [`DETAIL_BATCH`] costs, and its `blockedBy` connection
708/// besides: seven. Twenty-one items come to 147, which rounds to one point; twenty-two come to
709/// 154, which rounds to two. `tests/point_cost.rs` prices the document at one point and fails
710/// if one item more would still be priced at one.
711pub const COPY_DETAIL_BATCH: usize = 21;
712/// How many mutations one aliased request of a copy's creates, closes and updates carries:
713/// [`graphql::CREATE_ISSUES`], [`graphql::CLOSE_ISSUES`] and [`graphql::UPDATE_ISSUES`].
714///
715/// Eleven is what GitHub was seen to accept in one request — the timing spike
716/// (`board-copy-speed-2026-10-18-spike-copy-timing-report`) sent eleven aliased mutations of four
717/// kinds, three `createIssue`, three `addProjectV2ItemById`, three field updates, an
718/// `addSubIssue` and an `addBlockedBy`, and every one ran — and no more was established.
719pub const MUTATION_BATCH: usize = 11;
720
721/// The most people one lookup ([`graphql::user_ids`]) asks for: GitHub's documented limit of
722/// [`NODE_COUNT_LIMIT`] nodes a request, each `user(login:)` field being one. Every person a
723/// call names that this process has not resolved is looked up in one request below it — so a
724/// call is split only past it.
725#[expect(
726    clippy::cast_possible_truncation,
727    reason = "500,000 fits every target's usize"
728)]
729pub const PEOPLE_PER_LOOKUP: usize = NODE_COUNT_LIMIT as usize;
730
731/// The most relation writes — `addSubIssue`, `removeSubIssue`, `addRelatesTo`,
732/// `removeRelatesTo` — one request carries: a 60-alias `addRelatesTo` answered HTTP 504 after
733/// landing 58 of its 60 (`spike-relations`), and 30 were accepted every time.
734pub const RELATION_BATCH: usize = 30;
735/// How many aliased writes one request of a copy's board field values and blocked-by edges
736/// carries: [`graphql::WRITE_FIELD_VALUES`], [`graphql::ADD_BLOCKED_BYS`] and, for a request
737/// holding both kinds, [`graphql::WRITE_FIELDS_AND_EDGES`].
738///
739/// Nineteen is the most aliases the feasibility spike
740/// (`board-copy-gaps-2026-10-24-spike-feasibility-report`) sent in one mutation request and
741/// saw GitHub price at the one point every mutation request costs; no larger request was
742/// established, so a copy holding more is split.
743pub const WRITE_BATCH: usize = 19;
744/// How many issues one [`graphql::DELETE_ISSUES`] request deletes: one request of eleven
745/// aliased `deleteIssue` met `RESOURCE_LIMITS_EXCEEDED` from the eighth alias on, and batches
746/// of five succeeded (the feasibility spike's undo-batching run).
747pub const DELETE_BATCH: usize = 5;
748/// How many origins one [`graphql::ORIGIN_LOOKUPS`] request asks about: the nine records of a
749/// plan and the project's document, and no more, since each carries a page of the board's field
750/// filter and one of the issue search.
751pub const ORIGIN_BATCH: usize = 10;
752/// How many searches one [`graphql::SEARCH_BATCH`] request asks: what `task find` asks of a
753/// board in one call, each search an aliased `search` field of its own.
754pub const SEARCH_BATCH: usize = 20;
755/// How many origins one [`graphql::SEARCH_BATCH`] request looks up beside its searches, each by
756/// the board's own field filter in an aliased `items` field of its own and by one of the
757/// request's searches.
758pub const SEARCH_BATCH_ORIGINS: usize = 5;
759/// The rows each search of a [`graphql::SEARCH_BATCH`] request asks for on its first page.
760///
761/// A batched find asks narrowed questions that each expect a handful of answers, and every
762/// search slot is priced at its page size: three rows a slot keep a first round of
763/// [`SEARCH_BATCH`] searches at three points, where a page of [`SEARCH_PAGE_SIZE`] each would
764/// cost twenty. A search with more to answer is walked on at [`SEARCH_PAGE_SIZE`] rows a page.
765pub const SEARCH_BATCH_FIRST_PAGE: u32 = 3;
766
767/// The rows each resumed page of one [`graphql::SEARCH_BATCH`] round asks for, when `resumed`
768/// of its slots — searches and origin item listings alike — resume from a cursor.
769///
770/// Every resumed page of a round shares one [`SEARCH_PAGE_SIZE`] of rows, rather than each
771/// asking that many: a round in which all twenty searches walked on at twenty rows a slot cost
772/// 22 points in one request, while sharing holds every round to what its first pages cost and
773/// one page more. A search with more to answer is walked on over more rounds, each page still
774/// read, so what a walk answers is unchanged; a round of one resumed search asks the page a
775/// search alone asks.
776#[must_use]
777pub fn search_batch_resumed_page(resumed: usize) -> u32 {
778    let resumed = u32::try_from(resumed.max(1)).unwrap_or(u32::MAX);
779    (SEARCH_PAGE_SIZE / resumed).max(1)
780}
781
782/// The page sizes of the most expensive [`graphql::SEARCH_BATCH`] round this source sends:
783/// every slot on its first page, at [`SEARCH_BATCH_FIRST_PAGE`] rows, but one resumed slot
784/// asking all of [`search_batch_resumed_page`]'s shared rows.
785///
786/// `tests/point_cost.rs` holds every round shape [`search_batch_resumed_page`] allows to cost
787/// no more than this, and the credentialed lane reconciles GitHub's own price of the document
788/// under it. [`largest_page_sizes`] still binds every slot at [`SEARCH_PAGE_SIZE`], an upper
789/// bound on this, so the offline worst case covers more than any round sends.
790#[must_use]
791pub fn search_batch_largest_round() -> Variables {
792    let mut sizes = largest_page_sizes();
793    for slot in 0..SEARCH_BATCH {
794        sizes.insert(format!("first{slot}"), SEARCH_BATCH_FIRST_PAGE);
795    }
796    for slot in 0..SEARCH_BATCH_ORIGINS {
797        sizes.insert(format!("itemsFirst{slot}"), SEARCH_BATCH_FIRST_PAGE);
798    }
799    sizes.insert("first0".to_owned(), search_batch_resumed_page(1));
800    sizes
801}
802/// How many comments one [`graphql::ADD_COMMENTS`] request adds, and how many issue updates one
803/// [`graphql::WRITE_TASKS`] request carries: [`MUTATION_BATCH`], the most aliased mutations
804/// GitHub was seen to accept in one request.
805pub const COMMENT_BATCH: usize = MUTATION_BATCH;
806/// How many board field values one [`graphql::WRITE_TASKS`] request carries, beside
807/// [`MUTATION_BATCH`] field clears: [`WRITE_BATCH`].
808pub const TASK_FIELD_BATCH: usize = WRITE_BATCH;
809
810/// The most nodes any one document this source sends may be asked to return.
811///
812/// GitHub's own published per-query ceiling, taken from
813/// [`github_graphql_node_count::NODE_LIMIT`] rather than written out again here, so this
814/// workspace cannot hold a stale copy of somebody else's number. A query above it is
815/// **refused before it is executed**, whoever is asking and whatever board they are
816/// asking about — so this is a bound on the documents rather than a budget that runs out.
817///
818/// This is `nodeCount`, the maximum number of nodes *one query may return*. It is not
819/// `cost`, the rate-limit points a call spends against an hourly allowance shared by
820/// everything the credential does — two numbers against two limits, and this constant
821/// bounds only the first. The second is computed offline too, per document:
822/// [`worst_case_point_cost`], pinned for every document in [`graphql::DOCUMENTS`] by
823/// `tests/point_cost.rs`, and reconciled against GitHub's own `cost` by the credentialed
824/// lane. There is no constant like this one to hold a price under, because points are an
825/// hourly allowance rather than a per-call bound.
826///
827/// Neither is a session's price. What `session-cost.md` records of a whole session is its
828/// **requests** and its **worst-case nodes**; what a whole session spends in points is
829/// reported only by a credentialed run's own `x-ratelimit-*` headers, through
830/// [`accounting`]. The module section on the three ways this source reaches an item says how
831/// the count is arrived at, and which of the page sizes below decide it.
832pub const NODE_COUNT_LIMIT: u64 = github_graphql_node_count::NODE_LIMIT;
833
834/// Nested connection size for the connections that hang off one item.
835///
836/// It multiplies through every document that reaches an item under a page — the count
837/// rules multiply down a nested path — so it is the constant [`NODE_COUNT_LIMIT`] is most
838/// sensitive to. `tests/node_count.rs` is what holds the pair together: it recomputes
839/// every document under these constants and fails naming any that reaches the limit, so
840/// raising this is caught there rather than by GitHub.
841const NESTED_PAGE_SIZE: u32 = 50;
842/// How many of one issue's board memberships are read when an issue is reached directly.
843///
844/// An issue reached through a search or through its own node id carries its board half in
845/// `Issue.projectItems`, and only the entry for *this* board is read. This connection sits
846/// under a page of issues, so every point of it multiplies through the whole document and
847/// is paid for whether or not any issue is on a second board — which is why it is
848/// deliberately far smaller than [`NESTED_PAGE_SIZE`].
849///
850/// **Three, because what a page misses is now recovered rather than refused**, and the
851/// recovery is what the value is chosen against. An issue whose entry for this board sits
852/// past this page costs one further request — [`graphql::ISSUE_BOARD_ITEMS`], resumed from
853/// that page's own cursor — so the value trades a bound every read pays for a request only
854/// a multi-board issue pays. At one, a deployment whose issues commonly sit on two or more
855/// boards would pay that request *per issue*, which is order N against the one page per
856/// hundred issues a read costs today. At three it is only reached by an issue on four or
857/// more boards at once, which keeps the recovery path exceptional rather than routine for
858/// a plausible deployment.
859const BOARD_ITEMS_PAGE_SIZE: u32 = 3;
860/// How many carriers of one copy origin one page of [`graphql::ORIGIN_LOOKUP`] asks each of
861/// its two connections for.
862///
863/// An origin names one item, so the answer an origin lookup expects is one carrier, and a
864/// second is a duplicate a copy already takes the first of. Both connections are walked to
865/// exhaustion whatever this is, so it decides how many requests an unusual answer costs and
866/// never what the answer is. It is small because every point of it is paid on every lookup,
867/// and a copy makes one lookup per item it has no link for: at three, ten lookups cost fewer
868/// worst-case nodes than the one whole-board read they replaced.
869const ORIGIN_PAGE_SIZE: u32 = 3;
870/// How many carriers of each origin the batched [`graphql::ORIGIN_LOOKUPS`] asks each of its two
871/// connections for: one, the one carrier an origin names.
872///
873/// A second carrier still shows: the page then says there is more, and that origin is left to
874/// its own [`graphql::ORIGIN_LOOKUP`], which walks every page at `ORIGIN_PAGE_SIZE` — so a
875/// duplicate is found exactly as before, by the lookup that reads all of them. The feasibility
876/// spike (`board-copy-gaps-2026-10-24-spike-feasibility-report`) priced the batch of ten
877/// origins at two points with a first page of three and at one with a first page of one.
878const ORIGIN_LOOKUPS_PAGE_SIZE: u32 = 1;
879
880/// How many of one project's sub-issues one [`graphql::SUB_ISSUES`] page asks for: the most
881/// one point buys, since every row carries six connections GitHub charges for once per row.
882/// `session-cost.md` derives it; `tests/point_cost.rs` prices the document at one point and
883/// fails if one row more would still be priced at one.
884pub const MEMBER_PAGE_SIZE: u32 = 23;
885
886pub use github_graphql_node_count::{NodeCountError, Variables};
887
888/// The largest value this source can bind to each page-size variable its documents name.
889///
890/// Every `first:` in [`graphql`] reads one of these seven, and each is capped at the
891/// constant above it wherever a caller's own limit could reach it — `$first` at
892/// [`MAX_PAGE_SIZE`], `$commentFirst` at [`MAX_PAGE_SIZE`], `$nestedFirst` at `NESTED_PAGE_SIZE`, `$boardItems` at
893/// `BOARD_ITEMS_PAGE_SIZE`, `$originFirst` at `ORIGIN_PAGE_SIZE`, `$lookupFirst` at
894/// `ORIGIN_LOOKUPS_PAGE_SIZE`, `$memberFirst` at [`MEMBER_PAGE_SIZE`]. So this is the worst case a caller can drive this source to,
895/// not one configuration of it, which is what makes a bound computed under it a bound on
896/// every read.
897pub fn largest_page_sizes() -> Variables {
898    let mut sizes = Variables::from([
899        ("first".to_owned(), MAX_PAGE_SIZE),
900        ("commentFirst".to_owned(), MAX_PAGE_SIZE),
901        ("nestedFirst".to_owned(), NESTED_PAGE_SIZE),
902        ("boardItems".to_owned(), BOARD_ITEMS_PAGE_SIZE),
903        ("originFirst".to_owned(), ORIGIN_PAGE_SIZE),
904        ("lookupFirst".to_owned(), ORIGIN_LOOKUPS_PAGE_SIZE),
905        ("memberFirst".to_owned(), MEMBER_PAGE_SIZE),
906    ]);
907    // Each slot of the batched search pages at most what one search does.
908    for slot in 0..SEARCH_BATCH {
909        sizes.insert(format!("first{slot}"), SEARCH_PAGE_SIZE);
910    }
911    for slot in 0..SEARCH_BATCH_ORIGINS {
912        sizes.insert(format!("itemsFirst{slot}"), SEARCH_PAGE_SIZE);
913    }
914    sizes
915}
916
917/// The most nodes `document` could be asked to return, by GitHub's published rules.
918///
919/// Computed offline from the document's own text under [`largest_page_sizes`] — no
920/// network, no credential and no schema — by
921/// [`github_graphql_node_count::node_count`], which is where the rules themselves live.
922/// A document at or above [`NODE_COUNT_LIMIT`] is one GitHub refuses before executing, so
923/// this is what a check holds every document in [`graphql::DOCUMENTS`] below.
924///
925/// # Errors
926///
927/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
928/// no single operation, or binds a page size this source does not name — each of which is
929/// a defect in the document rather than a number.
930pub fn worst_case_node_count(document: &str) -> Result<u64, NodeCountError> {
931    node_count(document, &largest_page_sizes())
932}
933
934/// The most rate-limit points one call of `document` could spend, by GitHub's published
935/// rules.
936///
937/// Computed offline from the document's own text under [`largest_page_sizes`] — no
938/// network, no credential and no schema — by
939/// [`github_graphql_node_count::point_cost`], which is where the rules themselves live.
940/// This is `cost`, metered **per hour** against the allowance one credential shares across
941/// everything it does; it is not `nodeCount`, which is [`worst_case_node_count`] and is
942/// bounded per query by [`NODE_COUNT_LIMIT`]. There is no per-call ceiling to hold this
943/// under, so what `tests/point_cost.rs` does with it is pin every document in
944/// [`graphql::DOCUMENTS`] at what it costs, and the credentialed lane reconciles those
945/// figures against GitHub's own reported `cost`.
946///
947/// # Errors
948///
949/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
950/// no single operation, or binds a page size this source does not name — each of which is
951/// a defect in the document rather than a number.
952pub fn worst_case_point_cost(document: &str) -> Result<u64, NodeCountError> {
953    github_graphql_node_count::point_cost(document, &largest_page_sizes())
954}
955
956/// The rate-limit points one call of `document` spends under `variables`, by GitHub's published
957/// rules: [`worst_case_point_cost`] is this under [`largest_page_sizes`], and a request this
958/// source sent is priced by it under the page sizes that request really bound — what GitHub
959/// charges the request, since it charges every connection at the page size asked for.
960///
961/// # Errors
962///
963/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
964/// no single operation, or binds a page size `variables` does not name.
965pub fn point_cost(document: &str, variables: &Variables) -> Result<u64, NodeCountError> {
966    github_graphql_node_count::point_cost(document, variables)
967}
968
969/// The most nodes `document` could be asked to return under `variables`.
970///
971/// [`worst_case_node_count`] is this under [`largest_page_sizes`], and the accounting in
972/// [`accounting`] is this under the bindings one request really sent — one spelling of the
973/// calculation, so a bound checked offline and a cost recorded at run time cannot come to
974/// disagree. The rules themselves live in [`github_graphql_node_count::node_count`].
975///
976/// # Errors
977///
978/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
979/// no single operation, or binds a page size `variables` does not name.
980pub fn node_count(document: &str, variables: &Variables) -> Result<u64, NodeCountError> {
981    github_graphql_node_count::node_count(document, variables)
982}
983
984/// `variables` with the page sizes and flags a token twin's inline issue selection binds,
985/// at a read's page sizes.
986fn token_variables(mut variables: Value) -> Value {
987    if let Some(object) = variables.as_object_mut() {
988        object.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
989        object.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
990        object.insert("duplicates".to_owned(), json!(true));
991    }
992    variables
993}
994
995/// What a caller's request gate is told of one GraphQL request: it draws on GitHub's `graphql`
996/// resource, it creates content exactly when it creates an issue or a comment,
997/// and it costs what GitHub's published rules price it at under the page sizes it binds.
998fn gated_graphql(document: &str, variables: &Value) -> onetaskgraph_plugin_api::GatedRequest {
999    onetaskgraph_plugin_api::GatedRequest {
1000        resource: "graphql".to_owned(),
1001        content_creating: creates_content(document),
1002        cost_hint: point_cost(document, &accounting::bindings(variables)).ok(),
1003    }
1004}
1005
1006/// Whether `document` creates content GitHub's secondary limits meter as such: an issue or a
1007/// comment. `creates_content_tests` classifies every mutation root `graphql::DOCUMENTS` sends,
1008/// so a root added later fails there until it is said whether it creates content.
1009fn creates_content(document: &str) -> bool {
1010    is_mutation(document)
1011        && ["createIssue(", "addComment("]
1012            .iter()
1013            .any(|root| document.contains(root))
1014}
1015
1016#[cfg(test)]
1017mod creates_content_tests {
1018    use super::{creates_content, graphql};
1019    use std::collections::BTreeMap;
1020
1021    /// Every root field a mutation document selects at its top level, aliases resolved.
1022    fn roots(document: &str) -> Vec<String> {
1023        let body = &document[document.find('{').expect("a selection set") + 1..];
1024        let (mut braces, mut parens, mut roots) = (0_usize, 0_usize, Vec::new());
1025        let mut chars = body.char_indices().peekable();
1026        while let Some((at, c)) = chars.next() {
1027            match c {
1028                '{' => braces += 1,
1029                '}' if braces == 0 => break,
1030                '}' => braces -= 1,
1031                '(' => parens += 1,
1032                ')' => parens -= 1,
1033                // A directive's name is no field.
1034                '@' => {
1035                    while chars
1036                        .peek()
1037                        .is_some_and(|&(_, n)| n.is_ascii_alphanumeric() || n == '_')
1038                    {
1039                        chars.next();
1040                    }
1041                }
1042                c if braces == 0 && parens == 0 && (c.is_ascii_alphabetic() || c == '_') => {
1043                    let mut end = at + c.len_utf8();
1044                    while let Some(&(next, n)) = chars.peek() {
1045                        if !(n.is_ascii_alphanumeric() || n == '_') {
1046                            break;
1047                        }
1048                        end = next + n.len_utf8();
1049                        chars.next();
1050                    }
1051                    let rest = body[end..].trim_start();
1052                    // An alias names the root after its colon, which this loop reads next.
1053                    if !rest.starts_with(':') {
1054                        roots.push(body[at..end].to_owned());
1055                    }
1056                }
1057                _ => {}
1058            }
1059        }
1060        roots
1061    }
1062
1063    #[test]
1064    fn every_mutation_root_sent_is_classified_and_creates_content_agrees() {
1065        // Whether each root creates an issue or a comment: what GitHub's
1066        // secondary limits meter as content creation.
1067        let classified = BTreeMap::from([
1068            ("addBlockedBy", false),
1069            ("addComment", true),
1070            ("addProjectV2ItemById", false),
1071            ("addRelatesTo", false),
1072            ("addSubIssue", false),
1073            ("clearProjectV2ItemFieldValue", false),
1074            ("closeIssue", false),
1075            ("createIssue", true),
1076            ("createProjectV2Field", false),
1077            ("deleteIssue", false),
1078            ("deleteIssueComment", false),
1079            ("removeBlockedBy", false),
1080            ("removeRelatesTo", false),
1081            ("removeSubIssue", false),
1082            ("updateIssue", false),
1083            ("updateIssueComment", false),
1084            ("updateProjectV2DraftIssue", false),
1085            ("updateProjectV2Field", false),
1086            ("updateProjectV2ItemFieldValue", false),
1087        ]);
1088        let (mut seen, mut unclassified) = (BTreeMap::new(), std::collections::BTreeSet::new());
1089        for (document, _) in graphql::DOCUMENTS {
1090            if !super::is_mutation(document) {
1091                assert!(!creates_content(document), "a query: {document}");
1092                continue;
1093            }
1094            let roots = roots(document);
1095            assert!(!roots.is_empty(), "no root read: {document}");
1096            for root in &roots {
1097                match classified.get(root.as_str()) {
1098                    Some(&creates) => _ = seen.insert(root.clone(), creates),
1099                    None => _ = unclassified.insert(root.clone()),
1100                }
1101            }
1102            let expected = roots
1103                .iter()
1104                .any(|root| classified.get(root.as_str()) == Some(&true));
1105            assert_eq!(creates_content(document), expected, "{document}");
1106        }
1107        assert!(
1108            unclassified.is_empty(),
1109            "say whether each of these mutation roots creates content: {unclassified:?}"
1110        );
1111        let unsent: Vec<_> = classified
1112            .keys()
1113            .filter(|root| !seen.contains_key(**root))
1114            .collect();
1115        assert!(unsent.is_empty(), "classified but never sent: {unsent:?}");
1116    }
1117}
1118
1119/// The input members a mutation names the issue or board item it writes by.
1120const WRITTEN_NAMES: [&str; 4] = ["id", "issueId", "subjectId", "itemId"];
1121
1122tokio::task_local! {
1123    /// The source a targeted update is running on, by its address, while it runs: what has its
1124    /// mutations sent as the twins selecting the whole issue, so the update answers the version
1125    /// its own last response shows (see `GitHubProjectsSource::written_tokens`).
1126    static SPELLING: usize;
1127}
1128
1129/// The issue-title prefix that makes a board issue a document.
1130///
1131/// A GitHub Projects board has no document type — it holds issues — so the discriminator
1132/// is the title, and this is the whole of it: an issue whose title begins with these bytes
1133/// is a document and every other issue is the task or project the sub-issue rule makes it.
1134///
1135/// It is spelled **once**, here, and read rather than restated everywhere else — including
1136/// by the shared journeys, which take it from this constant so a board fixture cannot
1137/// drift from what this source reads. `docs/metadata.md` records the two consequences that
1138/// are not obvious from the bytes: the reported title has this prefix taken off, exactly
1139/// as the body's metadata slot is taken off `content`, and this prefix is read *before*
1140/// the sub-issue rule, so a design issue with no sub-issues is never an empty project.
1141pub const DESIGN_TITLE_PREFIX: &str = "DESIGN: ";
1142
1143/// The most characters GitHub stores in one issue's body: a longer one is refused as
1144/// `body is too long (maximum is 65536 characters)`.
1145pub const BODY_LIMIT: u64 = 65_536;
1146
1147/// The address a new upload's URL is spelled at, as GitHub serves a user attachment: what the
1148/// size of a body is measured with before an asset of it is uploaded, a UUID long.
1149const PREDICTED_ATTACHMENT_URL: &str =
1150    "https://github.com/user-attachments/assets/00000000-0000-0000-0000-000000000000";
1151
1152/// Exact GraphQL query documents issued by this plugin.
1153///
1154/// Keeping the production documents here lets the pinned-schema test validate the same
1155/// bytes that are sent to GitHub, rather than a test-only copy which could drift
1156/// independently. [`STATUS_OPTIONS_UPDATE`] is the sole document that may rewrite a board
1157/// field, and its guarded caller always supplies the complete existing option set with ids.
1158pub mod graphql {
1159    /// The board half of one item: the field values every document here reads it from.
1160    ///
1161    /// A macro for the same reason [`board_issue!`] below is one, a level further in. This
1162    /// selection is needed by that fragment, by [`BOARD`] under the board's own `items`,
1163    /// and by [`ISSUE_BOARD_ITEMS`] under a membership walk — and all three have to produce
1164    /// *the same value*, because
1165    /// [`GitHubProjectsSource::resolve`](super::GitHubProjectsSource) reads them through
1166    /// one path. Three spellings of it is what would drift, so there is one.
1167    ///
1168    /// The `Status` option and this source's own origin text field are the whole of it. It
1169    /// selects no `ProjectV2ItemFieldLabelValue`: GitHub derives that field from the item's
1170    /// content, so it holds nothing the content's own `labels` do not already say, and it
1171    /// would sit a label connection two page sizes deep.
1172    macro_rules! board_item_values {
1173        () => {
1174            r#"fieldValues(first:$nestedFirst){nodes{
1175          ... on ProjectV2ItemFieldSingleSelectValue{name field{
1176            ... on ProjectV2SingleSelectField{id name options{id name}}
1177          }}
1178          ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{id name}}}
1179        }pageInfo{hasNextPage}}"#
1180        };
1181    }
1182
1183    /// The variable every document reading an issue declares for the relationship events its
1184    /// change token counts, with its value as the default, so no caller binds it.
1185    ///
1186    /// A variable rather than a literal list because every argument a production document
1187    /// passes is a declared variable, which `tests/schema.rs` holds them to, and every member of
1188    /// its default to the pinned enum. Its default is the six event types GitHub records a
1189    /// relationship added or removed with: a dependency on either end, as `blockedBy` and
1190    /// `blocking`, so one a person makes from the far end moves this end's count too; and a
1191    /// project membership on the task, as its parent, which GitHub records there whichever
1192    /// issue the move was made from. A sub-issue's events on its parent are not counted: a
1193    /// project carries no task token, and a copy writes nothing of a task its own sub-issues
1194    /// decide. [`super::change_token`] says why the count is in the token.
1195    macro_rules! relationship_events_variable {
1196        () => {
1197            ",$relationshipEvents:[IssueTimelineItemsItemType!]=[BLOCKED_BY_ADDED_EVENT,BLOCKED_BY_REMOVED_EVENT,BLOCKING_ADDED_EVENT,BLOCKING_REMOVED_EVENT,PARENT_ISSUE_ADDED_EVENT,PARENT_ISSUE_REMOVED_EVENT]"
1198        };
1199    }
1200
1201    /// Everything this source reads about one issue, wherever it reaches that issue.
1202    ///
1203    /// A macro rather than a constant so the three documents below can `concat!` it: one
1204    /// spelling of these fields is what makes an issue read through the board-scoped
1205    /// search, through its own node id, and through its project's sub-issue relationship
1206    /// resolve to *the same* item, which is the whole of what
1207    /// [`GitHubProjectsSource::resolve_issue`](super::GitHubProjectsSource) relies on.
1208    ///
1209    /// `projectItems` is what carries the board half of an issue: the board item's own id
1210    /// and the [`board_item_values!`] above — the `Status` option and this source's origin
1211    /// text field — that a `ProjectV2.items` read used to carry. It is asked for on the
1212    /// issue rather than on the board, which is what makes the cost of a read proportional
1213    /// to what was asked for instead of to the board's size.
1214    ///
1215    /// It carries a *page* of that connection, at `BOARD_ITEMS_PAGE_SIZE`, and its
1216    /// `endCursor` is what [`ISSUE_BOARD_ITEMS`] resumes from when this board's entry is
1217    /// not on that page: a page here is where the search for the entry starts rather than
1218    /// where it ends.
1219    ///
1220    /// It does **not** select the board's `Labels` field value, and that is the whole of
1221    /// what keeps the three documents below under [`NODE_COUNT_LIMIT`](super::NODE_COUNT_LIMIT):
1222    /// a label connection there sits under `fieldValues` under `projectItems` under a page
1223    /// of issues, spending `$nestedFirst` twice down one path, and took
1224    /// [`SEARCH_ISSUES`] and [`SUB_ISSUES`] to 2,556,100 nodes against a limit of 500,000.
1225    /// No label is lost — this is a fragment `on Issue`, whose own `labels` are selected
1226    /// above, and that connection is where every label this source reports comes from. No
1227    /// document in this module selects the board field any longer, [`BOARD`] included; the
1228    /// module documentation records why nothing it could have held is lost.
1229    macro_rules! board_issue {
1230        () => {
1231            concat!(
1232                r#" fragment BoardIssue on Issue{"#,
1233                board_issue_fields!(),
1234                "}"
1235            )
1236        };
1237    }
1238
1239    /// What [`board_issue!`] selects of an issue, written out where a document selects it
1240    /// inline rather than through the fragment.
1241    macro_rules! board_issue_fields {
1242        () => {
1243            concat!(
1244                r#"__typename id number title body url createdAt updatedAt state stateReason(enableDuplicate:$duplicates) repository{nameWithOwner} parent{id} subIssuesSummary{total} commentCount:comments{totalCount} relationshipEvents:timelineItems(itemTypes:$relationshipEvents){totalCount}
1245      labels(first:$nestedFirst){nodes{id name color}pageInfo{hasNextPage}}
1246      projectItems(first:$boardItems){nodes{id updatedAt project{id number}
1247        "#,
1248                board_item_values!(),
1249                r#"}pageInfo{hasNextPage endCursor}}"#
1250            )
1251        };
1252    }
1253
1254    /// One page of a repository's issues, newest first, each with when it was created and its
1255    /// body: what a retried copy reads to find the issue its earlier attempt created, by the
1256    /// create key in that body's metadata slot — never through search, whose index lags.
1257    pub const ISSUES_BY_CREATION: &str = "query($owner:String!,$name:String!,$first:Int!,$after:String){repository(owner:$owner,name:$name){issues(first:$first,after:$after,orderBy:{field:CREATED_AT,direction:DESC}){nodes{id createdAt body}pageInfo{hasNextPage endCursor}}}}";
1258    /// Every issue of one board, found by a search scoped to that board.
1259    ///
1260    /// This is how the projects a board holds are listed, and it selects no `items`
1261    /// connection on `ProjectV2`: the board is a *qualifier of the search* rather than a
1262    /// container walked page by page, so nothing nested inside a board item is paid for.
1263    /// Which of the issues it returns is a project is then read off `parent` — GitHub
1264    /// accepts `-has:parent` as a search qualifier and silently ignores it, so the
1265    /// discriminator has to be applied to the field, which is a scalar on the issue and
1266    /// costs nothing.
1267    pub const SEARCH_ISSUES: &str = concat!(
1268        r#"query($search:String!,$type:SearchType!,$first:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1269        relationship_events_variable!(),
1270        r#"){
1271      search(query:$search,type:$type,first:$first,after:$after){
1272        pageInfo{hasNextPage endCursor}
1273        nodes{__typename ...BoardIssue}
1274      }
1275    }"#,
1276        board_issue!()
1277    );
1278
1279    /// What a dependency read selects of each far end: enough to say which kind of item it
1280    /// is, its body included for the kind marker.
1281    macro_rules! related_issue {
1282        () => {
1283            " fragment Related on Issue{id title body parent{id} subIssuesSummary{total}}"
1284        };
1285    }
1286
1287    /// One issue by its own node id, which is what a qualified id names here — with what a
1288    /// write of it needs and the issue does not carry in `board_issue!`: the field
1289    /// definitions of the boards it sits on, and the far ends of its `blockedBy`.
1290    ///
1291    /// Strongly consistent, unlike the search above: GitHub's issue search is an index and
1292    /// answers a write made moments ago with the value from before it, and resolving a node
1293    /// id does not.
1294    ///
1295    /// **Why those two ride here and not on the fragment.** A copy or an update of an item
1296    /// reads it by its own id, and with them that one read answers everything the write
1297    /// needs: which option ids the board's `Status` and `Priority` fields hold — so no
1298    /// [`BOARD_FIELDS`] — and which issues block it, with each one's kind — so no
1299    /// [`ISSUE_DEPENDENCIES`]. On `board_issue!` they would sit under the hundred-issue
1300    /// pages of [`SEARCH_ISSUES`] and [`SUB_ISSUES`], multiplying both documents' price. Here
1301    /// they sit under one item, and this read is still one point.
1302    pub const ISSUE: &str = concat!(
1303        r#"query($id:ID!,$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1304        relationship_events_variable!(),
1305        r#"){
1306      node(id:$id){__typename ...BoardIssue ... on Issue{
1307        boards:projectItems(first:$boardItems){nodes{project{id number fields(first:$nestedFirst){nodes{
1308          ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1309          ... on ProjectV2Field{__typename id name dataType}
1310        }pageInfo{hasNextPage}}}}}
1311        blockedBy(first:$first){nodes{...Related}pageInfo{hasNextPage endCursor}}
1312      }}
1313    }"#,
1314        board_issue!(),
1315        related_issue!()
1316    );
1317
1318    /// One document by its own node id, as [`ISSUE`] reads one, with the project it is filed
1319    /// under and that project's members beside it: the project issue whole, and a page of its
1320    /// sub-issues, each as [`SUB_ISSUES`] carries one but with no page of what blocks it.
1321    ///
1322    /// What a guarded write of a document's metadata reads, and what reading a document by its
1323    /// id is: a write to a board the boundary screens is held to who may read the document,
1324    /// which is the project's and every member's classification as much as its own, and here
1325    /// the one request that holds the version the write is compared against answers all of it.
1326    /// Its members carry no edges, which nothing classifying them reads.
1327    pub const DOCUMENT_IN_PROJECT: &str = concat!(
1328        r#"query($id:ID!,$first:Int!,$memberFirst:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1329        relationship_events_variable!(),
1330        r#"){
1331      node(id:$id){__typename ...BoardIssue ... on Issue{
1332        boards:projectItems(first:$boardItems){nodes{project{id number fields(first:$nestedFirst){nodes{
1333          ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1334          ... on ProjectV2Field{__typename id name dataType}
1335        }pageInfo{hasNextPage}}}}}
1336        blockedBy(first:$first){nodes{...Related}pageInfo{hasNextPage endCursor}}
1337        project:parent{__typename ...BoardIssue
1338          subIssues(first:$memberFirst){pageInfo{hasNextPage endCursor} nodes{__typename ...BoardIssue}}
1339        }
1340      }}
1341    }"#,
1342        board_issue!(),
1343        related_issue!()
1344    );
1345
1346    /// One project's tasks: the sub-issues of the issue that project is, each with a page of
1347    /// what blocks it.
1348    ///
1349    /// Paged at `$memberFirst` — [`MEMBER_PAGE_SIZE`](super::MEMBER_PAGE_SIZE), the most rows
1350    /// one point buys — rather than at `$first`, because every row carries six connections and
1351    /// a hundred-row page cost six points to list a project of ten.
1352    ///
1353    /// The work this costs is the project's own size. Nothing about it grows as the board
1354    /// gains projects, or as those projects gain tasks.
1355    ///
1356    /// **Why `blockedBy` rides here and on no other page of issues.** What reads a project's
1357    /// tasks reads their edges next — `project graph` draws them, a copy carries them — and
1358    /// without them here that is one [`ISSUE_DEPENDENCIES`] per task, so the requests a graph
1359    /// costs grow with its tasks rather than with the pages of them. Carried here, a task
1360    /// blocked by no more than `$nestedFirst` issues answers its forward edges from this read,
1361    /// exactly as an [`ISSUE`] read of it does, and only one blocked by more is asked again.
1362    /// It adds a connection under each issue of the page — one rate-limit point per page,
1363    /// and `$nestedFirst` nodes per issue — and is kept off [`SEARCH_ISSUES`], whose pages
1364    /// answer questions that never read an edge.
1365    ///
1366    /// **The project issue itself rides here too**, with the page of what blocks it, because
1367    /// the reader of a project's tasks reads the project next: a copy writing the project reads
1368    /// it and its edges before it writes them. Carried on the request that already names the
1369    /// project, the first page answers that read and the dependency read after it, at the
1370    /// state GitHub answered in this command, rather than spending one more read on an item
1371    /// the cache's token cannot vouch for whole. Each sub-issue is kept the same way, so a
1372    /// copy's read of a task this listing carried is answered by it rather than sent again.
1373    /// Only a copy's read-before-write takes them; every other read by id reads GitHub.
1374    pub const SUB_ISSUES: &str = concat!(
1375        r#"query($id:ID!,$memberFirst:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1376        relationship_events_variable!(),
1377        r#"){
1378      node(id:$id){__typename ...BoardIssue
1379        ... on Issue{blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}
1380          subIssues(first:$memberFirst,after:$after){
1381          pageInfo{hasNextPage endCursor}
1382          nodes{__typename ...BoardIssue ... on Issue{
1383            blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}
1384          }}
1385        }}}
1386    }"#,
1387        board_issue!(),
1388        related_issue!()
1389    );
1390
1391    /// Everything this source reads about one issue comment, wherever it reaches one.
1392    ///
1393    /// A macro for the reason [`board_issue!`] is one: a comment listed, a comment just added
1394    /// and a comment just edited are handed to one mapper, so they are selected by one
1395    /// spelling. `author` is `Actor`, which GitHub answers `null` for an account that no
1396    /// longer exists, and `login` is the one member every kind of actor carries; `__typename`
1397    /// says whether it is a `Bot`, whose `login` GitHub's own pages spell with `[bot]` after it.
1398    macro_rules! issue_comment {
1399        () => {
1400            "id author{__typename login} createdAt updatedAt body url"
1401        };
1402    }
1403
1404    /// What a read of the board's own `items` selects of each item's content.
1405    ///
1406    /// A macro for the reason [`board_item_values!`] is one: [`BOARD`] and [`ORIGIN_LOOKUP`]
1407    /// both walk `ProjectV2.items` and hand each item to one resolver, so they select its
1408    /// content by one spelling.
1409    macro_rules! board_item_content {
1410        () => { board_item_content!("") };
1411        ($comments:expr) => {
1412            concat!(r#" content{
1413        ... on Issue{__typename id number title body url createdAt updatedAt state stateReason(enableDuplicate:$duplicates) repository{nameWithOwner} parent{id} subIssuesSummary{total} commentCount:comments{totalCount} relationshipEvents:timelineItems(itemTypes:$relationshipEvents){totalCount} labels(first:$nestedFirst){nodes{id name color}pageInfo{hasNextPage}}"#, $comments, r#"}
1414        ... on PullRequest{__typename id}
1415        ... on DraftIssue{__typename id title body createdAt updatedAt}
1416      }"#)
1417        };
1418    }
1419
1420    macro_rules! board_listing {
1421        ($variables:expr, $comments:expr) => { concat!(
1422        r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$nestedFirst:Int!,$duplicates:Boolean!"#,
1423        relationship_events_variable!(), $variables,
1424        r#"){
1425      owner:repositoryOwner(login:$owner){
1426        ... on ProjectV2Owner{projectV2(number:$number){...Board}}
1427      }
1428    } fragment Board on ProjectV2 { id title
1429      fields(first:$nestedFirst){nodes{
1430        ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1431        ... on ProjectV2Field{__typename id name dataType}
1432      }pageInfo{hasNextPage}}
1433      items(first:$first,after:$after){nodes{id updatedAt "#,
1434        board_item_values!(),
1435        board_item_content!($comments),
1436        r#"} pageInfo{hasNextPage endCursor}}
1437    }"#
1438    ) };
1439    }
1440
1441    /// Reads the board's fields and one page of its items.
1442    pub const BOARD: &str = board_listing!("", "");
1443
1444    /// A board page carrying each issue's first comment page in the same request.
1445    pub const BOARD_WITH_COMMENTS: &str = concat!(
1446        board_listing!(
1447            ",$commentFirst:Int!",
1448            concat!(
1449                "comments(first:$commentFirst){nodes{",
1450                issue_comment!(),
1451                "}pageInfo{hasNextPage endCursor}} blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}"
1452            )
1453        ),
1454        related_issue!()
1455    );
1456
1457    /// Every carrier of one copy origin, by two reads in one request, and nothing else of
1458    /// the board.
1459    ///
1460    /// **`originItems`** is the board's own items narrowed by its own field filter —
1461    /// `ProjectV2.items(query:)`, which GitHub's schema declares as "Search query for
1462    /// filtering items" — to those whose `onetaskgraph.origin` text field holds the
1463    /// qualified id, quoted. It reads the field every carrier already holds, whichever release
1464    /// wrote it, and matches it exactly: measured on 2026-09-29 against a 394-item board,
1465    /// the quoted, the unquoted and the bare-value spellings each returned exactly the one
1466    /// carrier and a prefix of the value returned none. It is `ProjectV2.items`, so it lags a
1467    /// fresh `addProjectV2ItemById` the way that connection does.
1468    ///
1469    /// **`search`** is the board-scoped issue search for the same id as a quoted phrase in
1470    /// the body, which is where this source mirrors the origin into its metadata slot. GitHub
1471    /// indexes that comment, and the index catches up with a write in a second or two rather
1472    /// than in minutes, so it finds a carrier another process wrote that the first read is
1473    /// still behind on.
1474    ///
1475    /// Each connection pages at `$originFirst`, its own small size — see `ORIGIN_PAGE_SIZE`
1476    /// — and resumes from its own cursor; a connection already walked to its end is resumed
1477    /// from its last cursor, which answers an empty page. Every candidate either read returns
1478    /// is confirmed against its own origin field before it is reported, so a token match of
1479    /// the search or anything else the filter admits never is.
1480    ///
1481    /// The root is aliased `originItems` rather than `owner`, so nothing counting the board's
1482    /// own whole reads counts this one among them.
1483    pub const ORIGIN_LOOKUP: &str = concat!(
1484        r#"query($owner:String!,$number:Int!,$filter:String!,$search:String!,$type:SearchType!,$originFirst:Int!,$itemsAfter:String,$searchAfter:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1485        relationship_events_variable!(),
1486        r#"){
1487      originItems:repositoryOwner(login:$owner){
1488        ... on ProjectV2Owner{projectV2(number:$number){
1489          items(first:$originFirst,after:$itemsAfter,query:$filter){nodes{id updatedAt "#,
1490        board_item_values!(),
1491        board_item_content!(),
1492        r#"} pageInfo{hasNextPage endCursor}}
1493        }}
1494      }
1495      search(query:$search,type:$type,first:$originFirst,after:$searchAfter){
1496        pageInfo{hasNextPage endCursor}
1497        nodes{__typename ...BoardIssue}
1498      }
1499    }"#,
1500        board_issue!()
1501    );
1502
1503    /// Every closed item of the board, by the board's own field filter — what
1504    /// `task status reconcile` reads, and nothing else of the board.
1505    ///
1506    /// **`ProjectV2.items(query:)` narrowed by `$filter`**, which this source binds to
1507    /// `is:closed` alone, so a board whose open items are most of it is not read whole to find
1508    /// the closed ones. It is narrowed rather than trusted: every item it answers is confirmed
1509    /// closed, with a reason and a card that contradict each other, from the item node it
1510    /// already carries, so a filter that also let open items through would cost reads and
1511    /// write nothing wrong.
1512    ///
1513    /// The board's own id and field definitions ride along, as [`BOARD`] carries them, so the
1514    /// option writes that follow need no read of the board. The root is aliased `closedItems`
1515    /// rather than `owner`, so nothing counting the board's own whole reads counts this one
1516    /// among them.
1517    pub const CLOSED_ITEMS: &str = concat!(
1518        r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$filter:String!,$nestedFirst:Int!,$duplicates:Boolean!"#,
1519        relationship_events_variable!(),
1520        r#"){
1521      closedItems:repositoryOwner(login:$owner){
1522        ... on ProjectV2Owner{projectV2(number:$number){id
1523          fields(first:$nestedFirst){nodes{
1524            ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1525            ... on ProjectV2Field{__typename id name dataType}
1526          }pageInfo{hasNextPage}}
1527          items(first:$first,after:$after,query:$filter){nodes{id updatedAt "#,
1528        board_item_values!(),
1529        board_item_content!(),
1530        r#"} pageInfo{hasNextPage endCursor}}
1531        }}
1532      }
1533    }"#
1534    );
1535
1536    /// Every open item of the board, drafts included, by the board's own field filter — what a
1537    /// task listing whose every status category is open reads, and nothing else of the board.
1538    ///
1539    /// **`ProjectV2.items(query:)` narrowed by `$filter`**, which this source binds to
1540    /// `is:open` alone. GitHub's filter reads the issue's state, not its card, so it answers
1541    /// every open issue whatever column its card sits in — an open issue under a terminal card,
1542    /// and one under an option no mapping names, among them — and every draft, which has no
1543    /// state and is never closed; measured on the real board by `spike-store-defects`, it read
1544    /// 466 open items in five requests where the whole board's walk and its issue search took
1545    /// thirty-one. Each item's category is still confirmed in process from its own node, so a
1546    /// filter that let a closed item through would cost a read and keep nothing it should not.
1547    ///
1548    /// The board's own id and field definitions ride along, as [`CLOSED_ITEMS`] carries them,
1549    /// so a status write after it needs no read of the board's fields. The root is aliased
1550    /// `openItems`, so nothing counting the board's whole reads counts this one among them.
1551    pub const OPEN_ITEMS: &str = concat!(
1552        r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$filter:String!,$nestedFirst:Int!,$duplicates:Boolean!"#,
1553        relationship_events_variable!(),
1554        r#"){
1555      openItems:repositoryOwner(login:$owner){
1556        ... on ProjectV2Owner{projectV2(number:$number){id
1557          fields(first:$nestedFirst){nodes{
1558            ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1559            ... on ProjectV2Field{__typename id name dataType}
1560          }pageInfo{hasNextPage}}
1561          items(first:$first,after:$after,query:$filter){nodes{id updatedAt "#,
1562        board_item_values!(),
1563        board_item_content!(),
1564        r#"} pageInfo{hasNextPage endCursor}}
1565        }}
1566      }
1567    }"#
1568    );
1569
1570    /// One alias of [`ISSUES_BY_REFERENCE`]: the issue `$owner<n>/$name<n>#$number<n>` names.
1571    macro_rules! reference_alias {
1572        ($n:literal) => {
1573            concat!(
1574                "\n      r",
1575                stringify!($n),
1576                ":repository(owner:$owner",
1577                stringify!($n),
1578                ",name:$name",
1579                stringify!($n),
1580                "){issue(number:$number",
1581                stringify!($n),
1582                "){...HeldIssue}}"
1583            )
1584        };
1585    }
1586
1587    /// [`REFERENCE_BATCH`](super::REFERENCE_BATCH) issues at once, each by its repository and
1588    /// number — the one read `task status complete` makes of a source, and nothing else of
1589    /// the board: no `items`, no search and no project read.
1590    ///
1591    /// **Its own fragment, lighter than `board_issue!`, and that is what makes fifty
1592    /// references one point.** It selects no labels, and of each board membership only the
1593    /// `Status` value, by name, with `fieldValueByName` — so each alias asks GitHub for one
1594    /// connection, its page of memberships, where the whole fragment asks for five. What a
1595    /// completion writes is a card and, at most, the issue's state, so the labels and the other
1596    /// field values it leaves out are never what it needs; an item read this way is held for
1597    /// that write alone and never answers another read. An issue whose entry for this board is
1598    /// past its first page of memberships is walked with [`ISSUE_BOARD_ITEMS`], exactly as
1599    /// every other read of an issue recovers one.
1600    ///
1601    /// Fixed-size, as [`ISSUE_DETAILS`] is, so there is one document to price: a batch of
1602    /// fewer references binds the slots it has none for to its last one.
1603    pub const ISSUES_BY_REFERENCE: &str = concat!(
1604        r#"query($owner0:String!,$name0:String!,$number0:Int!,$owner1:String!,$name1:String!,$number1:Int!,$owner2:String!,$name2:String!,$number2:Int!,$owner3:String!,$name3:String!,$number3:Int!,$owner4:String!,$name4:String!,$number4:Int!,$owner5:String!,$name5:String!,$number5:Int!,$owner6:String!,$name6:String!,$number6:Int!,$owner7:String!,$name7:String!,$number7:Int!,$owner8:String!,$name8:String!,$number8:Int!,$owner9:String!,$name9:String!,$number9:Int!,$owner10:String!,$name10:String!,$number10:Int!,$owner11:String!,$name11:String!,$number11:Int!,$owner12:String!,$name12:String!,$number12:Int!,$owner13:String!,$name13:String!,$number13:Int!,$owner14:String!,$name14:String!,$number14:Int!,$owner15:String!,$name15:String!,$number15:Int!,$owner16:String!,$name16:String!,$number16:Int!,$owner17:String!,$name17:String!,$number17:Int!,$owner18:String!,$name18:String!,$number18:Int!,$owner19:String!,$name19:String!,$number19:Int!,$owner20:String!,$name20:String!,$number20:Int!,$owner21:String!,$name21:String!,$number21:Int!,$owner22:String!,$name22:String!,$number22:Int!,$owner23:String!,$name23:String!,$number23:Int!,$owner24:String!,$name24:String!,$number24:Int!,$owner25:String!,$name25:String!,$number25:Int!,$owner26:String!,$name26:String!,$number26:Int!,$owner27:String!,$name27:String!,$number27:Int!,$owner28:String!,$name28:String!,$number28:Int!,$owner29:String!,$name29:String!,$number29:Int!,$owner30:String!,$name30:String!,$number30:Int!,$owner31:String!,$name31:String!,$number31:Int!,$owner32:String!,$name32:String!,$number32:Int!,$owner33:String!,$name33:String!,$number33:Int!,$owner34:String!,$name34:String!,$number34:Int!,$owner35:String!,$name35:String!,$number35:Int!,$owner36:String!,$name36:String!,$number36:Int!,$owner37:String!,$name37:String!,$number37:Int!,$owner38:String!,$name38:String!,$number38:Int!,$owner39:String!,$name39:String!,$number39:Int!,$owner40:String!,$name40:String!,$number40:Int!,$owner41:String!,$name41:String!,$number41:Int!,$owner42:String!,$name42:String!,$number42:Int!,$owner43:String!,$name43:String!,$number43:Int!,$owner44:String!,$name44:String!,$number44:Int!,$owner45:String!,$name45:String!,$number45:Int!,$owner46:String!,$name46:String!,$number46:Int!,$owner47:String!,$name47:String!,$number47:Int!,$owner48:String!,$name48:String!,$number48:Int!,$owner49:String!,$name49:String!,$number49:Int!,$boardItems:Int!,$statusField:String!,$duplicates:Boolean!"#,
1605        relationship_events_variable!(),
1606        r#"){"#,
1607        reference_alias!(0),
1608        reference_alias!(1),
1609        reference_alias!(2),
1610        reference_alias!(3),
1611        reference_alias!(4),
1612        reference_alias!(5),
1613        reference_alias!(6),
1614        reference_alias!(7),
1615        reference_alias!(8),
1616        reference_alias!(9),
1617        reference_alias!(10),
1618        reference_alias!(11),
1619        reference_alias!(12),
1620        reference_alias!(13),
1621        reference_alias!(14),
1622        reference_alias!(15),
1623        reference_alias!(16),
1624        reference_alias!(17),
1625        reference_alias!(18),
1626        reference_alias!(19),
1627        reference_alias!(20),
1628        reference_alias!(21),
1629        reference_alias!(22),
1630        reference_alias!(23),
1631        reference_alias!(24),
1632        reference_alias!(25),
1633        reference_alias!(26),
1634        reference_alias!(27),
1635        reference_alias!(28),
1636        reference_alias!(29),
1637        reference_alias!(30),
1638        reference_alias!(31),
1639        reference_alias!(32),
1640        reference_alias!(33),
1641        reference_alias!(34),
1642        reference_alias!(35),
1643        reference_alias!(36),
1644        reference_alias!(37),
1645        reference_alias!(38),
1646        reference_alias!(39),
1647        reference_alias!(40),
1648        reference_alias!(41),
1649        reference_alias!(42),
1650        reference_alias!(43),
1651        reference_alias!(44),
1652        reference_alias!(45),
1653        reference_alias!(46),
1654        reference_alias!(47),
1655        reference_alias!(48),
1656        reference_alias!(49),
1657        "\n    }",
1658        r#" fragment HeldIssue on Issue{__typename id number title body url createdAt updatedAt state stateReason(enableDuplicate:$duplicates) repository{nameWithOwner} parent{id} subIssuesSummary{total} commentCount:comments{totalCount} relationshipEvents:timelineItems(itemTypes:$relationshipEvents){totalCount}
1659      projectItems(first:$boardItems){nodes{id updatedAt project{id number}
1660        status:fieldValueByName(name:$statusField){... on ProjectV2ItemFieldSingleSelectValue{name field{
1661          ... on ProjectV2SingleSelectField{id name options{id name}}
1662        }}}
1663      }pageInfo{hasNextPage endCursor}}}"#
1664    );
1665
1666    /// The board's own id and field definitions, and not one of its items.
1667    ///
1668    /// What a write needs of the board when the item it writes does not say: the id a field
1669    /// write and `addProjectV2ItemById` address, and the definitions of the `Status` and
1670    /// origin fields. It selects no `items`, so what it costs is the board's field list
1671    /// however many items the board holds — and it decides nothing about which items those
1672    /// are, which is the question a read of one item by its own id answers instead.
1673    ///
1674    /// The root is aliased `boardFields` rather than `owner`, so nothing counting the
1675    /// board's item reads by their root counts this one among them.
1676    pub const BOARD_FIELDS: &str = r#"query($owner:String!,$number:Int!,$nestedFirst:Int!){
1677      boardFields:repositoryOwner(login:$owner){
1678        ... on ProjectV2Owner{projectV2(number:$number){id
1679          fields(first:$nestedFirst){nodes{
1680            ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1681            ... on ProjectV2Field{__typename id name dataType}
1682          }pageInfo{hasNextPage}}
1683        }}
1684      }
1685    }"#;
1686
1687    /// One board draft by its own node id, with the board item it sits in.
1688    ///
1689    /// A draft is not an issue, so [`ISSUE`] reaches it and reads nothing of it; this is the
1690    /// second read that answers it. `DraftIssue.projectV2Items` names the board item a draft
1691    /// is — GitHub links a draft to one item — with the same [`board_item_values!`] the
1692    /// issue fragment reads, so a draft reached by id resolves through the same resolver a
1693    /// board listing hands it to, and nothing has to list the board to find one.
1694    pub const DRAFT: &str = concat!(
1695        r#"query($id:ID!,$nestedFirst:Int!,$boardItems:Int!){
1696      node(id:$id){__typename ... on DraftIssue{id title body createdAt updatedAt
1697        projectV2Items(first:$boardItems){nodes{id project{id number}
1698        "#,
1699        board_item_values!(),
1700        r#"}pageInfo{hasNextPage endCursor}}}}
1701    }"#
1702    );
1703
1704    /// One issue's board memberships alone, walked past the page a read of it carried.
1705    ///
1706    /// The recovery read behind [`GitHubProjectsSource::resolve_issue`](super::GitHubProjectsSource):
1707    /// every document above carries a *page* of `Issue.projectItems`, and an issue on more
1708    /// boards than that page holds may have this board's entry past its end. This asks that
1709    /// one issue for its memberships and nothing else — the caller already holds the issue —
1710    /// so an answer of "this board does not hold it" is only ever given about a connection
1711    /// read to exhaustion.
1712    ///
1713    /// It selects the board item's id, its project number and the same
1714    /// [`board_item_values!`] the fragment does, because what it produces is handed to the
1715    /// very same resolver: an issue recovered this way reports the same title, the same
1716    /// status, the same labels and the same qualified id as one whose entry was on the
1717    /// page.
1718    ///
1719    /// `$first` rather than `$boardItems`: this document reads one issue, so nothing
1720    /// multiplies through it and the membership connection can be walked at
1721    /// [`MAX_PAGE_SIZE`](super::MAX_PAGE_SIZE) — which is what keeps the recovery to one
1722    /// further request for any issue a person really keeps.
1723    pub const ISSUE_BOARD_ITEMS: &str = concat!(
1724        r#"query($id:ID!,$first:Int!,$after:String,$nestedFirst:Int!){
1725      node(id:$id){
1726        ... on Issue{projectItems(first:$first,after:$after){
1727          nodes{id updatedAt project{id number}
1728        "#,
1729        board_item_values!(),
1730        r#"}
1731          pageInfo{hasNextPage endCursor}}}
1732      }
1733    }"#
1734    );
1735    /// Whether the board's Project is public — half of what decides whether a write here can
1736    /// be read by anybody. Needs the `read:project` scope.
1737    pub const PROJECT_VISIBILITY: &str = r#"query($owner:String!,$number:Int!){visibility:repositoryOwner(login:$owner){... on ProjectV2Owner{projectV2(number:$number){public}}}}"#;
1738    /// Resolves the configured repository's node id, which creating an issue requires.
1739    pub const REPOSITORY: &str = r#"query($owner:String!,$name:String!){repository(owner:$owner,name:$name){id nameWithOwner}}"#;
1740    /// What creating an issue needs and has not read yet: the board's own id and field
1741    /// definitions, as [`BOARD_FIELDS`] reads them, and the node id of the repository the
1742    /// issue is created in, as [`REPOSITORY`] reads it — in one request.
1743    ///
1744    /// Sent at the point a create knows which repository it is for, when neither half is
1745    /// already known to this process; a create needing only one of them sends that one's own
1746    /// document. Neither half is kept past the process: a field's option ids are re-minted by
1747    /// `sources fields --apply`, so a copy of them held between runs would write the wrong
1748    /// status.
1749    pub const CREATION_CONTEXT: &str = r#"query($owner:String!,$number:Int!,$nestedFirst:Int!,$repositoryOwner:String!,$repositoryName:String!){
1750      boardFields:repositoryOwner(login:$owner){
1751        ... on ProjectV2Owner{projectV2(number:$number){id
1752          fields(first:$nestedFirst){nodes{
1753            ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1754            ... on ProjectV2Field{__typename id name dataType}
1755          }pageInfo{hasNextPage}}
1756        }}
1757      }
1758      repository(owner:$repositoryOwner,name:$repositoryName){id nameWithOwner}
1759    }"#;
1760    /// Reads both dependency directions for one issue, with each far end's own kind — and
1761    /// the issue's own body, which is where an edge to another source is recorded, so that
1762    /// half of a dependency read needs no second read of the issue or of the board.
1763    pub const ISSUE_DEPENDENCIES: &str = concat!(
1764        r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename
1765      ... on Issue{body
1766        blockedBy(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1767        blocking(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1768      }}}"#,
1769        related_issue!()
1770    );
1771    /// What one item depends on: [`ISSUE_DEPENDENCIES`] narrowed to `blockedBy`, so a
1772    /// dependency read asks GitHub for the one direction it answers. The issue's `body` rides
1773    /// along because its metadata slot is where an edge to another source is recorded — and a
1774    /// board draft's `body` too, with the one board item GitHub links a draft to and, aliased
1775    /// `board`, this board's own id, so a draft's recorded edges are read off this same answer
1776    /// and only when that item is this board's: no draft read and no board read follow it.
1777    ///
1778    /// The draft's board item is asked for under a root of its own, aliased `draft`, rather
1779    /// than beside its `body` under `node`. GitHub counts the type-conditional fragments of
1780    /// one selection as the largest of them — `blockedBy`'s 100 alone, where this workspace's
1781    /// calculation adds the draft's 3 — while separate roots are summed by both, so this is
1782    /// the spelling whose node count GitHub and the calculation agree on. Both price it at
1783    /// one point; the credentialed lane's reconciliation is what holds the two to that.
1784    pub const ISSUE_DEPENDS_ON: &str = concat!(
1785        r#"query($id:ID!,$first:Int!,$after:String,$owner:String!,$number:Int!,$boardItems:Int!){
1786      node(id:$id){__typename
1787      ... on Issue{body
1788        blockedBy(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1789      }
1790      ... on DraftIssue{id body}}
1791      draft:node(id:$id){... on DraftIssue{projectV2Items(first:$boardItems){nodes{project{id number}}pageInfo{hasNextPage}}}}
1792      board:repositoryOwner(login:$owner){... on ProjectV2Owner{projectV2(number:$number){id}}}}"#,
1793        related_issue!()
1794    );
1795    /// What depends on one issue: [`ISSUE_DEPENDENCIES`] with its `blocking` alone. No `body`:
1796    /// the reverse of a recorded edge is derived from the far end, never written down here.
1797    pub const ISSUE_DEPENDED_ON_BY: &str = concat!(
1798        r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename
1799      ... on Issue{
1800        blocking(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1801      }}}"#,
1802        related_issue!()
1803    );
1804    /// Creates one issue. Outside a copy it is created on no board, and [`ADD_TO_BOARD`] files
1805    /// it; inside one, its input names the board in `projectV2Ids` and its project in
1806    /// `parentIssueId`, so this one request files it under both — see
1807    /// [`GitHubProjectsSource::create_filed_issue`](super::GitHubProjectsSource).
1808    pub const CREATE_ISSUE: &str =
1809        r#"mutation($input:CreateIssueInput!){createIssue(input:$input){issue{id number url}}}"#;
1810    /// Puts an existing issue on the configured board.
1811    pub const ADD_TO_BOARD: &str = r#"mutation($input:AddProjectV2ItemByIdInput!){addProjectV2ItemById(input:$input){item{id}}}"#;
1812    /// Updates an issue's visible fields and its open or closed state in one call.
1813    pub const UPDATE_ISSUE: &str =
1814        r#"mutation($input:UpdateIssueInput!){updateIssue(input:$input){issue{id}}}"#;
1815    /// Closes one issue for a reason, the survivor it is a duplicate of included — the one way
1816    /// GitHub records a duplicate's link: `updateIssue`'s `stateInput` carries no survivor, and
1817    /// the REST `state_reason=duplicate` is accepted and records none, both measured by
1818    /// `spike-store-defects`.
1819    pub const CLOSE_ISSUE: &str =
1820        r#"mutation($input:CloseIssueInput!){closeIssue(input:$input){issue{id}}}"#;
1821    /// Updates an existing draft's user-visible fields.
1822    pub const UPDATE_DRAFT: &str = r#"mutation($input:UpdateProjectV2DraftIssueInput!){updateProjectV2DraftIssue(input:$input){draftIssue{id}}}"#;
1823    /// Updates a text or single-select value on one project item.
1824    pub const UPDATE_FIELD: &str = r#"mutation($input:UpdateProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!){updateProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}}}}}"#;
1825    /// Writes up to six board fields and clears up to three in one ordered mutation: every
1826    /// aliased field is included by its own boolean, as [`FIELD_WRITE_SLOTS`](super::FIELD_WRITE_SLOTS)
1827    /// and [`FIELD_CLEAR_SLOTS`](super::FIELD_CLEAR_SLOTS) name them, writes before clears.
1828    pub const UPDATE_FIELDS: &str = r#"mutation($input:UpdateProjectV2ItemFieldValueInput!,$second:UpdateProjectV2ItemFieldValueInput!,$third:UpdateProjectV2ItemFieldValueInput!,$fourth:UpdateProjectV2ItemFieldValueInput!,$fifth:UpdateProjectV2ItemFieldValueInput!,$sixth:UpdateProjectV2ItemFieldValueInput!,$clear:ClearProjectV2ItemFieldValueInput!,$clearSecond:ClearProjectV2ItemFieldValueInput!,$clearThird:ClearProjectV2ItemFieldValueInput!,$writeFirst:Boolean!,$writeSecond:Boolean!,$writeThird:Boolean!,$writeFourth:Boolean!,$writeFifth:Boolean!,$writeSixth:Boolean!,$writeClear:Boolean!,$writeClearSecond:Boolean!,$writeClearThird:Boolean!){updateProjectV2ItemFieldValue(input:$input) @include(if:$writeFirst){projectV2Item{id}} second:updateProjectV2ItemFieldValue(input:$second) @include(if:$writeSecond){projectV2Item{id}} third:updateProjectV2ItemFieldValue(input:$third) @include(if:$writeThird){projectV2Item{id}} fourth:updateProjectV2ItemFieldValue(input:$fourth) @include(if:$writeFourth){projectV2Item{id}} fifth:updateProjectV2ItemFieldValue(input:$fifth) @include(if:$writeFifth){projectV2Item{id}} sixth:updateProjectV2ItemFieldValue(input:$sixth) @include(if:$writeSixth){projectV2Item{id}} cleared:clearProjectV2ItemFieldValue(input:$clear) @include(if:$writeClear){projectV2Item{id}} clearedSecond:clearProjectV2ItemFieldValue(input:$clearSecond) @include(if:$writeClearSecond){projectV2Item{id}} clearedThird:clearProjectV2ItemFieldValue(input:$clearThird) @include(if:$writeClearThird){projectV2Item{id}}}"#;
1829    /// Clears one project item's value of one field, which is what a `none` priority is.
1830    pub const CLEAR_FIELD: &str = r#"mutation($input:ClearProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!){clearProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}}}}}"#;
1831    /// Creates one field: a single-select one with its options, or a text one for a projected
1832    /// metadata value. Only the guarded field setup may use this document, and only for a
1833    /// field the board lacks.
1834    pub const CREATE_FIELD: &str = r#"mutation($input:CreateProjectV2FieldInput!){createProjectV2Field(input:$input){projectV2Field{... on ProjectV2SingleSelectField{id name options{id name color description}}}}}"#;
1835    /// Replaces a single-select field's options. Only the guarded field setup — the
1836    /// `status-options` and `fields` operations — may use this document, because GitHub
1837    /// treats the input as the complete option list.
1838    pub const STATUS_OPTIONS_UPDATE: &str = r#"mutation($input:UpdateProjectV2FieldInput!){updateProjectV2Field(input:$input){projectV2Field{... on ProjectV2SingleSelectField{id options{id name color description}}}}}"#;
1839    /// A fresh snapshot of the Status field and every board item's assignment.
1840    pub const STATUS_OPTIONS_SNAPSHOT: &str = r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$nestedFirst:Int!){owner:repositoryOwner(login:$owner){... on ProjectV2Owner{projectV2(number:$number){id fields(first:$nestedFirst){nodes{... on ProjectV2SingleSelectField{id name options{id name color description}}}pageInfo{hasNextPage}} items(first:$first,after:$after){nodes{id fieldValues(first:$nestedFirst){nodes{... on ProjectV2ItemFieldSingleSelectValue{name optionId field{... on ProjectV2SingleSelectField{id name}}}}pageInfo{hasNextPage}}}pageInfo{hasNextPage endCursor}}}}}}"#;
1841    /// Files one issue under another as a sub-issue, which is what project membership is.
1842    pub const ADD_SUB_ISSUE: &str =
1843        r#"mutation($input:AddSubIssueInput!){addSubIssue(input:$input){issue{id} subIssue{id}}}"#;
1844    /// Takes one issue back out of its parent.
1845    pub const REMOVE_SUB_ISSUE: &str = r#"mutation($input:RemoveSubIssueInput!){removeSubIssue(input:$input){issue{id} subIssue{id}}}"#;
1846    /// Adds GitHub's native issue blocked-by relationship.
1847    pub const ADD_BLOCKED_BY: &str = r#"mutation($input:AddBlockedByInput!){addBlockedBy(input:$input){issue{id} blockingIssue{id}}}"#;
1848    /// One origin of [`ORIGIN_LOOKUPS`]: [`ORIGIN_LOOKUP`]'s two connections for the origin the
1849    /// `$filter<n>` and `$search<n>` of slot `<n>` name, sent only while `$ask<n>` holds.
1850    macro_rules! origin_lookup_alias {
1851        ($n:literal) => {
1852            concat!(
1853                "\n      o",
1854                stringify!($n),
1855                ":repositoryOwner(login:$owner) @include(if:$ask",
1856                stringify!($n),
1857                "){... on ProjectV2Owner{projectV2(number:$number){items(first:$lookupFirst,query:$filter",
1858                stringify!($n),
1859                "){nodes{id updatedAt ",
1860                board_item_values!(),
1861                board_item_content!(),
1862                "} pageInfo{hasNextPage endCursor}}}}}\n      s",
1863                stringify!($n),
1864                ":search(query:$search",
1865                stringify!($n),
1866                ",type:$type,first:$lookupFirst) @include(if:$ask",
1867                stringify!($n),
1868                "){pageInfo{hasNextPage endCursor} nodes{__typename ...BoardIssue}}"
1869            )
1870        };
1871    }
1872
1873    /// [`ORIGIN_LOOKUPS`], with `$extra_variables` declared after its own and `$extra_fields`
1874    /// selected beside them: one spelling of the batched lookup for the documents that send it.
1875    macro_rules! origin_lookups {
1876        ($extra_variables:literal, $extra_fields:literal) => {
1877            concat!(
1878                r#"query($owner:String!,$number:Int!,$type:SearchType!,$lookupFirst:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!,$repositoryOwner:String!,$repositoryName:String!,$filter0:String!,$filter1:String!,$filter2:String!,$filter3:String!,$filter4:String!,$filter5:String!,$filter6:String!,$filter7:String!,$filter8:String!,$filter9:String!,$search0:String!,$search1:String!,$search2:String!,$search3:String!,$search4:String!,$search5:String!,$search6:String!,$search7:String!,$search8:String!,$search9:String!,$ask0:Boolean!,$ask1:Boolean!,$ask2:Boolean!,$ask3:Boolean!,$ask4:Boolean!,$ask5:Boolean!,$ask6:Boolean!,$ask7:Boolean!,$ask8:Boolean!,$ask9:Boolean!"#,
1879                relationship_events_variable!(),
1880                $extra_variables,
1881                r#"){
1882      boardFields:repositoryOwner(login:$owner){
1883        ... on ProjectV2Owner{projectV2(number:$number){id
1884          fields(first:$nestedFirst){nodes{
1885            ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1886            ... on ProjectV2Field{__typename id name dataType}
1887          }pageInfo{hasNextPage}}
1888        }}
1889      }
1890      repository(owner:$repositoryOwner,name:$repositoryName){id databaseId nameWithOwner}"#,
1891                $extra_fields,
1892                origin_lookup_alias!(0),
1893                origin_lookup_alias!(1),
1894                origin_lookup_alias!(2),
1895                origin_lookup_alias!(3),
1896                origin_lookup_alias!(4),
1897                origin_lookup_alias!(5),
1898                origin_lookup_alias!(6),
1899                origin_lookup_alias!(7),
1900                origin_lookup_alias!(8),
1901                origin_lookup_alias!(9),
1902                "\n    }",
1903                board_issue!()
1904            )
1905        };
1906    }
1907
1908    /// The first page of [`ORIGIN_LOOKUP`] for up to [`ORIGIN_BATCH`](super::ORIGIN_BATCH)
1909    /// origins a copy is about to look for, and everything creating an item then reads —
1910    /// the board's own id and field definitions, as [`CREATION_CONTEXT`] reads them, and the node
1911    /// id and the numeric id of the repository an issue is created in — in one request.
1912    ///
1913    /// What a copy reads before it writes anything, so that finding none of its records on the
1914    /// board and creating every one costs this read and the writes. An origin whose page says
1915    /// there is more is left to its own [`ORIGIN_LOOKUP`]. The repository's numeric id is what an
1916    /// image upload names, so a copy carrying assets needs no `GET /repos/{owner}/{repo}` either.
1917    pub const ORIGIN_LOOKUPS: &str = origin_lookups!("", "");
1918
1919    /// [`ORIGIN_LOOKUPS`], with a page of the members of the project `$project` beside it, each
1920    /// trimmed to what classifying it reads — its id, its parent, its body and its repository,
1921    /// and no connection under it.
1922    ///
1923    /// What a document copy sends where the public boundary screens its write: the document is
1924    /// held to who may read its project, which is its members' classification as much as the
1925    /// project's own, and this request carries both the project — among the origins it asks —
1926    /// and its members. GitHub's own dry run prices it at the one point [`ORIGIN_LOOKUPS`]
1927    /// costs alone (`docs/measurements/board-copy-gaps-2026-10-24/coalesced-members-dry-run`).
1928    pub const ORIGIN_LOOKUPS_WITH_MEMBERS: &str = origin_lookups!(
1929        ",$project:ID!,$memberFirst:Int!",
1930        "\n      members:node(id:$project){... on Issue{subIssues(first:$memberFirst){pageInfo{hasNextPage endCursor} nodes{id body parent{id} repository{nameWithOwner}}}}}"
1931    );
1932
1933    /// One slot `<n>` of a copy's aliased writes: `$<prefix><n>` is its input and `$send<n>`
1934    /// whether it is sent.
1935    macro_rules! write_slot {
1936        ($prefix:literal, $field:literal, $selection:literal, $n:literal) => {
1937            concat!(
1938                " ",
1939                $prefix,
1940                stringify!($n),
1941                ":",
1942                $field,
1943                "(input:$",
1944                $prefix,
1945                stringify!($n),
1946                ") @include(if:$send",
1947                stringify!($n),
1948                "){",
1949                $selection,
1950                "}"
1951            )
1952        };
1953    }
1954
1955    /// The variables of a copy's aliased writes: eleven inputs of `$type` named `$<prefix><n>`,
1956    /// and eleven `$send<n>`.
1957    macro_rules! write_variables {
1958        ($prefix:literal, $type:literal) => {
1959            concat!(
1960                "mutation(",
1961                "$",
1962                $prefix,
1963                "0:",
1964                $type,
1965                "!,$",
1966                $prefix,
1967                "1:",
1968                $type,
1969                "!,$",
1970                $prefix,
1971                "2:",
1972                $type,
1973                "!,$",
1974                $prefix,
1975                "3:",
1976                $type,
1977                "!,$",
1978                $prefix,
1979                "4:",
1980                $type,
1981                "!,$",
1982                $prefix,
1983                "5:",
1984                $type,
1985                "!,$",
1986                $prefix,
1987                "6:",
1988                $type,
1989                "!,$",
1990                $prefix,
1991                "7:",
1992                $type,
1993                "!,$",
1994                $prefix,
1995                "8:",
1996                $type,
1997                "!,$",
1998                $prefix,
1999                "9:",
2000                $type,
2001                "!,$",
2002                $prefix,
2003                "10:",
2004                $type,
2005                "!,",
2006                "$send0:Boolean!,$send1:Boolean!,$send2:Boolean!,$send3:Boolean!,$send4:Boolean!,",
2007                "$send5:Boolean!,$send6:Boolean!,$send7:Boolean!,$send8:Boolean!,$send9:Boolean!,",
2008                "$send10:Boolean!){"
2009            )
2010        };
2011    }
2012
2013    /// A copy's aliased writes of one kind: [`MUTATION_BATCH`](super::MUTATION_BATCH) slots of
2014    /// `$field`, each sent only while its `$send<n>` holds.
2015    macro_rules! write_batch {
2016        ($prefix:literal, $type:literal, $field:literal, $selection:literal) => {
2017            concat!(
2018                write_variables!($prefix, $type),
2019                write_slot!($prefix, $field, $selection, 0),
2020                write_slot!($prefix, $field, $selection, 1),
2021                write_slot!($prefix, $field, $selection, 2),
2022                write_slot!($prefix, $field, $selection, 3),
2023                write_slot!($prefix, $field, $selection, 4),
2024                write_slot!($prefix, $field, $selection, 5),
2025                write_slot!($prefix, $field, $selection, 6),
2026                write_slot!($prefix, $field, $selection, 7),
2027                write_slot!($prefix, $field, $selection, 8),
2028                write_slot!($prefix, $field, $selection, 9),
2029                write_slot!($prefix, $field, $selection, 10),
2030                "}"
2031            )
2032        };
2033    }
2034
2035    /// Creates up to [`MUTATION_BATCH`](super::MUTATION_BATCH) issues in one request, each filed on
2036    /// the board and under its project by the same `createIssue` — its `projectV2Ids` and
2037    /// `parentIssueId` — as [`CREATE_ISSUE`] creates one.
2038    pub const CREATE_ISSUES: &str = write_batch!(
2039        "create",
2040        "CreateIssueInput",
2041        "createIssue",
2042        "issue{id number url}"
2043    );
2044
2045    /// One issue of [`CREATED_BOARD_ITEMS`]: the board items the issue `$id<n>` names is on, with
2046    /// the `Status` value of each, read only while `$read<n>` holds.
2047    macro_rules! created_item_alias {
2048        ($n:literal) => {
2049            concat!(
2050                "\n      i",
2051                stringify!($n),
2052                ":node(id:$id",
2053                stringify!($n),
2054                ") @include(if:$read",
2055                stringify!($n),
2056                "){... on Issue{id projectItems(first:$boardItems){nodes{id project{id} status:fieldValueByName(name:$statusName){... on ProjectV2ItemFieldSingleSelectValue{name}}}}}}"
2057            )
2058        };
2059    }
2060
2061    /// The board item of each issue a copy created, up to
2062    /// [`COPY_DETAIL_BATCH`](super::COPY_DETAIL_BATCH) at a time, with its `Status` as the board
2063    /// set it: what `createIssue`'s `projectV2Ids` files the issue as, which GitHub adds after
2064    /// answering the create, so its id comes from a read made once every create has been sent.
2065    pub const CREATED_BOARD_ITEMS: &str = concat!(
2066        r#"query($id0:ID!,$id1:ID!,$id2:ID!,$id3:ID!,$id4:ID!,$id5:ID!,$id6:ID!,$id7:ID!,$id8:ID!,$id9:ID!,$id10:ID!,$id11:ID!,$id12:ID!,$id13:ID!,$id14:ID!,$id15:ID!,$id16:ID!,$id17:ID!,$id18:ID!,$id19:ID!,$id20:ID!,$read0:Boolean!,$read1:Boolean!,$read2:Boolean!,$read3:Boolean!,$read4:Boolean!,$read5:Boolean!,$read6:Boolean!,$read7:Boolean!,$read8:Boolean!,$read9:Boolean!,$read10:Boolean!,$read11:Boolean!,$read12:Boolean!,$read13:Boolean!,$read14:Boolean!,$read15:Boolean!,$read16:Boolean!,$read17:Boolean!,$read18:Boolean!,$read19:Boolean!,$read20:Boolean!,$boardItems:Int!,$statusName:String!){"#,
2067        created_item_alias!(0),
2068        created_item_alias!(1),
2069        created_item_alias!(2),
2070        created_item_alias!(3),
2071        created_item_alias!(4),
2072        created_item_alias!(5),
2073        created_item_alias!(6),
2074        created_item_alias!(7),
2075        created_item_alias!(8),
2076        created_item_alias!(9),
2077        created_item_alias!(10),
2078        created_item_alias!(11),
2079        created_item_alias!(12),
2080        created_item_alias!(13),
2081        created_item_alias!(14),
2082        created_item_alias!(15),
2083        created_item_alias!(16),
2084        created_item_alias!(17),
2085        created_item_alias!(18),
2086        created_item_alias!(19),
2087        created_item_alias!(20),
2088        "\n    }"
2089    );
2090
2091    /// The variables and the aliases of [`WRITE_BATCH`](super::WRITE_BATCH) slots: `$<prefix><n>`
2092    /// is a slot's input and `$<send><n>` whether it is sent, for the slot numbers given.
2093    macro_rules! wide_variables {
2094        ($prefix:literal, $type:literal, $send:literal; $($n:literal)+) => {
2095            concat!($("$", $prefix, stringify!($n), ":", $type, "!,$", $send, stringify!($n), ":Boolean!,",)+)
2096        };
2097    }
2098    macro_rules! wide_slots {
2099        ($prefix:literal, $field:literal, $selection:literal, $send:literal; $($n:literal)+) => {
2100            concat!($(
2101                " ", $prefix, stringify!($n), ":", $field, "(input:$", $prefix, stringify!($n),
2102                ") @include(if:$", $send, stringify!($n), "){", $selection, "}",
2103            )+)
2104        };
2105    }
2106
2107    /// Up to [`WRITE_BATCH`](super::WRITE_BATCH) board field values a copy writes on the items it
2108    /// created, each on its own item, in one ordered request.
2109    pub const WRITE_FIELD_VALUES: &str = concat!(
2110        "mutation(",
2111        wide_variables!("field", "UpdateProjectV2ItemFieldValueInput", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2112        "){",
2113        wide_slots!("field", "updateProjectV2ItemFieldValue", "projectV2Item{id}", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2114        "}"
2115    );
2116
2117    /// A copy's board field values and its blocked-by edges together, up to
2118    /// [`WRITE_BATCH`](super::WRITE_BATCH) of the two kinds between them, in one ordered request:
2119    /// every field value its `$sendField<n>` sends, then every edge its `$sendBlock<n>` sends.
2120    /// What a copy sends when one request of its writes holds both kinds; one holding a single
2121    /// kind is [`WRITE_FIELD_VALUES`] or [`ADD_BLOCKED_BYS`].
2122    pub const WRITE_FIELDS_AND_EDGES: &str = concat!(
2123        "mutation(",
2124        wide_variables!("field", "UpdateProjectV2ItemFieldValueInput", "sendField"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2125        wide_variables!("block", "AddBlockedByInput", "sendBlock"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2126        "){",
2127        wide_slots!("field", "updateProjectV2ItemFieldValue", "projectV2Item{id}", "sendField"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2128        wide_slots!("block", "addBlockedBy", "issue{id} blockingIssue{id}", "sendBlock"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2129        "}"
2130    );
2131
2132    /// Closes up to [`MUTATION_BATCH`](super::MUTATION_BATCH) issues a copy created at a closing
2133    /// status, each with its own `stateInput` and nothing else, once its option is selected.
2134    pub const CLOSE_ISSUES: &str =
2135        write_batch!("close", "UpdateIssueInput", "updateIssue", "issue{id}");
2136
2137    /// Updates up to [`MUTATION_BATCH`](super::MUTATION_BATCH) existing issues a copy rewrites,
2138    /// each with the members its own [`UPDATE_ISSUE`] would have sent, in one request.
2139    pub const UPDATE_ISSUES: &str =
2140        write_batch!("update", "UpdateIssueInput", "updateIssue", "issue{id}");
2141
2142    /// Up to [`WRITE_BATCH`](super::WRITE_BATCH) native blocked-by relationships a copy adds to the
2143    /// issues it created, in one request.
2144    pub const ADD_BLOCKED_BYS: &str = concat!(
2145        "mutation(",
2146        wide_variables!("block", "AddBlockedByInput", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2147        "){",
2148        wide_slots!("block", "addBlockedBy", "issue{id} blockingIssue{id}", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2149        "}"
2150    );
2151
2152    /// Removes one native issue blocked-by relationship.
2153    pub const REMOVE_BLOCKED_BY: &str = r#"mutation($input:RemoveBlockedByInput!){removeBlockedBy(input:$input){issue{id} blockingIssue{id}}}"#;
2154    /// Deletes one issue, which takes its board item with it.
2155    ///
2156    /// The engine sends this in one situation only: undoing a copy that could not finish,
2157    /// over the items that same copy created. Deleting the issue removes the board item
2158    /// too, so there is no second `deleteProjectV2Item` to keep in step with it.
2159    pub const DELETE_ISSUE: &str =
2160        r#"mutation($input:DeleteIssueInput!){deleteIssue(input:$input){repository{id}}}"#;
2161    /// Deletes up to [`DELETE_BATCH`](super::DELETE_BATCH) issues in one request, each as
2162    /// [`DELETE_ISSUE`] deletes one: what a write that created several issues and was refused
2163    /// part way sends to take them back.
2164    pub const DELETE_ISSUES: &str = concat!(
2165        "mutation(",
2166        wide_variables!("delete", "DeleteIssueInput", "send"; 0 1 2 3 4),
2167        "){",
2168        wide_slots!("delete", "deleteIssue", "repository{id}", "send"; 0 1 2 3 4),
2169        "}"
2170    );
2171
2172    /// One task's comments: a page of its issue's own `comments` connection.
2173    ///
2174    /// **No `orderBy`, and that is what makes the page oldest first.** GitHub's only
2175    /// `IssueCommentOrder` field is `UPDATED_AT`, which would move a comment to the end of the
2176    /// list every time somebody edited it; left unordered the connection answers in the order
2177    /// the comments were written, which is the order GitHub documents for the same collection
2178    /// over REST — ascending id. Nothing multiplies through it, so `$first` is the whole of its
2179    /// node count and the caller's own page size is pushed straight down.
2180    pub const ISSUE_COMMENTS: &str = concat!(
2181        r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename ... on Issue{comments(first:$first,after:$after){nodes{"#,
2182        issue_comment!(),
2183        r#"}pageInfo{hasNextPage endCursor}}}}}"#
2184    );
2185    /// One issue by its own node id, with a page of its comments: what `task show` and a
2186    /// comment listing read, in one request.
2187    ///
2188    /// [`ISSUE`] and [`ISSUE_COMMENTS`] in one document, rather than one then the other. The
2189    /// comments are selected here and **not** on the shared `board_issue!` fragment, which
2190    /// [`SEARCH_ISSUES`] and [`SUB_ISSUES`] nest under a page of a hundred issues: a comment
2191    /// connection there would multiply through both of those documents' price, and neither
2192    /// needs one.
2193    pub const ISSUE_DETAIL: &str = concat!(
2194        r#"query($id:ID!,$first:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2195        relationship_events_variable!(),
2196        r#"){
2197      node(id:$id){__typename ...BoardIssue ... on Issue{comments(first:$first,after:$after){nodes{"#,
2198        issue_comment!(),
2199        r#"}pageInfo{hasNextPage endCursor}}}}
2200    }"#,
2201        board_issue!()
2202    );
2203
2204    /// One alias of [`ISSUE_DETAILS`]: the item a batch's `$id<n>` names, with the first
2205    /// page of its comments when `$comments` asks for them.
2206    macro_rules! issue_details_alias {
2207        ($n:literal) => {
2208            concat!(
2209                "\n      i",
2210                stringify!($n),
2211                ":node(id:$id",
2212                stringify!($n),
2213                "){__typename ...BoardIssue ... on Issue{comments(first:$first) @include(if:$comments){nodes{",
2214                issue_comment!(),
2215                "}pageInfo{hasNextPage endCursor}}}}"
2216            )
2217        };
2218    }
2219
2220    /// [`ISSUE_DETAIL`] for [`DETAIL_BATCH`](super::DETAIL_BATCH) items at once, each by its
2221    /// own node id, as one fixed-size document of aliased `node(id:)` fields.
2222    ///
2223    /// **Aliased `node(id:)` rather than `nodes(ids:)`, and that is what keeps its price
2224    /// honest.** The `github-graphql-node-count` model this workspace prices with treats a
2225    /// field that supplies neither `first` nor `last` as free, and `nodes(ids:)` supplies
2226    /// neither — so every connection under it would be priced at nothing and the pin in
2227    /// `tests/point_cost.rs` would understate what GitHub charges. Each alias here is the
2228    /// one-item read the model already prices, so the batch costs what its aliases cost.
2229    ///
2230    /// **Fixed-size, so there is one document to price.** A batch of fewer items binds the
2231    /// slots it has no item for to the last item it does, and reads that item again; the
2232    /// price is the document's, whatever its variables, so a short batch costs what a full
2233    /// one does and nothing more.
2234    pub const ISSUE_DETAILS: &str = concat!(
2235        r#"query($id0:ID!,$id1:ID!,$id2:ID!,$id3:ID!,$id4:ID!,$id5:ID!,$id6:ID!,$id7:ID!,$id8:ID!,$id9:ID!,$id10:ID!,$id11:ID!,$id12:ID!,$id13:ID!,$id14:ID!,$id15:ID!,$id16:ID!,$id17:ID!,$id18:ID!,$id19:ID!,$id20:ID!,$id21:ID!,$id22:ID!,$id23:ID!,$first:Int!,$comments:Boolean!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2236        relationship_events_variable!(),
2237        r#"){"#,
2238        issue_details_alias!(0),
2239        issue_details_alias!(1),
2240        issue_details_alias!(2),
2241        issue_details_alias!(3),
2242        issue_details_alias!(4),
2243        issue_details_alias!(5),
2244        issue_details_alias!(6),
2245        issue_details_alias!(7),
2246        issue_details_alias!(8),
2247        issue_details_alias!(9),
2248        issue_details_alias!(10),
2249        issue_details_alias!(11),
2250        issue_details_alias!(12),
2251        issue_details_alias!(13),
2252        issue_details_alias!(14),
2253        issue_details_alias!(15),
2254        issue_details_alias!(16),
2255        issue_details_alias!(17),
2256        issue_details_alias!(18),
2257        issue_details_alias!(19),
2258        issue_details_alias!(20),
2259        issue_details_alias!(21),
2260        issue_details_alias!(22),
2261        issue_details_alias!(23),
2262        "\n    }",
2263        board_issue!()
2264    );
2265
2266    /// One alias of [`ISSUE_COPY_DETAILS`]: the item a batch's `$id<n>` names, with the first
2267    /// page of its comments and the issues it is blocked by.
2268    macro_rules! issue_copy_details_alias {
2269        ($n:literal) => {
2270            concat!(
2271                "\n      i",
2272                stringify!($n),
2273                ":node(id:$id",
2274                stringify!($n),
2275                "){__typename ...BoardIssue ... on Issue{comments(first:$first){nodes{",
2276                issue_comment!(),
2277                "}pageInfo{hasNextPage endCursor}} blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}}}"
2278            )
2279        };
2280    }
2281
2282    /// [`ISSUE_DETAILS`] as a copy reads the tasks it carries: each item with the first page of
2283    /// its comments and its `blockedBy` — the edges a copy reads of every task next, which
2284    /// [`ISSUE`] carries and [`ISSUE_DETAILS`] does not — [`COPY_DETAIL_BATCH`](super::COPY_DETAIL_BATCH)
2285    /// at a time, so a copy of a changed task costs this read and nothing else.
2286    ///
2287    /// A document of its own rather than a widening of [`ISSUE_DETAILS`], whose batch size is
2288    /// what `task show-many` is priced by and which reads no edge.
2289    ///
2290    /// `children`, read only while `$children` holds, is which issues the issue `$project` has
2291    /// as sub-issues — each one's id and title, the page `$nestedFirst` allows — so that a
2292    /// project copy, which reads its project and every task at once, knows from this same read
2293    /// which tasks the project holds at the destination, and its orphan check is answered by it
2294    /// rather than by a listing of the project.
2295    pub const ISSUE_COPY_DETAILS: &str = concat!(
2296        r#"query($id0:ID!,$id1:ID!,$id2:ID!,$id3:ID!,$id4:ID!,$id5:ID!,$id6:ID!,$id7:ID!,$id8:ID!,$id9:ID!,$id10:ID!,$id11:ID!,$id12:ID!,$id13:ID!,$id14:ID!,$id15:ID!,$id16:ID!,$id17:ID!,$id18:ID!,$id19:ID!,$id20:ID!,$project:ID!,$children:Boolean!,$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2297        relationship_events_variable!(),
2298        r#"){"#,
2299        issue_copy_details_alias!(0),
2300        issue_copy_details_alias!(1),
2301        issue_copy_details_alias!(2),
2302        issue_copy_details_alias!(3),
2303        issue_copy_details_alias!(4),
2304        issue_copy_details_alias!(5),
2305        issue_copy_details_alias!(6),
2306        issue_copy_details_alias!(7),
2307        issue_copy_details_alias!(8),
2308        issue_copy_details_alias!(9),
2309        issue_copy_details_alias!(10),
2310        issue_copy_details_alias!(11),
2311        issue_copy_details_alias!(12),
2312        issue_copy_details_alias!(13),
2313        issue_copy_details_alias!(14),
2314        issue_copy_details_alias!(15),
2315        issue_copy_details_alias!(16),
2316        issue_copy_details_alias!(17),
2317        issue_copy_details_alias!(18),
2318        issue_copy_details_alias!(19),
2319        issue_copy_details_alias!(20),
2320        "\n      children:node(id:$project) @include(if:$children){... on Issue{id subIssues(first:$nestedFirst){nodes{id title} pageInfo{hasNextPage}}}}",
2321        "\n    }",
2322        board_issue!(),
2323        related_issue!()
2324    );
2325
2326    /// Which issue one comment is on, read before that comment is edited or removed.
2327    ///
2328    /// GitHub's comment mutations take the comment's id and nothing else, so without this a
2329    /// comment id given against the wrong task would change a comment on another issue.
2330    pub const COMMENT_ISSUE: &str =
2331        r#"query($id:ID!){node(id:$id){__typename ... on IssueComment{id body issue{id}}}}"#;
2332    /// Adds one comment to an issue, signed as the account the token belongs to.
2333    pub const ADD_COMMENT: &str = concat!(
2334        r#"mutation($input:AddCommentInput!){addComment(input:$input){subject{id} commentEdge{node{"#,
2335        issue_comment!(),
2336        r#"}}}}"#
2337    );
2338    /// Replaces the body of one issue comment.
2339    pub const UPDATE_COMMENT: &str = concat!(
2340        r#"mutation($input:UpdateIssueCommentInput!){updateIssueComment(input:$input){issueComment{"#,
2341        issue_comment!(),
2342        r#"}}}"#
2343    );
2344    /// Removes one issue comment. Its payload carries nothing about the comment it removed.
2345    pub const DELETE_COMMENT: &str = r#"mutation($input:DeleteIssueCommentInput!){deleteIssueComment(input:$input){clientMutationId}}"#;
2346
2347    /// The variables of the search slots `<n>` of [`SEARCH_BATCH`]: its search, where it
2348    /// resumes, its page size and whether it is asked.
2349    macro_rules! search_batch_variables {
2350        ($($n:literal)+) => {
2351            concat!($(
2352                ",$search", stringify!($n), ":String!,$after", stringify!($n),
2353                ":String,$first", stringify!($n), ":Int!,$ask", stringify!($n), ":Boolean!",
2354            )+)
2355        };
2356    }
2357    /// The search slots `<n>` of [`SEARCH_BATCH`]: [`SEARCH_ISSUES`]'s one connection, aliased
2358    /// `s<n>`, sent only while `$ask<n>` holds.
2359    macro_rules! search_batch_slots {
2360        ($($n:literal)+) => {
2361            concat!($(
2362                "\n      s", stringify!($n), ":search(query:$search", stringify!($n),
2363                ",type:$type,first:$first", stringify!($n), ",after:$after", stringify!($n),
2364                ") @include(if:$ask", stringify!($n),
2365                "){pageInfo{hasNextPage endCursor} nodes{__typename ...BoardIssue}}",
2366            )+)
2367        };
2368    }
2369    /// The variables of the origin slots `<n>` of [`SEARCH_BATCH`]: the board's field filter
2370    /// naming the origin, where its items resume, their page size and whether it is asked.
2371    macro_rules! origin_batch_variables {
2372        ($($n:literal)+) => {
2373            concat!($(
2374                ",$filter", stringify!($n), ":String!,$itemsAfter", stringify!($n),
2375                ":String,$itemsFirst", stringify!($n), ":Int!,$origin", stringify!($n),
2376                ":Boolean!",
2377            )+)
2378        };
2379    }
2380    /// The origin slots `<n>` of [`SEARCH_BATCH`]: [`ORIGIN_LOOKUP`]'s board half, the board's
2381    /// own items through its field filter, aliased `o<n>`, sent only while `$origin<n>` holds.
2382    macro_rules! origin_batch_slots {
2383        ($($n:literal)+) => {
2384            concat!($(
2385                "\n      o", stringify!($n), ":repositoryOwner(login:$owner) @include(if:$origin",
2386                stringify!($n),
2387                "){... on ProjectV2Owner{projectV2(number:$number){items(first:$itemsFirst",
2388                stringify!($n), ",after:$itemsAfter", stringify!($n), ",query:$filter",
2389                stringify!($n), "){nodes{id updatedAt ", board_item_values!(),
2390                board_item_content!(), "} pageInfo{hasNextPage endCursor}}}}}",
2391            )+)
2392        };
2393    }
2394
2395    /// Up to [`SEARCH_BATCH`](super::SEARCH_BATCH) board-scoped issue searches in one request,
2396    /// each [`SEARCH_ISSUES`]'s connection in an aliased `s<n>` field with its own query, page
2397    /// size and cursor, and beside them up to
2398    /// [`SEARCH_BATCH_ORIGINS`](super::SEARCH_BATCH_ORIGINS) origin lookups' board halves —
2399    /// [`ORIGIN_LOOKUP`]'s `items` filtered by the origin field — in aliased `o<n>` fields, each
2400    /// origin's issue search in a search slot of its own.
2401    ///
2402    /// What `task find` asks a board, every search a page at a time: one request a round,
2403    /// rather than one per search. A slot not asked is left out by `@include`, its page size
2404    /// bound to one; GitHub answers an error about one slot at that slot's path, and the other
2405    /// slots are answered beside it.
2406    pub const SEARCH_BATCH: &str = concat!(
2407        r#"query($owner:String!,$number:Int!,$type:SearchType!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2408        relationship_events_variable!(),
2409        search_batch_variables!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19),
2410        origin_batch_variables!(0 1 2 3 4),
2411        "){",
2412        search_batch_slots!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19),
2413        origin_batch_slots!(0 1 2 3 4),
2414        "\n    }",
2415        board_issue!()
2416    );
2417
2418    /// The comment slots `<n>` of [`ADD_COMMENTS`]: [`ADD_COMMENT`]'s mutation, aliased
2419    /// `comment<n>`, sent only while `$send<n>` holds.
2420    macro_rules! comment_slots {
2421        ($($n:literal)+) => {
2422            concat!($(
2423                " comment", stringify!($n), ":addComment(input:$comment", stringify!($n),
2424                ") @include(if:$send", stringify!($n), "){subject{id} commentEdge{node{",
2425                issue_comment!(), "}}}",
2426            )+)
2427        };
2428    }
2429
2430    /// Adds up to [`COMMENT_BATCH`](super::COMMENT_BATCH) comments in one request, each as
2431    /// [`ADD_COMMENT`] adds one, in order: what `task comment add-many` sends. GitHub runs each
2432    /// alias on its own and answers one it refused at its own path, beside the others.
2433    pub const ADD_COMMENTS: &str = concat!(
2434        "mutation(",
2435        wide_variables!("comment", "AddCommentInput", "send"; 0 1 2 3 4 5 6 7 8 9 10),
2436        "){",
2437        comment_slots!(0 1 2 3 4 5 6 7 8 9 10),
2438        "}"
2439    );
2440
2441    /// Many tasks' targeted updates, each as [`UPDATE_FIELDS`] and [`UPDATE_ISSUE`] write one:
2442    /// up to [`TASK_FIELD_BATCH`](super::TASK_FIELD_BATCH) board field values in `field<n>`,
2443    /// [`MUTATION_BATCH`](super::MUTATION_BATCH) field clears in `clear<n>`, and as many
2444    /// `updateIssue`s in `update<n>`, each sent only while its own `send…<n>` holds.
2445    ///
2446    /// What `task update-many` sends, in two requests at most: every item's field values and
2447    /// clears first, then every issue update of an item whose fields all landed — the order one
2448    /// item's update keeps, so a refusal part way leaves an item's body as it stood.
2449    ///
2450    /// Each `update<n>` selects the issue it updated as a read of it does, so its response spells
2451    /// the change token the task holds after its batch's writes — the version `update-many`
2452    /// answers — with no read after them. Its page sizes are bound by `$nestedFirst` and
2453    /// `$boardItems`, as every read's are.
2454    pub const WRITE_TASKS: &str = concat!(
2455        "mutation(",
2456        wide_variables!("field", "UpdateProjectV2ItemFieldValueInput", "sendField"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2457        wide_variables!("clear", "ClearProjectV2ItemFieldValueInput", "sendClear"; 0 1 2 3 4 5 6 7 8 9 10),
2458        wide_variables!("update", "UpdateIssueInput", "sendUpdate"; 0 1 2 3 4 5 6 7 8 9 10),
2459        r#"$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2460        relationship_events_variable!(),
2461        "){",
2462        wide_slots!("field", "updateProjectV2ItemFieldValue", "projectV2Item{id}", "sendField"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2463        wide_slots!("clear", "clearProjectV2ItemFieldValue", "projectV2Item{id}", "sendClear"; 0 1 2 3 4 5 6 7 8 9 10),
2464        wide_slots!("update", "updateIssue", "issue{id ...BoardIssue}", "sendUpdate"; 0 1 2 3 4 5 6 7 8 9 10),
2465        "}",
2466        board_issue!()
2467    );
2468
2469    /// One alias of [`ISSUE_RELATIONS`]: the item a batch's `$id<n>` names, as a read of it by
2470    /// its own id reads it, with a page of its sub-issues' ids.
2471    macro_rules! issue_relations_alias {
2472        ($n:literal) => {
2473            concat!(
2474                "\n      i",
2475                stringify!($n),
2476                ":node(id:$id",
2477                stringify!($n),
2478                "){__typename ...BoardIssue ... on Issue{subIssues(first:$first){nodes{id}pageInfo{hasNextPage}}}}"
2479            )
2480        };
2481    }
2482
2483    /// [`ISSUE_DETAILS`] with each issue's sub-issues in place of its comments: what `task
2484    /// relations` and a link write read of [`DETAIL_BATCH`](super::DETAIL_BATCH) tasks at once
2485    /// on a source reading sub-issues as children — each task whole, its parent and the ids of up
2486    /// to `$first` of its children.
2487    pub const ISSUE_RELATIONS: &str = concat!(
2488        r#"query($id0:ID!,$id1:ID!,$id2:ID!,$id3:ID!,$id4:ID!,$id5:ID!,$id6:ID!,$id7:ID!,$id8:ID!,$id9:ID!,$id10:ID!,$id11:ID!,$id12:ID!,$id13:ID!,$id14:ID!,$id15:ID!,$id16:ID!,$id17:ID!,$id18:ID!,$id19:ID!,$id20:ID!,$id21:ID!,$id22:ID!,$id23:ID!,$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2489        relationship_events_variable!(),
2490        r#"){"#,
2491        issue_relations_alias!(0),
2492        issue_relations_alias!(1),
2493        issue_relations_alias!(2),
2494        issue_relations_alias!(3),
2495        issue_relations_alias!(4),
2496        issue_relations_alias!(5),
2497        issue_relations_alias!(6),
2498        issue_relations_alias!(7),
2499        issue_relations_alias!(8),
2500        issue_relations_alias!(9),
2501        issue_relations_alias!(10),
2502        issue_relations_alias!(11),
2503        issue_relations_alias!(12),
2504        issue_relations_alias!(13),
2505        issue_relations_alias!(14),
2506        issue_relations_alias!(15),
2507        issue_relations_alias!(16),
2508        issue_relations_alias!(17),
2509        issue_relations_alias!(18),
2510        issue_relations_alias!(19),
2511        issue_relations_alias!(20),
2512        issue_relations_alias!(21),
2513        issue_relations_alias!(22),
2514        issue_relations_alias!(23),
2515        "\n    }",
2516        board_issue!()
2517    );
2518
2519    /// Up to [`RELATION_BATCH`](super::RELATION_BATCH) parent writes in one request:
2520    /// `parent<n>` an `addSubIssue` (a re-parent carrying `replaceParent: true`) and `unparent<n>`
2521    /// a `removeSubIssue`, each sent only while its own `send…<n>` holds. GitHub runs each alias
2522    /// on its own and answers one it refused — a cycle, a depth or children limit — at its own
2523    /// path, beside the others.
2524    pub const SET_PARENTS: &str = concat!(
2525        "mutation(",
2526        wide_variables!("parent", "AddSubIssueInput", "sendParent"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2527        wide_variables!("unparent", "RemoveSubIssueInput", "sendUnparent"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2528        "){",
2529        wide_slots!("parent", "addSubIssue", "issue{id} subIssue{id}", "sendParent"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2530        wide_slots!("unparent", "removeSubIssue", "issue{id} subIssue{id}", "sendUnparent"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2531        "}"
2532    );
2533
2534    /// Up to [`RELATION_BATCH`](super::RELATION_BATCH) `relates-to` relations added in one
2535    /// request, each `relate<n>` sent only while `$send<n>` holds: what a link of a type a
2536    /// source mirrors natively writes beside its metadata.
2537    pub const ADD_RELATES_TO: &str = concat!(
2538        "mutation(",
2539        wide_variables!("relate", "AddRelatesToInput", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2540        "){",
2541        wide_slots!("relate", "addRelatesTo", "issue{id} relatedIssue{id}", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2542        "}"
2543    );
2544
2545    /// [`ADD_RELATES_TO`]'s removal: up to [`RELATION_BATCH`](super::RELATION_BATCH)
2546    /// `relates-to` relations removed in one request.
2547    pub const REMOVE_RELATES_TO: &str = concat!(
2548        "mutation(",
2549        wide_variables!("unrelate", "RemoveRelatesToInput", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2550        "){",
2551        wide_slots!("unrelate", "removeRelatesTo", "issue{id} relatedIssue{id}", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2552        "}"
2553    );
2554
2555    /// One alias of [`RELATES_TO_READS`]: the issue `$id<n>` names and the ids of up to
2556    /// `$first` of the issues it relates to.
2557    macro_rules! relates_to_alias {
2558        ($n:literal) => {
2559            concat!(
2560                "\n      r",
2561                stringify!($n),
2562                ":node(id:$id",
2563                stringify!($n),
2564                "){... on Issue{id relatesTo(first:$first){nodes{id}pageInfo{hasNextPage}}}}"
2565            )
2566        };
2567    }
2568
2569    /// What [`DETAIL_BATCH`](super::DETAIL_BATCH) issues relate to, one alias each: read
2570    /// after a relation write whose answer never arrived, so each relation is answered from what
2571    /// GitHub holds rather than sent again blindly.
2572    pub const RELATES_TO_READS: &str = concat!(
2573        r#"query($id0:ID!,$id1:ID!,$id2:ID!,$id3:ID!,$id4:ID!,$id5:ID!,$id6:ID!,$id7:ID!,$id8:ID!,$id9:ID!,$id10:ID!,$id11:ID!,$id12:ID!,$id13:ID!,$id14:ID!,$id15:ID!,$id16:ID!,$id17:ID!,$id18:ID!,$id19:ID!,$id20:ID!,$id21:ID!,$id22:ID!,$id23:ID!,$first:Int!){"#,
2574        relates_to_alias!(0),
2575        relates_to_alias!(1),
2576        relates_to_alias!(2),
2577        relates_to_alias!(3),
2578        relates_to_alias!(4),
2579        relates_to_alias!(5),
2580        relates_to_alias!(6),
2581        relates_to_alias!(7),
2582        relates_to_alias!(8),
2583        relates_to_alias!(9),
2584        relates_to_alias!(10),
2585        relates_to_alias!(11),
2586        relates_to_alias!(12),
2587        relates_to_alias!(13),
2588        relates_to_alias!(14),
2589        relates_to_alias!(15),
2590        relates_to_alias!(16),
2591        relates_to_alias!(17),
2592        relates_to_alias!(18),
2593        relates_to_alias!(19),
2594        relates_to_alias!(20),
2595        relates_to_alias!(21),
2596        relates_to_alias!(22),
2597        relates_to_alias!(23),
2598        "\n    }"
2599    );
2600
2601    /// What a mutation of a write the store's cache expects selects of the issue it wrote:
2602    /// everything [`ISSUE_DETAIL`] reads of it, so its response shows the task whole — its
2603    /// change token's every part and the first page of its comments.
2604    ///
2605    /// Sent **only** while that write runs, in place of the document named beside each
2606    /// below, so every other write's documents, prices and request counts are what they
2607    /// were. GitHub's token waits for a task to settle (`change_token::SETTLED`), and a
2608    /// mutation's response is stamped seconds after the change it made, so against GitHub
2609    /// itself a response rarely determines a version; the cache is then left unserveable
2610    /// for the task, and its next read refreshes it.
2611    macro_rules! whole_issue {
2612        () => {
2613            concat!(
2614                r#"__typename ...BoardIssue ... on Issue{comments(first:$first){nodes{"#,
2615                issue_comment!(),
2616                r#"}pageInfo{hasNextPage endCursor}}}"#
2617            )
2618        };
2619    }
2620
2621    /// The variables every document of `whole_issue!` declares beside its own.
2622    macro_rules! whole_variables {
2623        () => {
2624            concat!(
2625                r#",$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2626                relationship_events_variable!()
2627            )
2628        };
2629    }
2630
2631    /// [`ADD_COMMENT`], selecting the whole issue commented on.
2632    pub const ADD_COMMENT_WHOLE: &str = concat!(
2633        r#"mutation($input:AddCommentInput!"#,
2634        whole_variables!(),
2635        r#"){addComment(input:$input){subject{id "#,
2636        whole_issue!(),
2637        r#"} commentEdge{node{"#,
2638        issue_comment!(),
2639        r#"}}}}"#,
2640        board_issue!()
2641    );
2642    /// [`UPDATE_COMMENT`], selecting the whole issue the comment is on.
2643    pub const UPDATE_COMMENT_WHOLE: &str = concat!(
2644        r#"mutation($input:UpdateIssueCommentInput!"#,
2645        whole_variables!(),
2646        r#"){updateIssueComment(input:$input){issueComment{"#,
2647        issue_comment!(),
2648        r#" issue{"#,
2649        whole_issue!(),
2650        r#"}}}}"#,
2651        board_issue!()
2652    );
2653    /// [`UPDATE_ISSUE`], selecting the whole issue updated.
2654    pub const UPDATE_ISSUE_WHOLE: &str = concat!(
2655        r#"mutation($input:UpdateIssueInput!"#,
2656        whole_variables!(),
2657        r#"){updateIssue(input:$input){issue{id "#,
2658        whole_issue!(),
2659        r#"}}}"#,
2660        board_issue!()
2661    );
2662    /// [`UPDATE_FIELD`], selecting the whole issue behind the board item written.
2663    pub const UPDATE_FIELD_WHOLE: &str = concat!(
2664        r#"mutation($input:UpdateProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
2665        whole_variables!(),
2666        r#"){updateProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{"#,
2667        whole_issue!(),
2668        r#"}}}}"#,
2669        board_issue!()
2670    );
2671    /// [`CLEAR_FIELD`], selecting the whole issue behind the board item cleared.
2672    pub const CLEAR_FIELD_WHOLE: &str = concat!(
2673        r#"mutation($input:ClearProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
2674        whole_variables!(),
2675        r#"){clearProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{"#,
2676        whole_issue!(),
2677        r#"}}}}"#,
2678        board_issue!()
2679    );
2680
2681    /// The variables every document selecting [`board_issue_fields!`] inline declares beside
2682    /// its own.
2683    macro_rules! token_variables {
2684        () => {
2685            concat!(
2686                r#",$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2687                relationship_events_variable!()
2688            )
2689        };
2690    }
2691
2692    /// [`UPDATE_ISSUE`], selecting what a read of the issue updated selects — every part of its
2693    /// change token, and no comment — inline, so its root fields are the plain document's.
2694    ///
2695    /// What a targeted update sends in the plain document's place, so the version it answers
2696    /// is the one its own last response spells (`GitHubProjectsSource::written_tokens`). It
2697    /// costs the one point the plain document does.
2698    pub const UPDATE_ISSUE_TOKEN: &str = concat!(
2699        r#"mutation($input:UpdateIssueInput!"#,
2700        token_variables!(),
2701        r#"){updateIssue(input:$input){issue{"#,
2702        board_issue_fields!(),
2703        r#"}}}"#
2704    );
2705    /// [`UPDATE_FIELD`], selecting the issue behind the board item written as
2706    /// [`UPDATE_ISSUE_TOKEN`] selects the issue it updates.
2707    pub const UPDATE_FIELD_TOKEN: &str = concat!(
2708        r#"mutation($input:UpdateProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
2709        token_variables!(),
2710        r#"){updateProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{... on Issue{"#,
2711        board_issue_fields!(),
2712        r#"}}}}}"#
2713    );
2714    /// [`CLEAR_FIELD`], selecting the issue behind the board item cleared as
2715    /// [`UPDATE_ISSUE_TOKEN`] selects the issue it updates.
2716    pub const CLEAR_FIELD_TOKEN: &str = concat!(
2717        r#"mutation($input:ClearProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
2718        token_variables!(),
2719        r#"){clearProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{... on Issue{"#,
2720        board_issue_fields!(),
2721        r#"}}}}}"#
2722    );
2723
2724    /// The document a targeted update sends in `document`'s place, when it has one: the twin
2725    /// whose answer spells the change token of the issue written.
2726    #[must_use]
2727    pub fn token_twin(document: &str) -> Option<&'static str> {
2728        [
2729            (UPDATE_ISSUE, UPDATE_ISSUE_TOKEN),
2730            (UPDATE_FIELD, UPDATE_FIELD_TOKEN),
2731            (CLEAR_FIELD, CLEAR_FIELD_TOKEN),
2732        ]
2733        .into_iter()
2734        .find(|(plain, _)| *plain == document)
2735        .map(|(_, token)| token)
2736    }
2737
2738    /// The document sent in `document`'s place while a write the store's cache expects runs,
2739    /// when it has one.
2740    #[must_use]
2741    pub fn whole_twin(document: &str) -> Option<&'static str> {
2742        [
2743            (ADD_COMMENT, ADD_COMMENT_WHOLE),
2744            (UPDATE_COMMENT, UPDATE_COMMENT_WHOLE),
2745            (UPDATE_ISSUE, UPDATE_ISSUE_WHOLE),
2746            (UPDATE_FIELD, UPDATE_FIELD_WHOLE),
2747            (CLEAR_FIELD, CLEAR_FIELD_WHOLE),
2748        ]
2749        .into_iter()
2750        .find(|(plain, _)| *plain == document)
2751        .map(|(_, whole)| whole)
2752    }
2753
2754    /// The node id of one person by their login, as the aliased field `u0` answering `$login0`:
2755    /// what an assignee write names a person by, since `assigneeIds` takes node ids and a person
2756    /// is named by login.
2757    ///
2758    /// The inventoried form of the lookup. What is sent is this document sized to the call
2759    /// ([`user_ids`]): one `u<n>:user(login:$login<n>)` field per person the call names that
2760    /// this process has not resolved, so one request answers every one of them. GitHub answers a
2761    /// login it does not know with `null` at that alias beside a `NOT_FOUND` error naming it,
2762    /// and the others' ids beside them.
2763    pub const USER_IDS: &str = "query($login0:String!){ u0:user(login:$login0){id login}}";
2764
2765    /// [`USER_IDS`] for `people` logins — `$login0` to `$login<people - 1>`, each answered at
2766    /// its own alias — and [`USER_IDS`] itself for one.
2767    #[must_use]
2768    pub fn user_ids(people: usize) -> String {
2769        let people = people.max(1);
2770        let declared: Vec<String> = (0..people)
2771            .map(|slot| format!("$login{slot}:String!"))
2772            .collect();
2773        let fields: Vec<String> = (0..people)
2774            .map(|slot| format!("u{slot}:user(login:$login{slot}){{id login}}"))
2775            .collect();
2776        format!("query({}){{ {}}}", declared.join(","), fields.join(" "))
2777    }
2778
2779    /// The document a request sending `document` with `variables` really sends: [`USER_IDS`]
2780    /// sized to the logins `variables` binds, and every other document as it is.
2781    #[must_use]
2782    pub fn sized<'a>(
2783        document: &'a str,
2784        variables: &serde_json::Value,
2785    ) -> std::borrow::Cow<'a, str> {
2786        if document != USER_IDS {
2787            return std::borrow::Cow::Borrowed(document);
2788        }
2789        let people = (0..)
2790            .take_while(|slot| variables.get(format!("login{slot}")).is_some())
2791            .count();
2792        std::borrow::Cow::Owned(user_ids(people))
2793    }
2794
2795    /// The inventoried document `document` is an instance of: [`USER_IDS`] for any lookup
2796    /// [`user_ids`] sized, and `document` itself otherwise.
2797    #[must_use]
2798    pub fn inventoried(document: &str) -> &str {
2799        let people = document.matches(":user(login:$login").count();
2800        if people > 0 && user_ids(people) == document {
2801            USER_IDS
2802        } else {
2803            document
2804        }
2805    }
2806
2807    /// The selection of an issue's — or a draft's — assignees, as a source opted in to them
2808    /// (`config.assignees: true`) adds it to every document that reads one; see
2809    /// [`with_assignees`].
2810    const ASSIGNEES: &str = " assignees(first:$assigneeFirst){nodes{id login}}";
2811    /// The variable [`ASSIGNEES`] pages by, declared with its value as its default — the most
2812    /// people GitHub assigns one issue — so no caller binds it, and inserted first among a
2813    /// document's variables.
2814    const ASSIGNEE_VARIABLE: &str = "$assigneeFirst:Int!=10 ";
2815    /// [`ASSIGNEE_VARIABLE`] for a document declaring no variables of its own.
2816    const ASSIGNEE_VARIABLES: &str = "($assigneeFirst:Int!=10)";
2817    /// Where [`ASSIGNEES`] goes: straight after each of these, wherever an issue or a draft is
2818    /// read — what every read of an issue selects of it — and inside the answer of each
2819    /// `createIssue` and `updateIssue`, so a write's own answer says whom GitHub assigned.
2820    const ASSIGNEE_MARKERS: [&str; 2] = [
2821        "commentCount:comments{totalCount}",
2822        "title body createdAt updatedAt",
2823    ];
2824
2825    /// `document` as a source opted in to assignees sends it: [`ASSIGNEES`] selected wherever
2826    /// it reads an issue or a draft and in every `createIssue` and `updateIssue` answer, with the
2827    /// variable it pages by declared — or `None` when it reads and writes neither, and is sent
2828    /// as written.
2829    ///
2830    /// A rewrite of the one text sent rather than a second set of documents, so a source that
2831    /// has not opted in sends every document byte for byte as it did, and an opted-in one rides
2832    /// its assignees on the very reads and writes it already makes. [`without_assignees`] is its
2833    /// exact inverse, which the loopback board answers a document by.
2834    #[must_use]
2835    pub fn with_assignees(document: &str) -> Option<String> {
2836        let mut spelled = String::with_capacity(document.len() + 256);
2837        let mut inserted = false;
2838        let mut rest = document;
2839        while !rest.is_empty() {
2840            // The earliest place one is due, of every kind.
2841            let next = ASSIGNEE_MARKERS
2842                .iter()
2843                .filter_map(|marker| rest.find(marker).map(|at| (at + marker.len(), true)))
2844                .chain(["createIssue(", "updateIssue("].iter().filter_map(|write| {
2845                    let at = rest.find(write)?;
2846                    let open = at + rest[at..].find('{')?;
2847                    rest[open..]
2848                        .starts_with("{issue{id")
2849                        .then_some((open + "{issue{id".len(), true))
2850                        .or(Some((open, false)))
2851                }))
2852                .min_by_key(|(at, _)| *at);
2853            let Some((at, insert)) = next else {
2854                spelled.push_str(rest);
2855                break;
2856            };
2857            spelled.push_str(&rest[..at]);
2858            if insert {
2859                spelled.push_str(ASSIGNEES);
2860                inserted = true;
2861            }
2862            rest = &rest[at..];
2863            if !insert {
2864                // A write whose answer reads no issue's id first: past its opening brace.
2865                spelled.push('{');
2866                rest = &rest[1..];
2867            }
2868        }
2869        if !inserted {
2870            return None;
2871        }
2872        let open = spelled.find('(');
2873        let body = spelled.find('{');
2874        Some(match (open, body) {
2875            (Some(open), Some(body)) if open < body => {
2876                format!(
2877                    "{}{ASSIGNEE_VARIABLE}{}",
2878                    &spelled[..=open],
2879                    &spelled[open + 1..]
2880                )
2881            }
2882            (_, Some(body)) => format!(
2883                "{}{ASSIGNEE_VARIABLES}{}",
2884                &spelled[..body],
2885                &spelled[body..]
2886            ),
2887            _ => return None,
2888        })
2889    }
2890
2891    /// `document` as [`with_assignees`] spelled it, back as the document it was written as — or
2892    /// `None` for a document it did not rewrite.
2893    #[must_use]
2894    pub fn without_assignees(document: &str) -> Option<String> {
2895        if !document.contains(ASSIGNEES) {
2896            return None;
2897        }
2898        let plain = document.replace(ASSIGNEES, "");
2899        Some(if plain.contains(ASSIGNEE_VARIABLES) {
2900            plain.replacen(ASSIGNEE_VARIABLES, "", 1)
2901        } else {
2902            plain.replacen(ASSIGNEE_VARIABLE, "", 1)
2903        })
2904    }
2905
2906    /// Every document above, with what this source is doing when it sends one.
2907    ///
2908    /// One list rather than a `match` beside the constants: a rate-limit diagnostic has to
2909    /// name the call that was refused, and a `match` with a catch-all arm would answer a
2910    /// document added later with "talking to GitHub" and never say so.
2911    ///
2912    /// `documents_are_all_inventoried` reads this file back and fails naming any `pub
2913    /// const` here that this list omits, so the two cannot part — which is the same guard
2914    /// `CATEGORIES` carries, in the one shape available to a set of `&str` constants.
2915    pub const DOCUMENTS: [(&str, &str); 71] = [
2916        (USER_IDS, "looking up the people an assignee write names"),
2917        (
2918            ISSUE_RELATIONS,
2919            "reading several issues with their parents and sub-issues",
2920        ),
2921        (SET_PARENTS, "writing several issues' parents"),
2922        (ADD_RELATES_TO, "adding several relates-to relations"),
2923        (REMOVE_RELATES_TO, "removing several relates-to relations"),
2924        (
2925            RELATES_TO_READS,
2926            "reading what several issues relate to after a relation write went unanswered",
2927        ),
2928        (
2929            ISSUES_BY_CREATION,
2930            "listing a repository's issues newest first for a create key",
2931        ),
2932        (SEARCH_ISSUES, "searching this board's issues"),
2933        (ISSUE, "reading one issue"),
2934        (
2935            DOCUMENT_IN_PROJECT,
2936            "reading one document with its project and the project's members",
2937        ),
2938        (
2939            ISSUE_BOARD_ITEMS,
2940            "reading one issue's board memberships past the page it came with",
2941        ),
2942        (SUB_ISSUES, "reading a project's tasks"),
2943        (BOARD, "reading the board"),
2944        (
2945            BOARD_WITH_COMMENTS,
2946            "reading a board page with first comments",
2947        ),
2948        (ORIGIN_LOOKUP, "looking up the items copied from one origin"),
2949        (CLOSED_ITEMS, "reading the board's closed items"),
2950        (OPEN_ITEMS, "reading the board's open items"),
2951        (CLOSE_ISSUE, "closing an issue as a duplicate"),
2952        (
2953            ISSUES_BY_REFERENCE,
2954            "reading a batch of issues by their references",
2955        ),
2956        (BOARD_FIELDS, "reading the board's fields"),
2957        (DRAFT, "reading one draft"),
2958        (REPOSITORY, "reading the destination repository"),
2959        (
2960            PROJECT_VISIBILITY,
2961            "reading whether the board's project is public",
2962        ),
2963        (
2964            CREATION_CONTEXT,
2965            "reading the board's fields and the destination repository",
2966        ),
2967        (ISSUE_DEPENDENCIES, "reading an issue's dependencies"),
2968        (ISSUE_DEPENDS_ON, "reading what an item depends on"),
2969        (ISSUE_DEPENDED_ON_BY, "reading what depends on an issue"),
2970        (CREATE_ISSUE, "creating an issue"),
2971        (
2972            ORIGIN_LOOKUPS,
2973            "looking up the items copied from several origins, and what creating one reads",
2974        ),
2975        (
2976            ORIGIN_LOOKUPS_WITH_MEMBERS,
2977            "looking up the items copied from several origins, with a project's members",
2978        ),
2979        (CREATE_ISSUES, "creating several issues together"),
2980        (
2981            CREATED_BOARD_ITEMS,
2982            "reading the board items of the issues a copy created",
2983        ),
2984        (
2985            WRITE_FIELD_VALUES,
2986            "writing board fields of the items a copy created",
2987        ),
2988        (
2989            WRITE_FIELDS_AND_EDGES,
2990            "writing board fields and dependencies of the items a copy created",
2991        ),
2992        (CLOSE_ISSUES, "closing the issues a copy created"),
2993        (UPDATE_ISSUES, "updating several issues together"),
2994        (ADD_BLOCKED_BYS, "recording several dependencies together"),
2995        (ADD_TO_BOARD, "adding an issue to the board"),
2996        (UPDATE_ISSUE, "updating an issue"),
2997        (UPDATE_DRAFT, "updating a draft item"),
2998        (UPDATE_FIELD, "writing a board field"),
2999        (UPDATE_FIELDS, "writing board fields together"),
3000        (CLEAR_FIELD, "clearing a board field"),
3001        (
3002            CREATE_FIELD,
3003            "creating a board single-select field with its options",
3004        ),
3005        (
3006            STATUS_OPTIONS_SNAPSHOT,
3007            "snapshotting board Status options and assignments",
3008        ),
3009        (
3010            STATUS_OPTIONS_UPDATE,
3011            "safely replacing the board Status option list",
3012        ),
3013        (ADD_SUB_ISSUE, "filing an issue under its project"),
3014        (REMOVE_SUB_ISSUE, "taking an issue out of its project"),
3015        (ADD_BLOCKED_BY, "recording a dependency"),
3016        (REMOVE_BLOCKED_BY, "removing a dependency"),
3017        (DELETE_ISSUE, "deleting an issue"),
3018        (DELETE_ISSUES, "deleting several issues together"),
3019        (ISSUE_COMMENTS, "reading a task's comments"),
3020        (ISSUE_DETAIL, "reading one issue with its comments"),
3021        (
3022            ISSUE_DETAILS,
3023            "reading a batch of issues with their comments",
3024        ),
3025        (
3026            ISSUE_COPY_DETAILS,
3027            "reading a batch of issues with their comments and dependencies for a copy",
3028        ),
3029        (COMMENT_ISSUE, "reading which issue a comment is on"),
3030        (ADD_COMMENT, "adding a comment"),
3031        (UPDATE_COMMENT, "editing a comment"),
3032        (DELETE_COMMENT, "deleting a comment"),
3033        (
3034            SEARCH_BATCH,
3035            "searching this board's issues several ways at once",
3036        ),
3037        (ADD_COMMENTS, "adding several comments together"),
3038        (WRITE_TASKS, "updating several tasks together"),
3039        (
3040            ADD_COMMENT_WHOLE,
3041            "adding a comment, answered with the whole issue",
3042        ),
3043        (
3044            UPDATE_COMMENT_WHOLE,
3045            "editing a comment, answered with the whole issue",
3046        ),
3047        (
3048            UPDATE_ISSUE_WHOLE,
3049            "updating an issue, answered with it whole",
3050        ),
3051        (
3052            UPDATE_FIELD_WHOLE,
3053            "writing a board field, answered with the whole issue",
3054        ),
3055        (
3056            CLEAR_FIELD_WHOLE,
3057            "clearing a board field, answered with the whole issue",
3058        ),
3059        (
3060            UPDATE_ISSUE_TOKEN,
3061            "updating an issue, answered with its version",
3062        ),
3063        (
3064            UPDATE_FIELD_TOKEN,
3065            "writing a board field, answered with the issue's version",
3066        ),
3067        (
3068            CLEAR_FIELD_TOKEN,
3069            "clearing a board field, answered with the issue's version",
3070        ),
3071    ];
3072}
3073
3074/// One aliased mutation field of [`graphql::UPDATE_FIELDS`]: the key its answer comes back
3075/// under, the variable carrying its input, and the boolean variable that includes it.
3076#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3077pub struct FieldSlot {
3078    /// The key of the answer's `data` this field's payload is under.
3079    pub alias: &'static str,
3080    /// The variable carrying this field's input.
3081    pub variable: &'static str,
3082    /// The boolean variable whose `true` sends this field.
3083    pub include: &'static str,
3084}
3085
3086/// The value writes [`graphql::UPDATE_FIELDS`] carries, in the order GitHub runs them.
3087pub const FIELD_WRITE_SLOTS: [FieldSlot; 6] = [
3088    FieldSlot {
3089        alias: "updateProjectV2ItemFieldValue",
3090        variable: "input",
3091        include: "writeFirst",
3092    },
3093    FieldSlot {
3094        alias: "second",
3095        variable: "second",
3096        include: "writeSecond",
3097    },
3098    FieldSlot {
3099        alias: "third",
3100        variable: "third",
3101        include: "writeThird",
3102    },
3103    FieldSlot {
3104        alias: "fourth",
3105        variable: "fourth",
3106        include: "writeFourth",
3107    },
3108    FieldSlot {
3109        alias: "fifth",
3110        variable: "fifth",
3111        include: "writeFifth",
3112    },
3113    FieldSlot {
3114        alias: "sixth",
3115        variable: "sixth",
3116        include: "writeSixth",
3117    },
3118];
3119
3120/// The clears [`graphql::UPDATE_FIELDS`] carries, run after every write of the same request.
3121pub const FIELD_CLEAR_SLOTS: [FieldSlot; 3] = [
3122    FieldSlot {
3123        alias: "cleared",
3124        variable: "clear",
3125        include: "writeClear",
3126    },
3127    FieldSlot {
3128        alias: "clearedSecond",
3129        variable: "clearSecond",
3130        include: "writeClearSecond",
3131    },
3132    FieldSlot {
3133        alias: "clearedThird",
3134        variable: "clearThird",
3135        include: "writeClearThird",
3136    },
3137];
3138
3139/// Which of GitHub's two rate limiters refused a request.
3140///
3141/// Waiting is the whole answer to the primary budget, and polling is what *extends* the
3142/// secondary one — so an operator told the wrong one takes the wrong next step, which is
3143/// the whole reason this is carried rather than collapsed into "rate limited".
3144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3145enum Limiter {
3146    /// The hourly API budget, which `gh api rate_limit` reports and a wait answers.
3147    Primary,
3148    /// The burst limiter over content-generating requests, which nothing reports.
3149    Secondary,
3150}
3151
3152/// The wordings GitHub answers a secondary rate limit with.
3153///
3154/// It sends them under a forbidden status, under a too-many-requests status, and inside
3155/// the `errors` of a *successful* response, which is why the text is what this matches on
3156/// rather than the status. `abuse detection` is the wording GitHub used before the
3157/// limiter was renamed and still returns from some endpoints; `submitted too quickly` is
3158/// what a burst of content creation is refused with.
3159///
3160/// This is GitHub's vocabulary rather than this source's, so it is pinned rather than
3161/// remembered: `tests/fixtures/rate-limits.json` records where each wording was read and
3162/// when, and the drift gate reconciles the two lists both ways. Public for that gate
3163/// alone — a caller has no use for it, and matching on a refusal is this source's job.
3164pub const SECONDARY_WORDINGS: [&str; 5] = [
3165    "secondary rate limit",
3166    "temporarily blocked from content creation",
3167    "abuse detection",
3168    "submitted too quickly",
3169    "exceeded a secondary",
3170];
3171
3172/// The wordings GitHub answers an exhausted primary budget with.
3173///
3174/// `rate_limited` is the `type` its GraphQL error carries, which is read as a field rather
3175/// than looked for in the response text. `api rate limit already exceeded` is what GraphQL
3176/// answers a request made once the hour's budget is spent — "API rate limit already exceeded
3177/// for user ID …" in the `errors` of an HTTP 200, with no `type` — and neither of the other
3178/// two phrases is a substring of it, so without it that answer read as a refusal that will
3179/// never lift. Pinned and gated exactly as [`SECONDARY_WORDINGS`] is, and public for the same
3180/// one reason.
3181pub const PRIMARY_WORDINGS: [&str; 4] = [
3182    "api rate limit exceeded",
3183    "api rate limit already exceeded",
3184    "rate limit exceeded",
3185    "rate_limited",
3186];
3187
3188/// The wordings GitHub answers a write that collided with another change to the same
3189/// ordering with, in the `errors` of an HTTP 200: "Your attempt to move this item created a
3190/// temporary conflict. Please try again." The write did not take effect and GitHub asks for it
3191/// again, so it is retried on the same growing schedule a rate limit without a hint is, within
3192/// the same retry budget — except a `createIssue`, whose answer cannot say the issue was not
3193/// made, and which is therefore reported rather than replayed into a duplicate.
3194///
3195/// Observed rather than documented, so it is pinned exactly as [`SECONDARY_WORDINGS`] is:
3196/// `tests/fixtures/rate-limits.json` records where it was read under `conflict.observed`, and
3197/// the same drift gate reconciles the two both ways. Public for that gate alone.
3198pub const CONFLICT_WORDINGS: [&str; 1] = ["created a temporary conflict"];
3199
3200/// What a response *says about itself*, which is the only place a refusal can be read.
3201///
3202/// Deliberately not the whole response body. A board is a place people write about their
3203/// own work, and a task on it titled "the secondary rate limit" would, matched across the
3204/// raw text, turn a perfectly good answer into a refusal this source then waited out and
3205/// reported. So the item data is never read: what is read is GitHub's own REST-style
3206/// `message` envelope, which is what a forbidden status carries, and the `message` and
3207/// `type` of each GraphQL error, which is where a *successful* response says it.
3208///
3209/// A body that is not JSON at all has nothing structured to read, so only a failing
3210/// response's own text is taken — a successful response that is not JSON is malformed
3211/// rather than refused, and [`GitHubProjectsSource::answer`] says so.
3212fn refusal_wording(status: StatusCode, body: &str) -> String {
3213    let Ok(parsed) = serde_json::from_str::<Value>(body) else {
3214        return if status.is_success() {
3215            String::new()
3216        } else {
3217            body.to_owned()
3218        };
3219    };
3220    let mut said: Vec<&str> = parsed
3221        .get("message")
3222        .and_then(Value::as_str)
3223        .into_iter()
3224        .collect();
3225    if let Some(errors) = parsed.get("errors").and_then(Value::as_array) {
3226        for error in errors {
3227            said.extend(
3228                ["message", "type"]
3229                    .into_iter()
3230                    .filter_map(|key| error.get(key).and_then(Value::as_str)),
3231            );
3232        }
3233    }
3234    said.join("; ")
3235}
3236
3237impl Limiter {
3238    /// Which limiter refused this response, or `None` when none of them did.
3239    ///
3240    /// The wording is read first and the status only decides what carries none of it,
3241    /// because GitHub answers a secondary limit with a forbidden status far more often
3242    /// than with too-many-requests — while a forbidden status saying nothing about a limit
3243    /// really is a credential this token lacks.
3244    ///
3245    /// A response is a refusal because of its status or its own wording. A spent budget
3246    /// only ever explains one; it never turns an answer into a refusal.
3247    fn classify(status: StatusCode, budget_exhausted: bool, body: &str) -> Option<Self> {
3248        let normalized = refusal_wording(status, body).to_ascii_lowercase();
3249        if SECONDARY_WORDINGS
3250            .iter()
3251            .any(|wording| normalized.contains(wording))
3252        {
3253            return Some(Self::Secondary);
3254        }
3255        if status == StatusCode::TOO_MANY_REQUESTS {
3256            return Some(Self::Primary);
3257        }
3258        // An exhausted budget *explains* a response that failed; it does not make one that
3259        // succeeded into a failure. GitHub sets `x-ratelimit-remaining: 0` on the last
3260        // request the budget allowed as well as on the ones it then refuses, so reading
3261        // the header alone threw away a good answer — and, once refusals were retried,
3262        // replayed a request that had already taken effect.
3263        if !status.is_success() && budget_exhausted {
3264            return Some(Self::Primary);
3265        }
3266        // A successful response saying it: GitHub reports a GraphQL rate limit in the
3267        // `errors` of an HTTP 200, where nothing about the status says so at all.
3268        if status.is_success()
3269            && PRIMARY_WORDINGS
3270                .iter()
3271                .any(|wording| normalized.contains(wording))
3272        {
3273            return Some(Self::Primary);
3274        }
3275        None
3276    }
3277
3278    /// What this limiter is called where an operator can look it up.
3279    const fn name(self) -> &'static str {
3280        match self {
3281            Self::Primary => "GitHub's primary API rate limit",
3282            Self::Secondary => "GitHub's secondary rate limit",
3283        }
3284    }
3285
3286    /// What the endpoint an operator would go and check says about this limiter.
3287    const fn where_to_look(self) -> &'static str {
3288        match self {
3289            Self::Primary => {
3290                "That is the budget `gh api rate_limit` reports, so that endpoint says when it \
3291                 comes back."
3292            }
3293            Self::Secondary => {
3294                "That limiter is not the primary API budget: `gh api rate_limit` reports the \
3295                 primary budget and does not report this one, so budget showing there says \
3296                 nothing about this refusal, and every further attempt extends it."
3297            }
3298        }
3299    }
3300
3301    /// The next step this limiter actually calls for.
3302    const fn what_to_do(self) -> &'static str {
3303        match self {
3304            Self::Primary => {
3305                "wait for the reset `gh api rate_limit` reports, then run the command again."
3306            }
3307            Self::Secondary => {
3308                "leave this board alone for a few minutes, then run the command again — or \
3309                 raise pacing.min_mutation_interval_ms on this source so it writes more slowly."
3310            }
3311        }
3312    }
3313}
3314
3315/// One rate-limit refusal, and the wait GitHub asked for if it asked for one.
3316#[derive(Debug, Clone, Copy)]
3317struct Limited {
3318    limiter: Limiter,
3319    hint: Option<u64>,
3320    /// Which header the hint came from: `retry-after`, or an exhausted primary budget's
3321    /// `x-ratelimit-reset`.
3322    hinted_by: Hint,
3323}
3324
3325/// Where a refusal's hint came from, which is what its wait is named after.
3326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3327enum Hint {
3328    /// `retry-after`, or no hint at all.
3329    RetryAfter,
3330    /// An exhausted primary budget's `x-ratelimit-reset`.
3331    PrimaryReset,
3332}
3333
3334impl Limited {
3335    /// The wait this refusal is answered with, when the backing-off schedule is at `backoff`,
3336    /// and the cause it is named by: the hint, raised to the schedule's own next wait —
3337    /// GitHub really does send `retry-after: 0`, and retrying at once is the one move that
3338    /// extends a secondary limit — or the schedule alone when there is none.
3339    fn wait(self, backoff: Duration) -> (Duration, WaitCause) {
3340        match (self.hint, self.hinted_by) {
3341            (Some(hint), Hint::RetryAfter) => (
3342                Duration::from_secs(hint).max(backoff),
3343                pacing::cause::RETRY_AFTER,
3344            ),
3345            (Some(hint), Hint::PrimaryReset) => (
3346                Duration::from_secs(hint).max(backoff),
3347                pacing::cause::PRIMARY_RESET,
3348            ),
3349            (None, _) => (backoff, pacing::cause::BACKOFF),
3350        }
3351    }
3352
3353    /// What the caller is told once this source has waited as long as it may.
3354    ///
3355    /// Both limiters report as [`SourceError::RateLimited`], because that is what
3356    /// happened: the kind a caller matches on says a rate limit refused this, and nothing
3357    /// about *which* limiter it was makes it a different kind of failure. What differs is
3358    /// the operator's next step, and that is what the message carries — a secondary
3359    /// refusal read as a primary one sends an operator to `gh api rate_limit`, where the
3360    /// budget looks fine, and then back to retry the very burst that was refused.
3361    fn exhausted(
3362        self,
3363        doing: &str,
3364        waits: u32,
3365        waited: Duration,
3366        needed: Duration,
3367        budget: Duration,
3368    ) -> SourceError {
3369        SourceError::RateLimited {
3370            retry_after_seconds: self.hint,
3371            message: Some(format!(
3372                "{} refused this source while {doing}; it waited {} out over {} and was refused \
3373                 again, and the next wait of {} would take it past the {} one call may spend \
3374                 waiting. {} next: {}",
3375                self.limiter.name(),
3376                plural(waits, "refusal"),
3377                seconds(waited),
3378                seconds(needed),
3379                seconds(budget),
3380                self.limiter.where_to_look(),
3381                self.limiter.what_to_do(),
3382            )),
3383        }
3384    }
3385}
3386
3387/// One HTTP attempt's result, with what its response said about the rate limit.
3388///
3389/// The two travel together so the record and the outcome are written from the same place:
3390/// what a response said about the budget is only readable while that response is in hand,
3391/// and what the attempt *meant* is only decidable once its body has been read.
3392struct Attempted {
3393    result: Result<Value, Attempt>,
3394    limits: accounting::RateLimit,
3395    /// GitHub's own reported cost for this call, for a document that asked for it.
3396    reported_cost: Option<u64>,
3397    response_outcome: accounting::ResponseOutcome,
3398}
3399
3400/// One attempt's outcome: an error to report, or a rate limit to wait out.
3401enum Attempt {
3402    Failed(SourceError),
3403    Limited(Limited),
3404    /// GitHub refused a write as a temporary conflict and asked for it again — see
3405    /// [`CONFLICT_WORDINGS`]. Carries what GitHub said, for the diagnostic once retrying ends.
3406    Conflicted(String),
3407}
3408
3409fn plural(count: u32, thing: &str) -> String {
3410    if count == 1 {
3411        format!("{count} {thing}")
3412    } else {
3413        format!("{count} {thing}s")
3414    }
3415}
3416
3417fn seconds(duration: Duration) -> String {
3418    format!("{:.1}s", duration.as_secs_f64())
3419}
3420
3421/// The member [`stamp_served`] writes onto every node of a response that says when it last
3422/// changed: the `Date` that response was served at. No GitHub type has a field of this name.
3423const SERVED_AT: &str = "onetaskgraphServedAt";
3424
3425/// Write `served` onto every object of `data` carrying an `updatedAt`, so whatever reads a
3426/// node's time later knows the server's clock on the response that read it — which is what
3427/// decides whether that node's change token is given (see [`change_token::SETTLED`]).
3428fn stamp_served(data: &mut Value, served: &str) {
3429    match data {
3430        Value::Object(members) => {
3431            if members.contains_key("updatedAt") {
3432                members.insert(SERVED_AT.to_owned(), Value::String(served.to_owned()));
3433            }
3434            for member in members.values_mut() {
3435                stamp_served(member, served);
3436            }
3437        }
3438        Value::Array(items) => {
3439            for item in items {
3440                stamp_served(item, served);
3441            }
3442        }
3443        _ => {}
3444    }
3445}
3446
3447/// A header GitHub spells as a whole number of seconds, or `None` when this one is not.
3448///
3449/// A value that is present and unreadable is deliberately *not* an error. `retry-after` is
3450/// allowed by HTTP to be a date rather than a count, an intermediary can rewrite either
3451/// header, and neither is what makes a response a refusal — so the whole cost of one this
3452/// cannot read is that the refusal carries no hint and the backing-off schedule answers it
3453/// instead. Refusing the response over the header would turn a readable refusal into an
3454/// unreadable one, and refusing to *wait* would be the one wrong direction to fail in.
3455fn whole_seconds(value: Option<&reqwest::header::HeaderValue>) -> Option<u64> {
3456    value
3457        .and_then(|value| value.to_str().ok())
3458        .and_then(|value| value.trim().parse::<u64>().ok())
3459}
3460
3461/// A transport failure with every cause beneath it, outermost first.
3462///
3463/// The client's own text for a request it could not complete is `error sending request for
3464/// url (…)`, and the socket error that says why — a refused or reset connection, an exhausted
3465/// port range, a connection closed before its answer — is only in the chain of sources below
3466/// it. Those differ in what to do next, so all of them are kept.
3467pub(crate) fn transport_error(error: &(dyn std::error::Error + 'static)) -> String {
3468    let mut text = error.to_string();
3469    let mut cause = error.source();
3470    while let Some(next) = cause {
3471        let said = next.to_string();
3472        if !text.ends_with(&said) {
3473            text = format!("{text}: {said}");
3474        }
3475        cause = next.source();
3476    }
3477    text
3478}
3479
3480/// Every mutation this source sends creates content — an issue, a board item, a field of
3481/// one, a sub-issue link, a dependency, a comment — or edits or removes content of that
3482/// kind, and no query in [`graphql::DOCUMENTS`] does, so what the secondary limiter counts
3483/// and what the keyword says are the same set. That is what makes the keyword a sound test
3484/// rather than a convenient one: counting an edit or a removal the limiter might not have
3485/// counted costs a wait, and not counting one it did count costs the next fifty minutes.
3486pub(crate) fn is_mutation(query: &str) -> bool {
3487    query.trim_start().starts_with("mutation")
3488}
3489
3490/// What this source was doing, for a diagnostic that has to say so.
3491///
3492/// Read out of [`graphql::DOCUMENTS`], which is the inventory rather than a copy of it, so
3493/// a document added without a description is caught by that list's own gate instead of
3494/// falling through to the vague arm below.
3495fn operation_description(query: &str) -> &'static str {
3496    let query = graphql::inventoried(query);
3497    graphql::DOCUMENTS
3498        .iter()
3499        .find(|(document, _)| *document == query)
3500        .map_or("talking to GitHub", |(_, doing)| *doing)
3501}
3502
3503/// GitHub's published ceiling on content-generating requests in any one minute.
3504///
3505/// Pinned in `tests/fixtures/rate-limits.json` and gated against it, because it is
3506/// GitHub's number rather than this source's. This source paces at it over its window: a
3507/// content-creating request goes out at once while the minute's creations leave room for it,
3508/// and waits until they do otherwise — see the `pacing` module.
3509pub const CONTENT_CREATION_PER_MINUTE: u64 = 80;
3510/// The same ceiling as GitHub publishes it for any one hour, paced over its window as the
3511/// per-minute one is. Pinned beside its sibling so the gate would notice either one moving.
3512pub const CONTENT_CREATION_PER_HOUR: u64 = 500;
3513/// GitHub's published ceiling on secondary points in any one minute: what every GraphQL
3514/// request is charged against, a mutation [`SECONDARY_POINTS_PER_MUTATION`] and a query
3515/// [`SECONDARY_POINTS_PER_QUERY`]. Pinned and paced as [`CONTENT_CREATION_PER_MINUTE`] is.
3516pub const SECONDARY_POINTS_PER_MINUTE: u64 = 2_000;
3517/// The secondary points one GraphQL request carrying a mutation is charged.
3518pub const SECONDARY_POINTS_PER_MUTATION: u64 = 5;
3519/// The secondary points one GraphQL request carrying no mutation is charged.
3520pub const SECONDARY_POINTS_PER_QUERY: u64 = 1;
3521/// The fastest *steady* spacing of content-creating mutations that cannot exceed
3522/// [`CONTENT_CREATION_PER_MINUTE`], in milliseconds: 60000/80 is 750.
3523///
3524/// It is no longer the default. This source paces by GitHub's windows instead, so a copy's
3525/// few dozen writes go out as fast as GitHub answers them while the minute has room, rather
3526/// than 750 ms apart — which was most of a plan copy's wall time. An installation that wants
3527/// mutations spaced as well says so through `pacing.min_mutation_interval_ms`, and this is the
3528/// value that holds a long sustained burst under the per-minute bound by spacing alone.
3529pub const MIN_MUTATION_INTERVAL_MS: u64 = 60_000 / CONTENT_CREATION_PER_MINUTE;
3530/// First wait when a rate-limit refusal carries no hint; each further wait doubles it.
3531///
3532/// A doubling schedule from one second reaches a minute in six waits, which is GitHub's
3533/// own advice for a secondary limit — wait, and wait longer each time — without spending
3534/// the first minute of a transient refusal doing nothing.
3535pub const RETRY_BACKOFF_MS: u64 = 1_000;
3536/// Total time one call may spend waiting out rate limits before it reports a failure.
3537///
3538/// Two minutes is long enough to ride out the refusals a paced copy still collects and
3539/// short enough that a command an operator is watching returns. The bound is what makes
3540/// the wait a wait rather than a hang: a call refused past it ends in a diagnostic naming
3541/// the limiter, not in a process nobody can tell from a wedged one.
3542pub const RETRY_BUDGET_MS: u64 = 120_000;
3543
3544fn default_token_env() -> String {
3545    "GH_PROJECTS_TOKEN".to_owned()
3546}
3547fn default_endpoint() -> String {
3548    "https://api.github.com/graphql".to_owned()
3549}
3550
3551/// The name of a `Status` single-select option on the board.
3552///
3553/// Validated on the way in rather than checked later, so a blank option name — which
3554/// nothing on a board can be — is a state this type cannot hold.
3555#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3556#[serde(try_from = "String")]
3557#[schemars(extend("minLength" = 1))]
3558pub struct ColumnName(String);
3559
3560impl ColumnName {
3561    /// The option name, as the board spells it.
3562    fn as_str(&self) -> &str {
3563        &self.0
3564    }
3565}
3566
3567impl TryFrom<String> for ColumnName {
3568    type Error = String;
3569
3570    fn try_from(name: String) -> Result<Self, Self::Error> {
3571        if name.trim().is_empty() {
3572            return Err("a status_mapping option name cannot be blank".to_owned());
3573        }
3574        Ok(Self(name))
3575    }
3576}
3577
3578/// The two closed states this product can mean.
3579///
3580/// GitHub's `IssueClosedStateReason` also spells `DUPLICATE`, which nothing here ever writes:
3581/// an issue closed as one *reads* `cancelled`, because its work is another issue's, but this
3582/// product never decides on a person's behalf that two issues are the same work.
3583#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, schemars::JsonSchema)]
3584#[serde(rename_all = "kebab-case")]
3585pub enum ClosedState {
3586    /// `COMPLETED` — precisely done.
3587    Completed,
3588    /// `NOT_PLANNED` — precisely cancelled.
3589    NotPlanned,
3590}
3591
3592impl ClosedState {
3593    const fn reason(self) -> &'static str {
3594        match self {
3595            Self::Completed => "COMPLETED",
3596            Self::NotPlanned => "NOT_PLANNED",
3597        }
3598    }
3599}
3600
3601/// Configuration for one GitHub Projects v2 board.
3602///
3603/// It serializes to a document this same type reads back as itself, so a caller writing a
3604/// configuration — a consumer filing onto a board it configures — can build one here rather
3605/// than spell the shape again; an empty `metadata_fields` is left out, as one never set.
3606#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3607#[serde(default, deny_unknown_fields)]
3608pub struct GitHubProjectsConfig {
3609    /// Login of the user or organization which owns the board.
3610    pub owner: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates GitHub's owner grammar before private construction.
3611    /// The project number shown in the board's GitHub URL.
3612    pub project_number: u32, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` bounds this to a positive GraphQL Int.
3613    // llmlint: ignore-block[contracts_have_one_source_or_a_drift_gate] This doc is the field's schema description, which is what a person configuring the source reads, so it has to say when the field decides an issue's repository and when the item's own field does; the rule's one executable source is `GitHubProjectsSource::creation_target`, and `tests/plugin.rs` drives each case named here against the loopback board.
3614    /// `owner/name` of the repository this source creates an issue in when the item's own
3615    /// `repositories` field does not decide it.
3616    ///
3617    /// An item naming exactly one repository is created there — on a source declared
3618    /// `visibility: private`, only when that repository reads private, and otherwise as an
3619    /// item naming none is; a task or a document naming none or several is created in its
3620    /// parent project's repository; and a project, or a task or document with no parent,
3621    /// naming none or several is created here. A board
3622    /// has no repository of its own and `createIssue` requires one, so a write without
3623    /// this is refused naming the field. Reads never need it.
3624    pub repository: Option<String>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates the `owner/name` grammar before private construction.
3625    // llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate]
3626    /// GitHub logins whose repositories this source may create an issue in.
3627    ///
3628    /// Absent or empty, the default, restricts nothing. Otherwise a create whose issue the
3629    /// rule `repository` describes would file in a repository owned by anyone else is refused
3630    /// before anything of it is written — by `task copy`, `task copy --create`, a member
3631    /// create of a project copy and a dry run of each — with the error kind `creation-owner`,
3632    /// naming the repository and these owners. Logins compare case-insensitively, as GitHub
3633    /// compares them. An update of an issue that already exists is never refused by it.
3634    /// `task locate` reports such a refusal as `creates_in.refused` rather than failing.
3635    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3636    // Kept in the schema as `"default": []` although a serialized configuration leaves an empty
3637    // list out, so both SDKs model an absent list as an empty one rather than as `null`.
3638    #[schemars(!skip_serializing_if)]
3639    pub creation_owners: Vec<String>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates each entry against GitHub's login grammar, naming the one it refuses.
3640    /// Environment variable containing a fine-grained token with Projects and Issues
3641    /// read/write plus Pull requests read-only access for every repository represented on
3642    /// the board.
3643    #[serde(default = "default_token_env")]
3644    pub token_env: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates the environment-variable grammar.
3645    /// GraphQL endpoint. GitHub Enterprise installations may override it.
3646    #[serde(default = "default_endpoint")]
3647    pub endpoint: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` converts it to the private validated `Url`.
3648    /// Per-instance mapping from a status category to the option of the board's one
3649    /// `Status` field it lands on, for a task and for a project.
3650    ///
3651    /// The shared `StatusMapping` grammar: each value is one option name for both kinds,
3652    /// `null` to disable the category for both, or `{task, project}` naming it per kind,
3653    /// where a kind left out leaves the category unmapped for that kind. A category this
3654    /// does not mention keeps its shipped default for both kinds: `backlog` to "Backlog",
3655    /// `todo` to "Todo", `queued` to "Queued", `in-progress` to "In Progress", `done` to
3656    /// "Done" plus closed as completed, `cancelled` to "Cancelled" plus closed as not
3657    /// planned, and `draft` and `unknown` unmapped. A category it does mention gets no
3658    /// shipped default for a kind it leaves out. `done` and `cancelled` close the issue for
3659    /// either kind. No two categories may name one option for the same kind, ignoring case.
3660    /// `unknown` may name one existing option; every unknown word then lands on it and
3661    /// reads back as `unknown` under its name. Unlike `local-md`, this source cannot keep
3662    /// each unknown word because it never creates board options.
3663    #[serde(default)]
3664    pub status_mapping: StatusMapping,
3665    /// Per-instance mapping from a task's priority to an option of this board's
3666    /// single-select field named `Priority`.
3667    ///
3668    /// Absent, this source holds no priority: every task reads as `none`, and a write of any
3669    /// other priority is refused before it reaches this board. Present, each of `urgent`,
3670    /// `high`, `medium` and `low` it does not mention keeps its shipped default — `Urgent`,
3671    /// `High`, `Medium` and `Low` — and an item with no value in the `Priority` field reads
3672    /// as `none`, so writing `none` clears the value. Option names match case-insensitively;
3673    /// no two levels may name one option. Reads and writes never create the field or an
3674    /// option: `onetaskgraph sources fields <source> --apply` does, and a write naming one
3675    /// the board lacks is refused pointing there.
3676    #[serde(default)]
3677    pub priority_mapping: Option<PriorityMappingConfig>,
3678    /// Caller metadata values this source also writes to board text fields, so the board can
3679    /// filter on them.
3680    ///
3681    /// Absent or empty, nothing is projected. Each entry names a board text `field`, a
3682    /// top-level metadata `key` and an optional `path` of object keys walked inside that key's
3683    /// value. On every item write — create, update and copy, of a task, a project or a
3684    /// document — a string found there is written to the field, an array of strings as one
3685    /// line per element and an object of string values as one `KEY: VALUE` line per entry in
3686    /// byte order of the keys, shortened to whole lines and a count of the rest past the
3687    /// field's 1,024-byte limit; nothing is sent when the field already holds that text;
3688    /// nothing there, or `null`, clears the field when it holds a value; any other JSON type
3689    /// is refused before any mutation. `docs/metadata.md` states the rule. The metadata comment in the
3690    /// issue body stays the one home of the value, and every read reports metadata from it.
3691    /// Reads and writes never create the field: `onetaskgraph sources fields <source>
3692    /// --apply` does, as a text field, and a write to a board lacking it, or holding a
3693    /// non-text field of that name, is refused pointing there.
3694    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3695    // Kept in the schema as `"default": []` although a serialized configuration leaves an empty
3696    // list out, so both SDKs model an absent list as an empty one rather than as `null`.
3697    #[schemars(!skip_serializing_if)]
3698    pub metadata_fields: Vec<MetadataFieldConfig>,
3699    /// How fast this source writes, and how long it waits out a rate-limit refusal.
3700    ///
3701    /// Every field keeps its shipped default when it is absent, and the defaults are
3702    /// GitHub's own published limits rather than taste. See [`Pacing`].
3703    #[serde(default)]
3704    pub pacing: PacingConfig,
3705    /// What an issue's sub-issues mean on this board.
3706    ///
3707    /// `project`, the default, is this source's meaning since it was first written: an issue
3708    /// with sub-issues reads as a project and its sub-issues as that project's tasks. `parent`
3709    /// reads every issue as a task and a sub-issue as a child under the parent relation, which
3710    /// `task parent set-many` writes and `task relations` reads; a project write to such a
3711    /// source is refused naming this setting. The two meanings answer differently for the same
3712    /// issues, so a `parent` source needs a board of its own: two sources naming one board with
3713    /// different `sub_issues` are refused when the configuration is read.
3714    #[serde(default, skip_serializing_if = "SubIssues::is_project")]
3715    pub sub_issues: SubIssues,
3716    /// The link types this source also writes as GitHub's own `relates-to` relation, beside the
3717    /// store's metadata, so they show in the issue's Relationships panel: each type name mapped
3718    /// to `{"native": "relates-to"}`. A type not named here is kept in metadata alone. Any other
3719    /// word — `blocks`, `blocked-by`, `duplicate`, `similar` among them — is refused when the
3720    /// source is built.
3721    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
3722    // Kept in the schema as `"default": {}` although a serialized configuration leaves an empty
3723    // map out, so both SDKs model an absent map as an empty one rather than as `null`.
3724    #[schemars(!skip_serializing_if)]
3725    pub link_types: BTreeMap<String, onetaskgraph_plugin_api::LinkTypeConfig>,
3726    /// Whether this source's tasks carry the GitHub users each issue is assigned to, and
3727    /// take an assignee write. `false`, the default, reads no issue's assignees and writes
3728    /// none: every request this source sends is then exactly what it was before assignees
3729    /// existed. `true` reads each issue's assignees on the reads it already makes, and writes
3730    /// one person or none — by login — in the `createIssue` or `updateIssue` the write already
3731    /// sends, refusing a person GitHub does not know or leaves off the issue.
3732    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3733    // Kept in the schema as `"default": false` although a serialized configuration leaves a
3734    // `false` out, so both SDKs model an absent setting as `false` rather than as `null`.
3735    #[schemars(!skip_serializing_if)]
3736    pub assignees: bool,
3737}
3738
3739/// What an issue's sub-issues mean on a GitHub Projects board: see
3740/// [`GitHubProjectsConfig::sub_issues`].
3741#[derive(
3742    Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema,
3743)]
3744#[serde(rename_all = "kebab-case")]
3745pub enum SubIssues {
3746    /// An issue with sub-issues is a project, and its sub-issues are its tasks.
3747    #[default]
3748    Project,
3749    /// Every issue is a task, and a sub-issue is a child under the parent relation.
3750    Parent,
3751}
3752
3753impl SubIssues {
3754    /// Whether this is the default meaning, which a serialized configuration leaves out.
3755    #[must_use]
3756    pub const fn is_project(&self) -> bool {
3757        matches!(self, Self::Project)
3758    }
3759}
3760
3761/// Which option of the board's `Priority` field each priority lands on.
3762///
3763/// One member per level rather than a map, so a key that is not a level is refused where
3764/// the configuration is read, naming the levels there are. `none` is not a member: it is no
3765/// value in the field, not an option of it.
3766#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3767#[serde(default, deny_unknown_fields)]
3768pub struct PriorityMappingConfig {
3769    /// The option `urgent` lands on; `Urgent` when absent.
3770    pub urgent: Option<PriorityOptionName>,
3771    /// The option `high` lands on; `High` when absent.
3772    pub high: Option<PriorityOptionName>,
3773    /// The option `medium` lands on; `Medium` when absent.
3774    pub medium: Option<PriorityOptionName>,
3775    /// The option `low` lands on; `Low` when absent.
3776    pub low: Option<PriorityOptionName>,
3777}
3778
3779/// The name of an option of the board's `Priority` single-select field.
3780///
3781/// Validated on the way in, for the reason [`ColumnName`] is: nothing on a board can have a
3782/// blank name.
3783#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3784#[serde(try_from = "String")]
3785#[schemars(extend("minLength" = 1))]
3786pub struct PriorityOptionName(String);
3787
3788impl PriorityOptionName {
3789    /// The option name, as the board spells it.
3790    fn as_str(&self) -> &str {
3791        &self.0
3792    }
3793}
3794
3795impl TryFrom<String> for PriorityOptionName {
3796    type Error = String;
3797
3798    fn try_from(name: String) -> Result<Self, Self::Error> {
3799        if name.trim().is_empty() {
3800            return Err("a priority_mapping option name cannot be blank".to_owned());
3801        }
3802        Ok(Self(name))
3803    }
3804}
3805
3806/// The name of the board field a priority is held in.
3807pub const PRIORITY_FIELD: &str = "Priority";
3808
3809/// The four priorities a board option can hold, in the order a new `Priority` field lists
3810/// them. `none` is not among them: it is the field holding no value.
3811///
3812/// This list mirrors `Priority`, so it carries its own drift gate, in the shape [`CATEGORIES`]
3813/// does: [`level_position`] is a wildcard-free match, so a priority added to the shared
3814/// vocabulary fails to compile until it is placed there, and this crate's suite reconciles
3815/// this list and [`PriorityMappingConfig`]'s members against that enum's own derived schema.
3816pub const PRIORITY_LEVELS: [Priority; 4] = [
3817    Priority::Urgent,
3818    Priority::High,
3819    Priority::Medium,
3820    Priority::Low,
3821];
3822
3823/// Where one priority sits in [`PRIORITY_LEVELS`], or `None` for `none`, which is no option;
3824/// see that list for what this pins.
3825#[must_use]
3826pub const fn level_position(priority: Priority) -> Option<usize> {
3827    match priority {
3828        Priority::None => None,
3829        Priority::Urgent => Some(0),
3830        Priority::High => Some(1),
3831        Priority::Medium => Some(2),
3832        Priority::Low => Some(3),
3833    }
3834}
3835
3836/// This instance's complete priority-to-option mapping, read in both directions.
3837///
3838/// One option per level, held in [`PRIORITY_LEVELS`] order, once it is established that no
3839/// two levels name one option.
3840#[derive(Debug, Clone)]
3841struct PriorityMapping {
3842    options: [PriorityOptionName; 4],
3843}
3844
3845impl PriorityMapping {
3846    fn resolve(config: PriorityMappingConfig, instance: &SourceName) -> Result<Self, SourceError> {
3847        let shipped = |name: &str| PriorityOptionName(name.to_owned());
3848        let mapping = Self {
3849            options: [
3850                config.urgent.unwrap_or_else(|| shipped("Urgent")),
3851                config.high.unwrap_or_else(|| shipped("High")),
3852                config.medium.unwrap_or_else(|| shipped("Medium")),
3853                config.low.unwrap_or_else(|| shipped("Low")),
3854            ],
3855        };
3856        for (index, option) in mapping.options.iter().enumerate() {
3857            if let Some(earlier) = mapping.options[..index]
3858                .iter()
3859                .position(|other| other.as_str().eq_ignore_ascii_case(option.as_str()))
3860            {
3861                return Err(SourceError::Config {
3862                    message: format!(
3863                        "priority_mapping of source {instance} sends both {} and {} to the board \
3864                         option {:?}; one option cannot read back as two priorities",
3865                        PRIORITY_LEVELS[earlier],
3866                        PRIORITY_LEVELS[index],
3867                        option.as_str()
3868                    ),
3869                });
3870            }
3871        }
3872        Ok(mapping)
3873    }
3874
3875    /// The option `priority` lands on, or `None` for `none`, which is no option at all.
3876    fn option(&self, priority: Priority) -> Option<&str> {
3877        level_position(priority).map(|index| self.options[index].as_str())
3878    }
3879
3880    /// The priority a board option name reports, or `None` when nothing maps to it.
3881    fn priority_of(&self, option: &str) -> Option<Priority> {
3882        self.options
3883            .iter()
3884            .position(|name| name.as_str().eq_ignore_ascii_case(option))
3885            .map(|index| PRIORITY_LEVELS[index])
3886    }
3887
3888    /// Every mapped option name, in the order a new `Priority` field lists them.
3889    fn names(&self) -> impl Iterator<Item = &str> {
3890        self.options.iter().map(PriorityOptionName::as_str)
3891    }
3892}
3893
3894/// One metadata value this source projects onto a board text field.
3895#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3896#[serde(deny_unknown_fields)]
3897pub struct MetadataFieldConfig {
3898    /// The name of the board text field the value is written to.
3899    pub field: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `MetadataField::resolve` refuses a blank, reserved, GitHub-owned or repeated name before the private validated entry is built.
3900    /// The top-level metadata key the value is read from. A key under the reserved
3901    /// `onetaskgraph.` prefix is refused.
3902    pub key: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `MetadataField::resolve` refuses a blank or reserved key before the private validated entry is built.
3903    /// Object keys walked inside that key's value, outermost first. Absent or empty, the
3904    /// key's own value is the one projected. Left out of a serialized entry when empty.
3905    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3906    // Kept in the schema as `"default": []`, for the reason `metadata_fields`' is.
3907    #[schemars(!skip_serializing_if)]
3908    pub path: Vec<String>,
3909}
3910
3911/// The board fields no metadata value may be projected onto, compared ignoring case: the
3912/// three this source writes itself, and those GitHub owns on every board.
3913// llmlint: ignore[contracts_have_one_source_or_a_drift_gate] This list is the configuration contract `metadata_fields`' consumers agreed, refused at read so a mistaken entry is named early — not a mirror GitHub's field set has to stay in step with. What keeps a write off a field GitHub owns is the write's own check, `projection_field`, which refuses any field whose `dataType` is not `TEXT`: every built-in board field reports its own type (TITLE, ASSIGNEES, LABELS, …), and the live contract introspection holds GitHub to `ProjectV2Field.dataType`. So a built-in field GitHub adds later and this list lacks is still never written.
3914const UNPROJECTABLE_FIELDS: [&str; 13] = [
3915    STATUS_FIELD,
3916    PRIORITY_FIELD,
3917    ORIGIN_FIELD,
3918    "Title",
3919    "Assignees",
3920    "Labels",
3921    "Linked pull requests",
3922    "Milestone",
3923    "Repository",
3924    "Reviewers",
3925    "Parent issue",
3926    "Sub-issues progress",
3927    "Type",
3928];
3929
3930/// One validated [`MetadataFieldConfig`] entry.
3931#[derive(Debug, Clone)]
3932struct MetadataField {
3933    field: ProjectedField,
3934    key: ProjectedKey,
3935    path: Vec<String>,
3936}
3937
3938/// The name of a board text field a metadata value is projected onto: never blank, never one
3939/// this source or GitHub writes, and never one another entry of the same source names.
3940#[derive(Debug, Clone, PartialEq, Eq)]
3941struct ProjectedField(String);
3942
3943/// The top-level metadata key a projected value is read from: never blank, and never under
3944/// the namespace this product reserves.
3945#[derive(Debug, Clone, PartialEq, Eq)]
3946struct ProjectedKey(String);
3947
3948impl std::ops::Deref for ProjectedField {
3949    type Target = str;
3950    fn deref(&self) -> &str {
3951        &self.0
3952    }
3953}
3954
3955impl std::ops::Deref for ProjectedKey {
3956    type Target = str;
3957    fn deref(&self) -> &str {
3958        &self.0
3959    }
3960}
3961
3962/// What one item's metadata says one projected field should hold.
3963#[derive(Debug, Clone, PartialEq, Eq)]
3964enum Projected {
3965    /// A string to hold.
3966    Text(String),
3967    /// Nothing: the key or a step of the path is absent, or the value is `null`.
3968    Nothing,
3969}
3970
3971impl MetadataField {
3972    /// Validate every entry of one instance's `metadata_fields`, refusing the first that
3973    /// cannot stand, naming the source and the entry.
3974    fn resolve(
3975        configured: Vec<MetadataFieldConfig>,
3976        instance: &SourceName,
3977    ) -> Result<Vec<Self>, SourceError> {
3978        let mut resolved: Vec<Self> = Vec::with_capacity(configured.len());
3979        for (index, entry) in configured.into_iter().enumerate() {
3980            let refuse = |why: String| SourceError::Config {
3981                message: format!(
3982                    "metadata_fields[{index}] of source {instance} (field {:?}, key {:?}) {why}",
3983                    entry.field, entry.key
3984                ),
3985            };
3986            if let Some(why) = ProjectedValue::entry_refusal(
3987                &entry.field,
3988                &entry.key,
3989                resolved.iter().map(|other| &*other.field),
3990                "board field",
3991            ) {
3992                return Err(refuse(why));
3993            }
3994            if let Some(owned) = UNPROJECTABLE_FIELDS
3995                .iter()
3996                .find(|owned| owned.eq_ignore_ascii_case(&entry.field))
3997            {
3998                return Err(refuse(format!(
3999                    "names the board field {owned:?}, which this source or GitHub already \
4000                     writes; next: name a text field of your own"
4001                )));
4002            }
4003            resolved.push(Self {
4004                field: ProjectedField(entry.field),
4005                key: ProjectedKey(entry.key),
4006                path: entry.path,
4007            });
4008        }
4009        Ok(resolved)
4010    }
4011
4012    /// The path as a refusal spells it: `[]` for the key's own value.
4013    fn spelled_path(&self) -> String {
4014        serde_json::to_string(&self.path).unwrap_or_else(|_| format!("{:?}", self.path))
4015    }
4016
4017    /// What `metadata` says this field should hold, or the refusal for a value no text field
4018    /// can hold.
4019    fn projected(
4020        &self,
4021        metadata: &BTreeMap<String, Value>,
4022        instance: &SourceName,
4023    ) -> Result<Projected, SourceError> {
4024        let found = match ProjectedValue::read(metadata, &self.key, &self.path) {
4025            Ok(None) => return Ok(Projected::Nothing),
4026            Ok(Some(value)) => return Ok(Projected::Text(field_text(&value))),
4027            Err(found) => found,
4028        };
4029        Err(SourceError::Refused {
4030            message: format!(
4031                "source {instance} projects metadata key {:?} at path {} onto its board text \
4032                 field {:?}, and this item holds {found} there; only a string, an array of \
4033                 strings, an object of string values, null or nothing can be written to a text \
4034                 field; next: store one of those there, or remove the value",
4035                &*self.key,
4036                self.spelled_path(),
4037                &*self.field
4038            ),
4039        })
4040    }
4041}
4042
4043/// The most a ProjectV2 text field holds, in UTF-8 bytes.
4044///
4045/// Spike `spike-sample-ticket` measured it on a live board through this store with ASCII
4046/// values: 1,024 accepted, 1,025 refused whole with `Column value must be a valid value for
4047/// text column`, and nothing on the item changed. GitHub documents neither the limit nor its
4048/// unit, so this source counts UTF-8 bytes — at least as many as characters or UTF-16 units —
4049/// which can only shorten a non-ASCII value earlier than GitHub would, never send one it
4050/// refuses.
4051// llmlint: ignore[contracts_have_one_source_or_a_drift_gate] GitHub publishes no machine-readable statement of this limit — neither its documentation nor its GraphQL schema (`ProjectV2FieldValue.text: String`) names one — so the only source is the measurement above, and a live probe would spend the credentialed lane's budget, which is a decision outside this change. Drift cannot pass silently either way: a raised limit only shortens a value earlier than needed, and a lowered one makes GitHub refuse the write, which fails the command naming the field.
4052pub const TEXT_FIELD_LIMIT: usize = 1024;
4053
4054/// The text a board text field holds for `value`, as `docs/metadata.md` states it: a string as
4055/// itself, an array's elements and an object's `KEY: VALUE` entries — in byte order of the
4056/// keys — one per line, joined by one line feed; and, over [`TEXT_FIELD_LIMIT`], the longest
4057/// prefix of whole lines that fits beside one line feed and the line counting the rest.
4058fn field_text(value: &ProjectedValue) -> String {
4059    let rendered = match value {
4060        ProjectedValue::Text(text) => text.clone(),
4061        ProjectedValue::List(list) => list.join("\n"),
4062        ProjectedValue::Map(map) => map
4063            .iter()
4064            .map(|(key, value)| format!("{key}: {value}"))
4065            .collect::<Vec<_>>()
4066            .join("\n"),
4067    };
4068    if rendered.len() <= TEXT_FIELD_LIMIT {
4069        return rendered;
4070    }
4071    let lines: Vec<&str> = rendered.split('\n').collect();
4072    let elided = |left_out: usize| {
4073        let noun = if left_out == 1 { "line" } else { "lines" };
4074        format!("\u{2026} {left_out} more {noun} in this item's metadata")
4075    };
4076    // The bytes the first `kept` lines take with the line feeds between them.
4077    let mut prefix = 0;
4078    let mut fits = 0;
4079    for (kept, line) in lines.iter().enumerate().map(|(at, line)| (at + 1, line)) {
4080        prefix += line.len() + usize::from(kept > 1);
4081        if kept == lines.len() || prefix + 1 + elided(lines.len() - kept).len() > TEXT_FIELD_LIMIT {
4082            break;
4083        }
4084        fits = kept;
4085    }
4086    if fits == 0 {
4087        return elided(lines.len());
4088    }
4089    format!(
4090        "{}\n{}",
4091        lines[..fits].join("\n"),
4092        elided(lines.len() - fits)
4093    )
4094}
4095
4096/// What one item's `Priority` field says, read through this instance's mapping.
4097#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
4098enum HeldPriority {
4099    /// A priority this source reports: an option the mapping names, or no value (`none`).
4100    Read(Priority),
4101    /// An option the mapping does not name, which is never read as a level or as `none`.
4102    Unmapped(String),
4103}
4104
4105/// How fast this source writes, and how long it waits out a rate-limit refusal.
4106///
4107/// Configurable because a GitHub Enterprise installation sets its own limits and an
4108/// operator who has already been refused may want to go slower still — not because the
4109/// defaults are guesses.
4110#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
4111#[serde(default, deny_unknown_fields)]
4112pub struct PacingConfig {
4113    /// Shortest interval between two content-creating mutations, in milliseconds.
4114    ///
4115    /// Zero sends them as fast as they are asked for, which is what a fixture server on
4116    /// loopback wants and what no board on github.com does. At most [`MAX_PACING_MS`].
4117    pub min_mutation_interval_ms: Option<u64>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `Pacing::resolve` bounds it to `MAX_PACING_MS` before the private validated `Pacing` is built.
4118    /// First wait when a rate-limit refusal carries no hint, in milliseconds. Each
4119    /// further wait of the same call doubles it. At most [`MAX_PACING_MS`], and never
4120    /// zero while there is a budget to spend, because a schedule of zero-length waits
4121    /// consumes none of it and so never ends.
4122    pub retry_backoff_ms: Option<u64>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `Pacing::resolve` refuses a non-progressing zero and bounds the rest before the private validated `Pacing` is built.
4123    /// Total time one call may spend waiting out rate limits, in milliseconds.
4124    ///
4125    /// Zero reports the refusal rather than waiting at all. At most [`MAX_PACING_MS`]:
4126    /// the bound is what makes this a wait rather than a hang.
4127    pub retry_budget_ms: Option<u64>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `Pacing::resolve` bounds it to `MAX_PACING_MS` before the private validated `Pacing` is built.
4128}
4129
4130/// The largest any pacing setting may be, in milliseconds.
4131///
4132/// One hour. GitHub's own harshest published bound on content-generating requests works
4133/// out at one every 7.2 seconds, so an hour is already three orders of magnitude past
4134/// anything a real limit asks for, and past it the settings stop describing pacing at all:
4135/// a wait budget beyond it is the unbounded wait this whole mechanism exists to replace,
4136/// and an interval beyond it is a command that never sends its second mutation. It also
4137/// keeps the clock arithmetic in [`GitHubProjectsSource::reserve_mutation_slot`] inside
4138/// what a `Duration` can hold on every platform.
4139pub const MAX_PACING_MS: u64 = 3_600_000;
4140
4141/// [`PacingConfig`] with every default resolved and every value checked, which is what the
4142/// source holds.
4143///
4144/// Unset, `min_mutation_interval_ms` spaces nothing, and every request is paced by GitHub's
4145/// secondary windows alone — see the `pacing` module; set, it spaces content-creating mutations
4146/// on top of those windows, [`MIN_MUTATION_INTERVAL_MS`] being the spacing that holds a sustained
4147/// burst under the per-minute bound by spacing alone; and zero sends every request as fast as it
4148/// is asked for, windows included.
4149#[derive(Debug, Clone, Copy)]
4150struct Pacing {
4151    /// Whether requests are held for GitHub's secondary windows: always, unless
4152    /// `min_mutation_interval_ms` is set to exactly zero, which has always asked for no
4153    /// pacing at all — what a fixture server on loopback wants and no board on github.com does.
4154    windows: bool,
4155    min_mutation_interval: Duration,
4156    retry_backoff: Duration,
4157    retry_budget: Duration,
4158}
4159
4160impl Pacing {
4161    /// Resolve one instance's pacing, refusing a configuration that would not pace at all.
4162    fn resolve(config: PacingConfig, instance: &SourceName) -> Result<Self, SourceError> {
4163        let bounded = |value: Option<u64>, default: u64, field: &str| match value {
4164            Some(value) if value > MAX_PACING_MS => Err(SourceError::Config {
4165                message: format!(
4166                    "pacing.{field} of source {instance} is {value} ms, and the most any pacing \
4167                     setting may be is {MAX_PACING_MS} ms — an hour, which is already far past \
4168                     GitHub's own harshest published limit"
4169                ),
4170            }),
4171            Some(value) => Ok(Duration::from_millis(value)),
4172            None => Ok(Duration::from_millis(default)),
4173        };
4174        let retry_backoff = bounded(
4175            config.retry_backoff_ms,
4176            RETRY_BACKOFF_MS,
4177            "retry_backoff_ms",
4178        )?;
4179        let retry_budget = bounded(config.retry_budget_ms, RETRY_BUDGET_MS, "retry_budget_ms")?;
4180        if retry_backoff.is_zero() && !retry_budget.is_zero() {
4181            return Err(SourceError::Config {
4182                message: format!(
4183                    "pacing.retry_backoff_ms of source {instance} is 0 while \
4184                     pacing.retry_budget_ms is {} ms; a schedule of zero-length waits spends \
4185                     none of that budget, so it would retry a refusal forever. Set a backoff of \
4186                     at least 1 ms, or set retry_budget_ms to 0 to report a refusal without \
4187                     waiting at all",
4188                    retry_budget.as_millis()
4189                ),
4190            });
4191        }
4192        Ok(Self {
4193            windows: config.min_mutation_interval_ms != Some(0),
4194            min_mutation_interval: bounded(
4195                config.min_mutation_interval_ms,
4196                0,
4197                "min_mutation_interval_ms",
4198            )?,
4199            retry_backoff,
4200            retry_budget,
4201        })
4202    }
4203}
4204
4205/// Factory for [`GitHubProjectsSource`].
4206#[derive(Debug, Clone, Copy, Default)]
4207pub struct Plugin;
4208
4209impl SourcePlugin for Plugin {
4210    fn kind(&self) -> &'static str {
4211        KIND
4212    }
4213    /// The endpoint, the owner and the board's number: what names one board.
4214    fn remote_identity(&self, config: &Value) -> Option<String> {
4215        let config: GitHubProjectsConfig = serde_json::from_value(config.clone()).ok()?;
4216        Some(format!(
4217            "{}\n{}\n{}",
4218            config.endpoint, config.owner, config.project_number
4219        ))
4220    }
4221    fn config_schema(&self) -> Schema {
4222        schema_for!(GitHubProjectsConfig)
4223    }
4224    fn build(
4225        &self,
4226        name: &SourceName,
4227        config: &Value,
4228        secrets: &dyn SecretResolver,
4229    ) -> Result<Box<dyn TaskSource>, SourceError> {
4230        self.build_recording_into(name, config, secrets, Arc::new(Accounting::new()))
4231    }
4232
4233    fn build_with_clock(
4234        &self,
4235        name: &SourceName,
4236        config: &Value,
4237        secrets: &dyn SecretResolver,
4238        clock: SharedClock,
4239    ) -> Result<Box<dyn TaskSource>, SourceError> {
4240        self.build_recording_with_clock(name, config, secrets, Arc::new(Accounting::new()), clock)
4241    }
4242}
4243
4244/// The client `cell` holds, building it with `build` the first time it is asked for.
4245///
4246/// A failed build is the request's failure, with the message the source's construction gave it
4247/// before clients were deferred.
4248// llmlint: ignore[changed_behavior_has_e2e] A client build fails only when the TLS backend cannot initialise, which nothing outside the process can induce: a certificate bundle of garbage still builds one. That the build is deferred is proven end to end by `store_startup::a_command_builds_no_client_for_a_source_it_sends_nothing`.
4249fn built(
4250    cell: &std::sync::OnceLock<Client>,
4251    build: impl FnOnce() -> Result<Client, SourceError>,
4252) -> Result<&Client, SourceError> {
4253    if let Some(client) = cell.get() {
4254        return Ok(client);
4255    }
4256    let client = build()?;
4257    Ok(cell.get_or_init(|| client))
4258}
4259
4260impl Plugin {
4261    /// Build a source recording every request it sends into an accounting the caller holds.
4262    ///
4263    /// [`SourcePlugin::build`] is this with an accounting of its own, which is what the
4264    /// registry gets. This is for a caller that is also calling GitHub itself and wants one
4265    /// session total rather than two — see [`accounting`] and
4266    /// [`GitHubProjectsSource::recording_into`].
4267    ///
4268    /// # Errors
4269    ///
4270    /// Exactly [`SourcePlugin::build`]'s, with the same source name in front of each:
4271    /// [`SourceError::Config`] for configuration this plugin cannot use and
4272    /// [`SourceError::Auth`] for a credential it cannot find.
4273    pub fn build_recording_into(
4274        &self,
4275        name: &SourceName,
4276        config: &Value,
4277        secrets: &dyn SecretResolver,
4278        ledger: Arc<Accounting>,
4279    ) -> Result<Box<dyn TaskSource>, SourceError> {
4280        self.build_recording_with_clock(name, config, secrets, ledger, system_clock())
4281    }
4282
4283    fn build_recording_with_clock(
4284        &self,
4285        name: &SourceName,
4286        config: &Value,
4287        secrets: &dyn SecretResolver,
4288        ledger: Arc<Accounting>,
4289        clock: SharedClock,
4290    ) -> Result<Box<dyn TaskSource>, SourceError> {
4291        let config: GitHubProjectsConfig =
4292            serde_json::from_value(config.clone()).map_err(|e| SourceError::Config {
4293                message: format!("source {name}: {e}"),
4294            })?;
4295        let prefix = format!("source {name}: ");
4296        let mut source = GitHubProjectsSource::recording_into(name, config, secrets, ledger)
4297            .map_err(|error| match error {
4298                // The shared `StatusMapping::distinct` names the source itself.
4299                SourceError::Config { message } if message.starts_with(&prefix) => {
4300                    SourceError::Config { message }
4301                }
4302                SourceError::Config { message } => SourceError::Config {
4303                    message: format!("{prefix}{message}"),
4304                },
4305                SourceError::Auth { message } => SourceError::Auth {
4306                    message: format!("source {name}: {message}"),
4307                },
4308                other => other,
4309            })?;
4310        source.clock = clock;
4311        Ok(Box::new(source))
4312    }
4313}
4314
4315/// Where a status category lands on this board, once configuration is resolved.
4316#[derive(Debug, Clone, PartialEq, Eq)]
4317enum StatusTarget {
4318    /// Not usable against this instance for this kind, and why.
4319    Disabled(UnmappedStatus),
4320    /// The board's `Status` option of this name.
4321    Column(ColumnName),
4322    /// A closed issue, with both its board option and the reason that says which closed it means.
4323    // llmlint: ignore[invalid_states_unrepresentable] The reason is fixed by the category — `done` closes as completed, `cancelled` as not planned — and this private enum is built in one place, `BoardStatuses::resolve`, which pairs each from the category's own slot. Carrying the reason on the target is what lets every write site that holds only a target derive its `stateInput` from that one resolved model rather than re-deriving it from a category and risking a disagreement with the mapping.
4324    Terminal(ColumnName, ClosedState),
4325}
4326
4327/// Every status category, in the order the vocabulary declares them.
4328///
4329/// This list mirrors `StatusCategory`, so it carries its own drift gate rather than a
4330/// reviewer's attention: [`category_position`] is a wildcard-free match, so a variant
4331/// added to the shared vocabulary fails to compile until it is named there, and this
4332/// crate's suite reconciles this list against that enum's own derived schema, which is
4333/// generated from the variants rather than written beside them. The schema is what
4334/// catches a list left one short — a list checking only the positions it already holds
4335/// would pass while every mapping indexed by the new position panicked.
4336pub const CATEGORIES: [StatusCategory; 8] = [
4337    StatusCategory::Draft,
4338    StatusCategory::Backlog,
4339    StatusCategory::Todo,
4340    StatusCategory::Queued,
4341    StatusCategory::InProgress,
4342    StatusCategory::Done,
4343    StatusCategory::Cancelled,
4344    StatusCategory::Unknown,
4345];
4346
4347/// Where one category sits in [`CATEGORIES`]; see that list for what this pins.
4348#[must_use]
4349pub const fn category_position(category: StatusCategory) -> usize {
4350    match category {
4351        StatusCategory::Draft => 0,
4352        StatusCategory::Backlog => 1,
4353        StatusCategory::Todo => 2,
4354        StatusCategory::Queued => 3,
4355        StatusCategory::InProgress => 4,
4356        StatusCategory::Done => 5,
4357        StatusCategory::Cancelled => 6,
4358        StatusCategory::Unknown => 7,
4359    }
4360}
4361
4362/// The spelling a status category is configured and reported under.
4363fn category_name(category: StatusCategory) -> &'static str {
4364    match category {
4365        StatusCategory::Draft => "draft",
4366        StatusCategory::Backlog => "backlog",
4367        StatusCategory::Todo => "todo",
4368        StatusCategory::Queued => "queued",
4369        StatusCategory::InProgress => "in-progress",
4370        StatusCategory::Done => "done",
4371        StatusCategory::Cancelled => "cancelled",
4372        StatusCategory::Unknown => "unknown",
4373    }
4374}
4375
4376/// A shipped default's option name.
4377///
4378/// The literals below are this file's own and non-blank, and they are validated by the
4379/// one constructor a configured name goes through rather than beside it.
4380fn shipped_column(name: &'static str) -> ColumnName {
4381    ColumnName::try_from(name.to_owned()).expect("a shipped default names a board option")
4382}
4383
4384/// The shipped default for one category this instance's `status_mapping` does not mention,
4385/// for either kind.
4386fn shipped_default(category: StatusCategory) -> StatusTarget {
4387    match category {
4388        StatusCategory::Backlog => StatusTarget::Column(shipped_column("Backlog")),
4389        StatusCategory::Todo => StatusTarget::Column(shipped_column("Todo")),
4390        StatusCategory::Queued => StatusTarget::Column(shipped_column("Queued")),
4391        StatusCategory::InProgress => StatusTarget::Column(shipped_column("In Progress")),
4392        StatusCategory::Done => {
4393            StatusTarget::Terminal(shipped_column("Done"), ClosedState::Completed)
4394        }
4395        StatusCategory::Cancelled => {
4396            StatusTarget::Terminal(shipped_column("Cancelled"), ClosedState::NotPlanned)
4397        }
4398        StatusCategory::Draft | StatusCategory::Unknown => {
4399            StatusTarget::Disabled(UnmappedStatus::Unconfigured)
4400        }
4401    }
4402}
4403
4404/// The two kinds a status is written and read for, each with its own half of the mapping.
4405const STATUS_KINDS: [ItemKind; 2] = [ItemKind::Task, ItemKind::Project];
4406
4407/// This instance's complete category-to-target mapping for each kind, read in both
4408/// directions.
4409///
4410/// One target per category per kind, held at that category's own [`category_position`], so
4411/// a category missing from the mapping, named twice in it, or filed out of order is a state
4412/// this type cannot hold rather than one [`Self::target`] has to defend against. Both kinds'
4413/// targets are options of the board's one `Status` field.
4414#[derive(Debug, Clone)]
4415struct BoardStatuses {
4416    tasks: [StatusTarget; CATEGORIES.len()],
4417    projects: [StatusTarget; CATEGORIES.len()],
4418}
4419
4420impl BoardStatuses {
4421    /// Resolve `configured` against the shipped defaults, refusing two categories one kind
4422    /// would read back from one option.
4423    ///
4424    /// A category the mapping does not mention keeps its shipped default for both kinds; one
4425    /// it does mention is exactly what it configures, so a per-kind object leaves the kind it
4426    /// omits unmapped rather than defaulted.
4427    fn resolve(configured: &StatusMapping, instance: &SourceName) -> Result<Self, SourceError> {
4428        let resolve_kind =
4429            |kind: ItemKind| -> Result<[StatusTarget; CATEGORIES.len()], SourceError> {
4430                // `CATEGORIES[position] == category` for every category — the crate's suite
4431                // asserts it — so mapping the list in order fills each category's own slot.
4432                let mut targets = CATEGORIES.map(shipped_default);
4433                for (slot, category) in targets.iter_mut().zip(CATEGORIES) {
4434                    if !configured.mentions(category) {
4435                        continue;
4436                    }
4437                    *slot = match configured.name_for(category, kind) {
4438                        Err(why) => StatusTarget::Disabled(why),
4439                        Ok(name) => {
4440                            let option = ColumnName::try_from(name.as_str().to_owned())
4441                                .map_err(|message| SourceError::Config { message })?;
4442                            match category {
4443                                StatusCategory::Done => {
4444                                    StatusTarget::Terminal(option, ClosedState::Completed)
4445                                }
4446                                StatusCategory::Cancelled => {
4447                                    StatusTarget::Terminal(option, ClosedState::NotPlanned)
4448                                }
4449                                _ => StatusTarget::Column(option),
4450                            }
4451                        }
4452                    };
4453                }
4454                StatusMapping::distinct(
4455                    instance,
4456                    kind,
4457                    CATEGORIES
4458                        .iter()
4459                        .zip(&targets)
4460                        .filter_map(|(category, target)| target.option().map(|o| (*category, o))),
4461                )?;
4462                Ok(targets)
4463            };
4464        Ok(Self {
4465            tasks: resolve_kind(ItemKind::Task)?,
4466            projects: resolve_kind(ItemKind::Project)?,
4467        })
4468    }
4469
4470    /// Every category's target for `kind`, in category order.
4471    const fn targets(&self, kind: ItemKind) -> &[StatusTarget; CATEGORIES.len()] {
4472        match kind {
4473            ItemKind::Task => &self.tasks,
4474            ItemKind::Project => &self.projects,
4475        }
4476    }
4477
4478    fn target(&self, kind: ItemKind, category: StatusCategory) -> &StatusTarget {
4479        &self.targets(kind)[category_position(category)]
4480    }
4481
4482    /// The category a board option name reports for `kind`, or `None` when nothing of that
4483    /// kind maps to it.
4484    fn category_of(&self, kind: ItemKind, option: &str) -> Option<StatusCategory> {
4485        CATEGORIES.into_iter().find(|category| {
4486            self.target(kind, *category)
4487                .option()
4488                .is_some_and(|name| name.eq_ignore_ascii_case(option))
4489        })
4490    }
4491
4492    /// Every option name either kind maps a category to, each once ignoring case, in
4493    /// category order with a task's name before a project's — what the guarded setup asks
4494    /// the `Status` field to hold.
4495    fn wanted(&self) -> Vec<String> {
4496        let mut wanted: Vec<String> = Vec::new();
4497        for category in CATEGORIES {
4498            for kind in STATUS_KINDS {
4499                if let Some(name) = self.target(kind, category).option()
4500                    && !wanted.iter().any(|held| held.eq_ignore_ascii_case(name))
4501                {
4502                    wanted.push(name.to_owned());
4503                }
4504            }
4505        }
4506        wanted
4507    }
4508
4509    /// The status an item of `kind` reports, from the three things a read of it says: its
4510    /// board `Status` option, whether its issue is closed, and the reason it was closed with.
4511    ///
4512    /// **A closed issue's category follows its closure**, by [`closed_category`]: completed
4513    /// or no reason reads `done`, not planned and duplicate read `cancelled`, and any other
4514    /// reason reads `unknown`. `REOPENED`-while-closed is a state this source can never
4515    /// produce, so it is read permissively rather than refused — reads are faithful, and
4516    /// refusals belong on writes.
4517    ///
4518    /// **Its name follows the closure too, unless the option agrees with it.** The option's
4519    /// own name is kept when this kind's mapping reads that option as the same category, or
4520    /// does not name it at all — so a closed issue in a "Shipped" column reports `done`
4521    /// named `Shipped`. An option the mapping reads as another category contradicts the
4522    /// closure, and so does no option at all: the name is then the option the mapping gives
4523    /// the closure's category, so an issue closed as completed at `Todo` reads `done` named
4524    /// by the board's `done` option, and a destination reading `Todo` as todo is never handed
4525    /// it. An `unknown` closure keeps the option, or `Closed` without one.
4526    ///
4527    /// An open item's option reads through its own kind's mapping, and an option that mapping
4528    /// does not name reads as `Unknown` under its own name.
4529    ///
4530    /// One function of those three rather than of a response, so a narrow status write can
4531    /// answer what a re-read would report by applying it to the state it has just written.
4532    fn status(
4533        &self,
4534        kind: ItemKind,
4535        option: Option<&str>,
4536        closed: bool,
4537        reason: Option<&str>,
4538    ) -> Status {
4539        if closed {
4540            let category = closed_category(reason);
4541            let agrees = option.filter(|option| {
4542                category == StatusCategory::Unknown
4543                    || self
4544                        .category_of(kind, option)
4545                        .is_none_or(|read| read == category)
4546            });
4547            let name = agrees.or_else(|| self.target(kind, category).option());
4548            let fallback = match category {
4549                StatusCategory::Done => "Done",
4550                StatusCategory::Cancelled => "Cancelled",
4551                _ => "Closed",
4552            };
4553            return Status {
4554                category,
4555                name: name.or(option).unwrap_or(fallback).to_owned(),
4556            };
4557        }
4558        let name = option.unwrap_or("Open").to_owned();
4559        Status {
4560            category: self
4561                .category_of(kind, &name)
4562                .unwrap_or(StatusCategory::Unknown),
4563            name,
4564        }
4565    }
4566
4567    /// The option a closed item's `Status` has to hold for its card to agree with its
4568    /// closure, and the category that closure reads as — or `None` when the item is open,
4569    /// its closure reads `unknown`, or its option already agrees.
4570    ///
4571    /// What `task status reconcile` writes: only `done` and `cancelled` closures are brought
4572    /// in line, each to the one option the mapping gives its category — an item with no
4573    /// option, or at one the mapping does not name, included.
4574    fn contradicted(
4575        &self,
4576        kind: ItemKind,
4577        option: Option<&str>,
4578        closed: bool,
4579        reason: Option<&str>,
4580    ) -> Option<(ClosedAs, &str)> {
4581        if !closed {
4582            return None;
4583        }
4584        let closed_as = match closed_category(reason) {
4585            StatusCategory::Done => ClosedAs::Done,
4586            StatusCategory::Cancelled => ClosedAs::Cancelled,
4587            _ => return None,
4588        };
4589        let wanted = self.target(kind, closed_as.category()).option()?;
4590        if option.is_some_and(|option| option.eq_ignore_ascii_case(wanted)) {
4591            return None;
4592        }
4593        Some((closed_as, wanted))
4594    }
4595}
4596
4597/// The category a closed issue reads as, from the reason it was closed with.
4598///
4599/// `COMPLETED`, and no reason at all, is finished work; `NOT_PLANNED` and `DUPLICATE` are both
4600/// work nobody will do here — a duplicate's work is the other issue's — and any other reason
4601/// is one this source cannot read a category from.
4602fn closed_category(reason: Option<&str>) -> StatusCategory {
4603    match reason {
4604        None | Some("COMPLETED") => StatusCategory::Done,
4605        Some("NOT_PLANNED" | "DUPLICATE") => StatusCategory::Cancelled,
4606        Some(_) => StatusCategory::Unknown,
4607    }
4608}
4609
4610impl BoardStatuses {
4611    /// For each kind, the option names it maps a category to that `existing` lacks, ignoring
4612    /// case; a kind lacking none is left out.
4613    fn missing_by_kind(&self, existing: &[StatusOption]) -> Vec<KindMissing> {
4614        STATUS_KINDS
4615            .into_iter()
4616            .filter_map(|kind| {
4617                let missing: Vec<String> = self
4618                    .targets(kind)
4619                    .iter()
4620                    .filter_map(StatusTarget::option)
4621                    .filter(|wanted| {
4622                        !existing
4623                            .iter()
4624                            .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
4625                    })
4626                    .map(str::to_owned)
4627                    .collect();
4628                (!missing.is_empty()).then_some(KindMissing { kind, missing })
4629            })
4630            .collect()
4631    }
4632}
4633
4634impl StatusTarget {
4635    /// The board option this target selects, or `None` for an unmapped one.
4636    fn option(&self) -> Option<&str> {
4637        match self {
4638            Self::Column(name) | Self::Terminal(name, _) => Some(name.as_str()),
4639            Self::Disabled(_) => None,
4640        }
4641    }
4642}
4643
4644// llmlint: ignore-block[comments_earn_their_place, contracts_have_one_source_or_a_drift_gate] Every `createIssue` names one of these, and which one is the rule — a reader who reaches the type from `create_and_file_issue` gets the rule in one sentence here without the method's refusals, which stay on `creation_target`, the rule's one executable source; `tests/plugin.rs` drives every arm of it against the loopback board.
4645/// One repository this source can create an issue in, as `owner/name`.
4646///
4647/// Every `createIssue` this source sends names one of these: the item's own single
4648/// `repositories` entry — on a source declared private, only when it reads private — else
4649/// its parent project issue's repository, else the configured
4650/// [`GitHubProjectsConfig::repository`]. [`GitHubProjectsSource::creation_target`] makes
4651/// that choice and says what it refuses before `createIssue`.
4652// llmlint: ignore-end[comments_earn_their_place, contracts_have_one_source_or_a_drift_gate]
4653#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
4654#[serde(try_from = "String", into = "String")]
4655struct RepositoryTarget {
4656    owner: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only after `owner/name` validation in `new`.
4657    name: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only after `owner/name` validation in `new`.
4658}
4659
4660impl RepositoryTarget {
4661    fn parse(value: &str) -> Result<Self, SourceError> {
4662        let (owner, name) = value.split_once('/').ok_or_else(|| SourceError::Config {
4663            message: format!(
4664                "repository must be spelled owner/name; {value:?} names no repository"
4665            ),
4666        })?;
4667        if !valid_github_owner(owner) || !valid_github_repository_name(name) {
4668            return Err(SourceError::Config {
4669                message: format!(
4670                    "repository must be spelled owner/name with a GitHub login and one \
4671                     repository name; {value:?} is not"
4672                ),
4673            });
4674        }
4675        Ok(Self {
4676            owner: owner.to_owned(),
4677            name: name.to_owned(),
4678        })
4679    }
4680
4681    /// The one host whose repositories this source creates issues in, spelled once: it is
4682    /// what [`Self::origin`] renders and what [`Self::from_origin`] accepts.
4683    const HOST: &str = "github.com";
4684
4685    fn origin(&self) -> String {
4686        format!("{}/{}/{}", Self::HOST, self.owner, self.name)
4687    }
4688
4689    /// The repository a normalized origin names, or why it is none this source can create
4690    /// an issue in: another host, or more or fewer than `owner/name` under this one.
4691    fn from_origin(origin: &Repository) -> Result<Self, String> {
4692        let not_here = || {
4693            format!(
4694                "{} is not a {}/owner/name repository",
4695                origin.as_str(),
4696                Self::HOST
4697            )
4698        };
4699        let (host, rest) = origin.as_str().split_once('/').ok_or_else(not_here)?;
4700        if host != Self::HOST {
4701            return Err(not_here());
4702        }
4703        Self::parse(rest).map_err(|_| not_here())
4704    }
4705
4706    fn slug(&self) -> String {
4707        format!("{}/{}", self.owner, self.name)
4708    }
4709}
4710
4711/// Read back from a kept context as the `owner/name` it was written as, refused unless
4712/// [`RepositoryTarget::parse`] takes it.
4713impl TryFrom<String> for RepositoryTarget {
4714    type Error = String;
4715
4716    fn try_from(slug: String) -> Result<Self, Self::Error> {
4717        Self::parse(&slug).map_err(|error| error.to_string())
4718    }
4719}
4720
4721impl From<RepositoryTarget> for String {
4722    fn from(target: RepositoryTarget) -> Self {
4723        target.slug()
4724    }
4725}
4726
4727/// How long GitHub's issue search may go on missing a comment after it was made or edited,
4728/// which a read of the comments made since an instant sets its watermark back by: four times the
4729/// thirty seconds the credentialed lane has watched it lag.
4730pub const COMMENT_SEARCH_LAG: std::time::Duration = std::time::Duration::from_secs(120);
4731
4732/// A source which reads GitHub afresh for every operation.
4733pub struct GitHubProjectsSource {
4734    /// This source's configured name, used both to tell a far end naming this source
4735    /// from one naming a system it knows nothing about, and to name the instance a
4736    /// status refusal is about.
4737    name: SourceName,
4738    owner: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after full GitHub-owner validation.
4739    project_number: u32, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after GraphQL-Int validation.
4740    repository: Option<RepositoryTarget>,
4741    /// The logins whose repositories a create may file in; empty restricts nothing.
4742    creation_owners: Vec<String>, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after each entry passes GitHub's login grammar.
4743    endpoint: Url,
4744    token: SecretString,
4745    credential_name: String, // llmlint: ignore[invalid_states_unrepresentable] Private diagnostic value constructed only after environment-name validation.
4746    statuses: BoardStatuses,
4747    /// Where each priority lands on this board, or `None` when this instance holds none.
4748    priorities: Option<PriorityMapping>,
4749    /// The metadata values this instance projects onto board text fields, in configured order.
4750    metadata_fields: Vec<MetadataField>,
4751    /// What this board's sub-issues mean.
4752    sub_issues: SubIssues,
4753    /// The link types this source mirrors as `relates-to`.
4754    link_types: onetaskgraph_plugin_api::LinkTypes,
4755    /// Whether this source's configuration opted in to assignees: every document it sends is
4756    /// then spelled by [`graphql::with_assignees`], and every task it reads carries them.
4757    assignees: bool,
4758    /// The GitHub node id of each person an assignee write of this process has named, by
4759    /// lowercased login — `None` for a login GitHub said it does not know — so a later call
4760    /// naming one sends no lookup. A write that fails, or is answered with other people, has the
4761    /// people it named forgotten when its call ends ([`Self::forgotten`]), so the next call
4762    /// naming them asks GitHub again while the rest of its own call does not.
4763    people: Mutex<BTreeMap<String, Option<String>>>,
4764    /// The node ids of the people a failed or mismatched assignee write of this call named,
4765    /// forgotten from [`Self::people`] when the call ends.
4766    forgotten: Mutex<Vec<String>>,
4767    /// GitHub's own spelling of each login this process looked up, by lowercased login: what a
4768    /// write that assigned a person reports them as, however the caller spelled them.
4769    spellings: Mutex<BTreeMap<String, String>>,
4770    /// Built on the first request rather than with the source, as [`Self::client`] says.
4771    client: std::sync::OnceLock<Client>,
4772    /// Built on the first attachment request, as [`Self::asset_client`] says.
4773    asset_client: std::sync::OnceLock<Client>,
4774    /// The markup the engine handed this source for its bodies' headings, applied to every
4775    /// visible body it composes and stripped from every one it reads back: see
4776    /// [`TaskSource::attach_body_markup`].
4777    body_markup: std::sync::OnceLock<onetaskgraph_plugin_api::SharedBodyMarkup>,
4778    /// Every item this source has created in this command, in the order it created them —
4779    /// dropped by [`TaskSource::end_command`].
4780    ///
4781    /// GitHub's `projectV2.items` is eventually consistent: an issue added to a board with
4782    /// `addProjectV2ItemById` is routinely absent from the very next read of that board, so
4783    /// a copy resolving a dependency on an item it had just created refused it as not
4784    /// found. A board read is completed from this — an item remembered here and absent from
4785    /// the read is added back, because the board really does hold it and only the read is
4786    /// behind.
4787    ///
4788    /// It is not a cache of a user's work: nothing is remembered that this process did not
4789    /// itself just write, it lives and dies with the process, and it is never consulted for
4790    /// an item this source did not create.
4791    created: Mutex<Vec<Resolved>>,
4792    /// Every item that already existed and that this source has written in this command, as
4793    /// it wrote it — dropped by [`TaskSource::end_command`].
4794    ///
4795    /// The other half of [`Self::created`], held on the same terms and for the reason a
4796    /// narrowed read needs it: an answer from GitHub's search or from the board's own field
4797    /// filter is an index behind a write this process made moments ago, so a query matching
4798    /// what this process just wrote onto an existing item would otherwise miss it. Nothing
4799    /// is remembered that this process did not itself just write.
4800    updated: Mutex<Vec<Resolved>>,
4801    /// Every issue this source has added a comment to or edited a comment of in this command
4802    /// — dropped by [`TaskSource::end_command`].
4803    ///
4804    /// A comment-activity read is narrowed by GitHub's issue search, whose `updated:` index
4805    /// lags the write that moved an issue's `updatedAt`, and neither [`Self::created`] nor
4806    /// [`Self::updated`] is moved by a comment, so an issue this process had just commented
4807    /// on was missing from such a read — or ruled out by the `updatedAt` its own record held
4808    /// from before — until the index caught up. Each id here is a candidate of every such
4809    /// search-narrowed read, and wherever it is a candidate its comments are read rather than
4810    /// it being ruled out by a stale `updatedAt`; that read is of the issue's own node, so it
4811    /// is current. It holds ids alone: nothing of a comment is remembered. A comment another
4812    /// process wrote is still found only once the index has it.
4813    commented: Mutex<Vec<NativeId>>,
4814    /// How fast this source writes, and how long it waits out a refusal.
4815    pacing: Pacing,
4816    /// When the last content-creating mutation finished, or the moment the furthest-out
4817    /// reserved slot releases the next one, whichever is later — so the one after it can be
4818    /// spaced from that, when `pacing.min_mutation_interval_ms` asks for a spacing. See
4819    /// [`GitHubProjectsSource::paced`] for why completion rather than release is what it is
4820    /// measured from.
4821    last_mutation: Mutex<Option<Duration>>,
4822    /// The `Date` GitHub stated on the last answer this source read: its own time, which the
4823    /// watermark of a comment read is set back from. See [`TaskSource::served_at`].
4824    last_served: Mutex<Option<DateTime<Utc>>>,
4825    /// GitHub's secondary windows as this source has charged them; see the `pacing` module.
4826    windows: Mutex<pacing::Windows>,
4827    /// The tasks a project holds, as a copy's batched read of the project and every one of them
4828    /// found them — see [`TaskSource::read_ahead_for_copy`] — for the length of one command, so
4829    /// a listing of that project's tasks is answered without a read of its own.
4830    task_children: Mutex<BTreeMap<NativeId, Vec<Resolved>>>,
4831    /// The web address of each issue this source created in the current command, as its
4832    /// `createIssue` answered it — what [`TaskSource::written_location`] answers, without a
4833    /// request.
4834    written: Mutex<BTreeMap<NativeId, String>>,
4835    /// What a copy has held back of the items it created, between
4836    /// [`TaskSource::begin_deferred_writes`] and [`TaskSource::finish_writes`] — `None` while
4837    /// nothing is being held back, when every write lands whole as it is made.
4838    deferred: Mutex<Option<Deferred>>,
4839    /// Each existing issue's update held back while writes are, in the order it was made: sent
4840    /// together by [`Self::send_held_updates`] before any other request goes out, so nothing
4841    /// this source sends or reads ever sees the board without them.
4842    held_updates: Mutex<Vec<HeldUpdate>>,
4843    /// The first page of comments a comment-activity read read of each candidate it confirmed,
4844    /// held for the one comment listing of that task that follows in this command — see
4845    /// `batch::hold_comment_pages`.
4846    held_comments: Mutex<BTreeMap<NativeId, Page<Comment>>>,
4847    /// The board field writes and issue updates a batch of targeted updates is holding back,
4848    /// while one runs — see `batch::TaskWrites`.
4849    task_writes: Mutex<Option<batch::TaskWrites>>,
4850    /// The change token each task a targeted update wrote in the current command holds after
4851    /// that write, by the task's id with its board item's id — spelled from the write's own
4852    /// last response, or from the read made right after it where no response showed the whole
4853    /// issue: what [`TaskSource::written_task`] answers as its `version`. Any later mutation
4854    /// naming the task or its board item drops its entry before it is sent, so an entry is
4855    /// never one write behind.
4856    /// A response that showed the issue whole but not every part of its token — a draft, or a
4857    /// page of labels or field values that did not end — records `None`, which a read would
4858    /// not improve on.
4859    written_tokens: Mutex<BTreeMap<NativeId, (String, Option<String>)>>,
4860    clock: SharedClock,
4861    /// Whether the configuration declares this source private, as
4862    /// [`TaskSource::declare_visibility`] told it: what decides where a new issue whose one
4863    /// named repository reads public is created — see [`Self::creation_rule`].
4864    declared_private: std::sync::atomic::AtomicBool,
4865    numeric_repositories: tokio::sync::Mutex<BTreeMap<RepositoryTarget, std::num::NonZeroU64>>,
4866    /// The board as this process last read it, for the length of one command — dropped by
4867    /// [`TaskSource::end_command`].
4868    ///
4869    /// A copy of a project used to re-read the whole board, paged, before writing each of
4870    /// its items, which is by far the largest part of a copy's request count and none of
4871    /// its work. Nothing else changes this board while a command runs — this source's own
4872    /// writes are the only writer — so one read answers them all.
4873    ///
4874    /// It is not a store of a user's work and it is not the cache the no-persistence
4875    /// invariant forbids: it lives and dies with the process exactly as `created` does,
4876    /// nothing is written down, and [`Self::board`] still completes it from `created`, so
4877    /// an item this command created and then depends on resolves whether or not GitHub's
4878    /// own eventually-consistent read has caught up. A write to an item already on the
4879    /// board updates the entry here too, so what this holds is the last read plus this
4880    /// process's own writes rather than a snapshot taken before them.
4881    board_cache: Mutex<Option<Board>>,
4882    /// Every issue this board's own search reported, for the length of one command — dropped
4883    /// by [`TaskSource::end_command`].
4884    ///
4885    /// The second half of a board read, and cached for the same reason and on the same
4886    /// terms as the first: it lives and dies with the process, nothing is written down, and
4887    /// a write this process makes updates the entry here exactly as it updates the one in
4888    /// [`Self::board_cache`]. One read answers every question a command asks, so a command
4889    /// that lists this board's projects and its tasks pays for one search rather than two.
4890    search_cache: Mutex<Option<Vec<Resolved>>>,
4891    /// What each narrowed question GitHub was asked answered, keyed by that question, for
4892    /// the length of one command — dropped by [`TaskSource::end_command`].
4893    ///
4894    /// The narrowed counterpart of [`Self::search_cache`], held on the same terms: it lives
4895    /// and dies with the process, nothing is written down, a write this process makes
4896    /// updates the entry here as it updates the other two, and every answer is completed
4897    /// with this process's own writes each time it is given. A command that asks the same
4898    /// narrowed question twice — a wait polling for its own items, a listing repeated after a
4899    /// write — pays for it once, which is what the whole-board read it replaced gave it.
4900    narrowed_cache: Mutex<BTreeMap<String, Vec<Resolved>>>,
4901    search_next: Mutex<BTreeMap<String, Option<String>>>,
4902    /// Records already resolved in this command, reused by writes and for comment identity.
4903    /// Explicit item reads still reach GitHub. Nothing is persisted, and
4904    /// [`TaskSource::end_command`] drops every record, so a write in the next command reads
4905    /// its item as a person has since left it.
4906    resolved_cache: Mutex<BTreeMap<NativeId, Resolved>>,
4907    /// What [`TaskSource::read_ahead_for_copy`] read, by id — `None` for an id that read
4908    /// answered as holding nothing — each taken by the next read of that item by id and by
4909    /// nothing else, dropped by any mutation naming it, and cleared by
4910    /// [`TaskSource::end_command`]. So a read answered from it is the copy's own
4911    /// read-before-write, made in the same request as the others' rather than on its own.
4912    read_ahead: Mutex<BTreeMap<NativeId, Option<Resolved>>>,
4913    /// The origins [`TaskSource::read_ahead_origins_for_copy`] was asked about and has not sent
4914    /// yet: held for the [`TaskSource::read_ahead_for_copy`] that follows it, which sends them —
4915    /// beside the members of the one project it names, when it names one — or for the next
4916    /// request this source makes, whichever comes first.
4917    pending_origins: Mutex<Vec<String>>,
4918    /// Each project's members as a lookup carrying them read them in this command, trimmed to
4919    /// their classification and repositories, taken by [`TaskSource::member_classifications`]
4920    /// of that project and by nothing else, and cleared by [`TaskSource::end_command`].
4921    member_classes: Mutex<BTreeMap<NativeId, Vec<MemberClass>>>,
4922    /// Every item a listing of one project's members carried whole in this command — the
4923    /// project issue and each of its sub-issues — kept for [`TaskSource::read_ahead_for_copy`]
4924    /// alone, which takes each one it is asked for into [`Self::read_ahead`] instead of reading
4925    /// it again. No other read is answered from it, so a read by id outside a copy's
4926    /// read-before-write reads GitHub as it always did. Dropped by any mutation naming an
4927    /// item, and cleared by [`TaskSource::end_command`].
4928    carried: Mutex<BTreeMap<NativeId, Resolved>>,
4929    /// Items an issue read by reference reached, held for the one status write each was read
4930    /// for and taken out by it alone — see [`Self::take_held`] — because that read selects only
4931    /// what such a write needs. Dropped by [`TaskSource::end_command`].
4932    held_cache: Mutex<BTreeMap<NativeId, Resolved>>,
4933    /// Each project's sub-issues as GitHub answered them, keyed by the selector they were
4934    /// asked for under, with the project that selector named — for the length of one command,
4935    /// dropped by [`TaskSource::end_command`].
4936    ///
4937    /// A caller pages through a project's tasks one engine page at a time, and every page
4938    /// is cut from the whole list of them, so without this each page walked every
4939    /// [`graphql::SUB_ISSUES`] page again and a project of `n` listing pages cost `n²`
4940    /// requests to read once. Held on the terms [`Self::narrowed_cache`] is: it lives and
4941    /// dies with the process, nothing is written down, a write this process makes updates or
4942    /// removes the entry here as it does there, and every answer is completed with this
4943    /// process's own writes each time it is given.
4944    children_cache: Mutex<ProjectChildren>,
4945    /// The board's own id and field definitions as this process last read them on their
4946    /// own, for the length of one command — dropped by [`TaskSource::end_command`].
4947    ///
4948    /// What a write needs of the board and its item does not say, read once per command
4949    /// rather than once per item written, on the terms [`Self::board_cache`] is held on: it
4950    /// lives and dies with the process and nothing is written down. It holds no item and so
4951    /// can answer no question about one — see [`Self::board_fields`].
4952    fields_cache: Mutex<Option<BoardFields>>,
4953    /// Each destination repository's node id, resolved once per repository
4954    /// rather than per issue created.
4955    ///
4956    /// A repository's node id does not change, and re-reading it for every issue of a copy
4957    /// spent one request per item on an answer this source already had. It is a map rather
4958    /// than one entry because a copy files each item in the repository its own
4959    /// `repositories` field names, so a plan across five repositories asks GitHub five
4960    /// times and not once per item.
4961    repository_cache: Mutex<BTreeMap<RepositoryTarget, String>>,
4962    /// What every request this source sends is recorded into.
4963    ///
4964    /// Ordinary code path, not a mode: [`Self::send_once`] records into it at the one place
4965    /// a request leaves this crate, so nothing has to be switched on for a session to be
4966    /// counted. It is shared rather than owned so a caller accounting for a whole session —
4967    /// its own schema verification, board lookups, residue sweep and cleanup beside this
4968    /// source's reads and writes — adds up one accounting instead of two. See
4969    /// [`accounting`] for what a record carries and what a session's spend is and is not.
4970    ledger: Arc<Accounting>,
4971    /// What [`expected`] holds for a write the store's cache expects: the journal while one is
4972    /// open, the issues primed from the cache, and the comments known on each.
4973    expected: expected::Held,
4974    /// What [`projection`] holds for a producer's projection: a kept placement awaiting its
4975    /// setup-context token, and where the last create was placed.
4976    projection: projection::Held,
4977}
4978
4979/// The board item a single field update's answer names, refused unless it is `item_id`.
4980fn field_update_item<'a>(data: &'a Value, item_id: &str) -> Result<&'a Value, SourceError> {
4981    let returned = data
4982        .pointer("/updateProjectV2ItemFieldValue/projectV2Item")
4983        .ok_or_else(|| SourceError::Malformed {
4984            message: "GitHub field update returned no project item".into(),
4985        })?;
4986    if required_str(returned, "id")? != item_id {
4987        return Err(SourceError::Malformed {
4988            message: "GitHub field update returned the wrong project item".into(),
4989        });
4990    }
4991    Ok(returned)
4992}
4993
4994/// GitHub's closed single-select color vocabulary.
4995#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
4996#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
4997pub enum StatusOptionColor {
4998    /// Gray.
4999    Gray,
5000    /// Blue.
5001    Blue,
5002    /// Green.
5003    Green,
5004    /// Yellow.
5005    Yellow,
5006    /// Purple.
5007    Purple,
5008    /// Red.
5009    Red,
5010    /// Orange.
5011    Orange,
5012    /// Pink.
5013    Pink,
5014}
5015
5016/// Whether a guarded board setup — of the fields, or of the Status options alone — plans or
5017/// applies its additions.
5018#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5019pub enum SetupMode {
5020    /// Read without mutation.
5021    Plan,
5022    /// Apply and verify.
5023    Apply,
5024}
5025
5026/// The name [`SetupMode`] had when Status was the one field set up, kept so a caller written
5027/// against it goes on compiling.
5028pub type StatusOptionsMode = SetupMode;
5029
5030/// The explicit result of the requested operation.
5031#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5032#[serde(rename_all = "kebab-case")]
5033pub enum StatusOptionsOutcome {
5034    /// A read-only plan.
5035    Planned,
5036    /// Apply found nothing missing.
5037    Unchanged,
5038    /// Additions were applied and verified.
5039    Applied,
5040}
5041
5042/// A GitHub single-select option's opaque GraphQL node identifier.
5043#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5044#[serde(transparent)]
5045pub struct StatusOptionId(#[schemars(length(min = 1))] String);
5046
5047impl TryFrom<String> for StatusOptionId {
5048    type Error = String;
5049
5050    fn try_from(id: String) -> Result<Self, Self::Error> {
5051        if id.trim().is_empty() {
5052            return Err("a GitHub Status option id cannot be blank".to_owned());
5053        }
5054        Ok(Self(id))
5055    }
5056}
5057
5058/// One existing or proposed option in a guarded Status-field update.
5059#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5060pub struct StatusOption {
5061    /// GitHub's stable id.
5062    pub id: StatusOptionId,
5063    /// The visible option name.
5064    pub name: ColumnName,
5065    /// GitHub's single-select color token.
5066    pub color: StatusOptionColor,
5067    /// The option description, including an empty one.
5068    pub description: String,
5069}
5070
5071/// One board item's Status assignment, retained as recovery data.
5072#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5073pub struct StatusAssignment {
5074    /// The project item id whose assignment this is.
5075    // llmlint: ignore[invalid_states_unrepresentable] This opaque GraphQL node ID is
5076    // carried verbatim as operator recovery data; introducing a semantic type would claim
5077    // validation rules GitHub does not publish and no operation here interprets.
5078    pub item_id: String,
5079    /// The selected option, absent when the item has no status.
5080    #[serde(skip_serializing_if = "Option::is_none")]
5081    pub option: Option<AssignedStatusOption>,
5082}
5083
5084/// The inseparable id and name of an assigned option.
5085#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5086pub struct AssignedStatusOption {
5087    /// GitHub's stable id.
5088    pub id: StatusOptionId,
5089    /// The visible name.
5090    pub name: ColumnName,
5091}
5092
5093/// The plan and verified outcome of reconciling configured Status options.
5094#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5095pub struct StatusOptionsReport {
5096    /// The configured source name.
5097    pub source: SourceName,
5098    /// Configured option names absent before the operation.
5099    // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a
5100    // `ColumnName` and has therefore already passed its nonblank validation; retaining the
5101    // serialized string here preserves the report's intentionally simple public contract.
5102    pub missing: Vec<String>,
5103    /// What the requested operation did.
5104    pub outcome: StatusOptionsOutcome,
5105    /// The complete option list observed before any mutation.
5106    pub existing: Vec<StatusOption>,
5107}
5108
5109#[derive(Debug, Clone, PartialEq, Eq)]
5110struct StatusSnapshot {
5111    // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
5112    // passed back as the mutation's project identity; a newtype could enforce no stronger
5113    // invariant because GitHub publishes no grammar for it.
5114    board_id: String,
5115    // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
5116    // passed back as the mutation's field identity; a newtype could enforce no stronger
5117    // invariant because GitHub publishes no grammar for it.
5118    field_id: String,
5119    options: Vec<StatusOption>,
5120    assignments: Vec<StatusAssignment>,
5121}
5122
5123/// The name of the board field a status is held in.
5124const STATUS_FIELD: &str = "Status";
5125
5126/// Every item's value of each field `report` names, as it stood before the setup wrote
5127/// anything — what a person puts back when the setup is refused part way.
5128fn recovery(report: &FieldsReport, before: &BoardSnapshot) -> Result<String, SourceError> {
5129    let assignments: BTreeMap<&str, Vec<StatusAssignment>> = report
5130        .fields
5131        .iter()
5132        .map(|field| (field.field.name(), before.assignments(field.field)))
5133        .collect();
5134    serde_json::to_string_pretty(&assignments).map_err(|error| SourceError::Malformed {
5135        message: format!("cannot render the pre-write field recovery snapshot: {error}"),
5136    })
5137}
5138
5139/// One board field the guarded setup reads and writes — every one it reads, and the only
5140/// ones it writes.
5141#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, schemars::JsonSchema)]
5142pub enum BoardField {
5143    /// The single-select `Status` field every instance's `status_mapping` resolves into.
5144    Status,
5145    /// The single-select `Priority` field an instance's `priority_mapping` resolves into.
5146    Priority,
5147}
5148
5149impl BoardField {
5150    /// The field's name on the board.
5151    #[must_use]
5152    pub const fn name(self) -> &'static str {
5153        match self {
5154            Self::Status => STATUS_FIELD,
5155            Self::Priority => PRIORITY_FIELD,
5156        }
5157    }
5158
5159    /// The field a board calls `name`, or `None` for one this setup does not own.
5160    fn named(name: &str) -> Option<Self> {
5161        [Self::Status, Self::Priority]
5162            .into_iter()
5163            .find(|field| field.name() == name)
5164    }
5165}
5166
5167/// What the guarded setup did to one field.
5168#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5169#[serde(rename_all = "kebab-case")]
5170pub enum FieldOutcome {
5171    /// A read-only plan.
5172    Planned,
5173    /// Apply found the field there with every configured option.
5174    Unchanged,
5175    /// Missing options were added to the field that was there, and verified.
5176    Applied,
5177    /// The field was not there; it was created holding the configured options, and verified.
5178    Created,
5179}
5180
5181/// One field's plan, or its verified outcome.
5182#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5183pub struct FieldReport {
5184    /// Which field.
5185    pub field: BoardField,
5186    /// Whether the board had the field before the operation.
5187    // llmlint: ignore[invalid_states_unrepresentable] `exists` beside `outcome` is the report's
5188    // wire shape as its consumer's contract fixes it — `{"field", "exists", "missing",
5189    // "outcome", "existing"}` — so folding one into the other would change a published JSON
5190    // shape. The contradictory pairings cannot be built: `GitHubProjectsSource::fields` is the
5191    // one constructor, and it derives `outcome` from `exists` in one match.
5192    pub exists: bool,
5193    /// Configured option names the field lacked before the operation — every one of them,
5194    /// in the order a new field lists them, when the field was not there at all.
5195    // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a validated
5196    // mapping name and has therefore already passed its nonblank validation; the serialized
5197    // string is the report's intentionally simple public contract, as `StatusOptionsReport`'s is.
5198    pub missing: Vec<String>,
5199    /// For the `Status` field, which item kind each missing name is configured for: one
5200    /// entry per kind `status_mapping` names a missing option for, task before project, each
5201    /// listing that kind's missing names in category order. A name both kinds use is in
5202    /// both. Empty — and left out of the JSON — when nothing is missing, and always for
5203    /// `Priority`, which only a task holds.
5204    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5205    // Kept in the schema as `"default": []` although the JSON leaves an empty list out, so
5206    // both SDKs model an absent `kinds` as an empty list rather than as `null`.
5207    #[schemars(!skip_serializing_if)]
5208    pub kinds: Vec<KindMissing>,
5209    /// What the requested operation did.
5210    pub outcome: FieldOutcome,
5211    /// The field's complete option list observed before any mutation; empty when the field
5212    /// was not there.
5213    pub existing: Vec<StatusOption>,
5214}
5215
5216/// The `Status` option names one item kind's `status_mapping` names that the field lacked.
5217#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5218pub struct KindMissing {
5219    /// The kind these names are configured for.
5220    pub kind: ItemKind,
5221    /// The names that kind maps a category to and the field lacked, in category order.
5222    // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a validated
5223    // mapping name, as `FieldReport::missing`'s do, and the serialized string is the report's
5224    // intentionally simple public contract.
5225    pub missing: Vec<String>,
5226}
5227
5228/// The plan and verified outcome of setting up every field a source's configuration names.
5229#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5230pub struct FieldsReport {
5231    /// The configured source name.
5232    pub source: SourceName,
5233    /// `Status`, always, and `Priority` when the source sets `priority_mapping`.
5234    // llmlint: ignore[invalid_states_unrepresentable] A list is the report's wire shape as its
5235    // consumer's contract fixes it — `{"source", "fields": [...]}` — so a struct with one member
5236    // per field would change a published JSON shape. The states the list could hold and the
5237    // contract forbids cannot be built: `GitHubProjectsSource::fields` is the one constructor,
5238    // and it pushes `Status` first and exactly once, then `Priority` exactly when configured.
5239    pub fields: Vec<FieldReport>,
5240    /// Each board text field the source's `metadata_fields` projects a value onto, in
5241    /// configured order. Empty — and left out of the JSON — when it projects none.
5242    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5243    // Kept in the schema as `"default": []` although the JSON leaves an empty list out, so
5244    // both SDKs model an absent list as an empty one rather than as `null`.
5245    #[schemars(!skip_serializing_if)]
5246    pub metadata_fields: Vec<MetadataFieldReport>,
5247}
5248
5249/// The type of a board field that is not a text field, as GitHub names it — its `dataType`, or
5250/// its GraphQL type when it has none — which is what a projected field's conflict reports.
5251///
5252/// Never empty, never beginning with whitespace, and never `TEXT`: a text field of that name is
5253/// no conflict.
5254// The schema states that rule as `NON_TEXT_FIELD_TYPE_PATTERN`, so a generated SDK model
5255// refuses exactly what `try_from` below does.
5256#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5257#[serde(transparent)]
5258pub struct NonTextFieldType(#[schemars(regex(pattern = NON_TEXT_FIELD_TYPE_PATTERN))] String);
5259
5260/// What a [`NonTextFieldType`] may be, as the emitted schema states it: a first character that
5261/// is not whitespace, and anything but exactly `TEXT` — spelled without a lookahead, which
5262/// neither SDK's validator can be relied on to support.
5263const NON_TEXT_FIELD_TYPE_PATTERN: &str =
5264    r"^(?:[^T\s]|T(?:[^E]|$)|TE(?:[^X]|$)|TEX(?:[^T]|$)|TEXT[\s\S])";
5265
5266impl TryFrom<String> for NonTextFieldType {
5267    type Error = String;
5268
5269    fn try_from(kind: String) -> Result<Self, Self::Error> {
5270        if kind.is_empty() || kind.starts_with(char::is_whitespace) {
5271            return Err("a board field's type cannot be blank or begin with whitespace".to_owned());
5272        }
5273        if kind == "TEXT" {
5274            return Err("a TEXT field is no conflict for a projected text field".to_owned());
5275        }
5276        Ok(Self(kind))
5277    }
5278}
5279
5280impl std::fmt::Display for NonTextFieldType {
5281    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5282        formatter.write_str(&self.0)
5283    }
5284}
5285
5286/// One projected metadata text field's plan, or its verified outcome.
5287///
5288/// The setup creates a missing one as a text field and never alters a field that is there:
5289/// a same-named field of another type is reported in `conflict` and left as it is.
5290#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5291pub struct MetadataFieldReport {
5292    /// The board field's name.
5293    pub field: String, // llmlint: ignore[invalid_states_unrepresentable] Copied from a configuration entry `MetadataField::resolve` already validated; the serialized string is the report's intentionally simple public contract, as `FieldReport::missing`'s names are.
5294    /// The metadata key the value is read from.
5295    pub key: String, // llmlint: ignore[invalid_states_unrepresentable] As `field`: a validated configuration value reported back as written.
5296    /// The object keys walked inside that key's value; empty for the key's own value.
5297    pub path: Vec<String>,
5298    /// Whether the board had a text field of that name before the operation.
5299    // llmlint: ignore[invalid_states_unrepresentable] `exists` beside `outcome` mirrors `FieldReport`'s published shape; `GitHubProjectsSource::fields` is the one constructor and derives `outcome` from `exists` and `conflict` in one match.
5300    pub exists: bool,
5301    /// The type of a field of that name that is not a text field, which the setup leaves as
5302    /// it is; absent — and left out of the JSON — when there is none.
5303    #[serde(default, skip_serializing_if = "Option::is_none")]
5304    pub conflict: Option<NonTextFieldType>,
5305    /// What the requested operation did: `planned`; `created` for a field that was not
5306    /// there; `unchanged` for one that was, and for a conflict, which is never changed.
5307    pub outcome: FieldOutcome,
5308}
5309
5310/// Which options one field is configured with, in the order a new field would list them.
5311struct FieldPlan {
5312    field: BoardField,
5313    wanted: Vec<String>,
5314}
5315
5316/// One single-select field as the guarded setup snapshots it.
5317#[derive(Debug, Clone, PartialEq, Eq)]
5318struct SnapshotField {
5319    // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
5320    // passed back as the mutation's field identity; a newtype could enforce no stronger
5321    // invariant because GitHub publishes no grammar for it.
5322    field_id: String,
5323    options: Vec<StatusOption>,
5324}
5325
5326/// Every single-select field of a board and every item's value of each.
5327#[derive(Debug, Clone, PartialEq, Eq)]
5328struct BoardSnapshot {
5329    // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
5330    // passed back as the mutation's project identity; a newtype could enforce no stronger
5331    // invariant because GitHub publishes no grammar for it.
5332    board_id: String,
5333    fields: BTreeMap<BoardField, SnapshotField>,
5334    /// Each board item's id, and its value of each field this setup owns that it holds one of.
5335    items: Vec<(String, BTreeMap<BoardField, AssignedStatusOption>)>,
5336}
5337
5338impl BoardSnapshot {
5339    /// Every item's value of `field`, in board order — the recovery data a drift refusal
5340    /// carries.
5341    fn assignments(&self, field: BoardField) -> Vec<StatusAssignment> {
5342        self.items
5343            .iter()
5344            .map(|(item_id, values)| StatusAssignment {
5345                item_id: item_id.clone(),
5346                option: values.get(&field).cloned(),
5347            })
5348            .collect()
5349    }
5350}
5351
5352impl GitHubProjectsSource {
5353    /// `content` as this source sends it, with the markup the engine handed it applied.
5354    fn marked(&self, content: &str) -> String {
5355        match self.body_markup.get() {
5356            Some(markup) if !content.is_empty() => markup.written(content),
5357            _ => content.to_owned(),
5358        }
5359    }
5360
5361    /// The visible body and the metadata slot of `body` as [`metadata_body`] splits them,
5362    /// the visible body without the markup [`Self::marked`] applies.
5363    fn visible(
5364        &self,
5365        body: Option<String>,
5366    ) -> Result<(Option<String>, BTreeMap<String, Value>), SourceError> {
5367        let (visible, slot) = metadata_body(body)?;
5368        Ok((
5369            match (visible, self.body_markup.get()) {
5370                (Some(visible), Some(markup)) => {
5371                    Some(markup.read(&visible)).filter(|read| !read.is_empty())
5372                }
5373                (visible, _) => visible,
5374            },
5375            slot,
5376        ))
5377    }
5378
5379    /// Report missing configured Status options and, when `apply` is true, add them with
5380    /// a whole-list mutation that preserves every existing id and verifies the result.
5381    ///
5382    /// # Errors
5383    ///
5384    /// Refuses a board without a single-select `Status` field. A post-write difference in
5385    /// any pre-existing option id or item assignment is refused with the complete pre-write
5386    /// assignment snapshot in the diagnostic for recovery.
5387    // llmlint: ignore[changed_behavior_has_e2e] The CLI journeys cover plan, no-op apply,
5388    // successful mutation, both drift refusals, source selection, missing Status, casing,
5389    // and paging. Transport errors remain the shared `graphql` boundary's behavior rather
5390    // than a new status-options behavior, and the pinned-schema test prevents valid GitHub
5391    // responses from entering the defensive malformed-response branches below.
5392    pub async fn status_options(
5393        &self,
5394        mode: StatusOptionsMode,
5395    ) -> Result<StatusOptionsReport, SourceError> {
5396        let before = self.status_snapshot().await?;
5397        // A terminal category's option is as configured as an open one's: a terminal
5398        // write validates it before closing and refuses when the board lacks it. Both
5399        // kinds' names are options of the one field, so both are asked for.
5400        let missing = self
5401            .statuses
5402            .wanted()
5403            .into_iter()
5404            .filter(|wanted| {
5405                !before
5406                    .options
5407                    .iter()
5408                    .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
5409            })
5410            .collect::<Vec<_>>();
5411        let report = StatusOptionsReport {
5412            source: self.name.clone(),
5413            missing: missing.clone(),
5414            outcome: match (mode, missing.is_empty()) {
5415                (StatusOptionsMode::Plan, _) => StatusOptionsOutcome::Planned,
5416                (StatusOptionsMode::Apply, true) => StatusOptionsOutcome::Unchanged,
5417                (StatusOptionsMode::Apply, false) => StatusOptionsOutcome::Applied,
5418            },
5419            existing: before.options.clone(),
5420        };
5421        if mode == StatusOptionsMode::Plan || missing.is_empty() {
5422            return Ok(report);
5423        }
5424        let mut options = before
5425            .options
5426            .iter()
5427            .map(|option| {
5428                json!({
5429                    "id": option.id, "name": option.name, "color": option.color,
5430                    "description": option.description,
5431                })
5432            })
5433            .collect::<Vec<_>>();
5434        options.extend(missing.iter().map(|name| {
5435            json!({
5436                "name": name, "color": "GRAY", "description": ""
5437            })
5438        }));
5439        self.graphql(
5440            graphql::STATUS_OPTIONS_UPDATE,
5441            json!({"input": {
5442                "fieldId": before.field_id,
5443                "singleSelectOptions": options,
5444            }}),
5445        )
5446        .await?;
5447        let after = self.status_snapshot().await?;
5448        let options_preserved = before
5449            .options
5450            .iter()
5451            .all(|old| after.options.iter().any(|new| new == old));
5452        let additions_present = missing.iter().all(|wanted| {
5453            after
5454                .options
5455                .iter()
5456                .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
5457        });
5458        if !options_preserved || !additions_present || after.assignments != before.assignments {
5459            let recovery = serde_json::to_string_pretty(&before.assignments).map_err(|error| {
5460                SourceError::Malformed {
5461                    message: format!("cannot render pre-write Status recovery snapshot: {error}"),
5462                }
5463            })?;
5464            return Err(SourceError::Refused {
5465                message: format!(
5466                    "GitHub changed a pre-existing Status option id, name, color or description, or an item assignment after the guarded update; the pre-write item assignment snapshot is:\n{recovery}"
5467                ),
5468            });
5469        }
5470        Ok(report)
5471    }
5472
5473    /// A fresh snapshot of the Status field and every board item's assignment of it.
5474    ///
5475    /// # Errors
5476    ///
5477    /// Refuses a board without a single-select `Status` field, and one the token cannot see.
5478    async fn status_snapshot(&self) -> Result<StatusSnapshot, SourceError> {
5479        // Status alone, as this operation has always read it: a `Priority` field is another
5480        // operation's, so nothing about it can refuse this one.
5481        let mut board = self.board_snapshot(&[BoardField::Status]).await?;
5482        let field = board
5483            .fields
5484            .remove(&BoardField::Status)
5485            .ok_or_else(|| self.no_status_field())?;
5486        Ok(StatusSnapshot {
5487            assignments: board.assignments(BoardField::Status),
5488            board_id: board.board_id,
5489            field_id: field.field_id,
5490            options: field.options,
5491        })
5492    }
5493
5494    /// The refusal a board with no `Status` field is answered with by the guarded setup.
5495    fn no_status_field(&self) -> SourceError {
5496        SourceError::Refused {
5497            message: format!("source {} board has no Status field", self.name),
5498        }
5499    }
5500
5501    // llmlint: ignore-block[changed_behavior_has_e2e] Valid snapshot shapes are exercised through
5502    // the real CLI loopback journey, including pagination. The individual malformed guards
5503    // are defensive validation of a schema-pinned third-party response, not separate user
5504    // journeys; drift and missing-field failures cover the operation's recovery behavior.
5505    /// A fresh snapshot of each of the `owned` fields on the board, with its options, and of
5506    /// every board item's value of each, walked to the end of the board's items. A field not
5507    /// in `owned` is read past whatever it holds.
5508    async fn board_snapshot(&self, owned: &[BoardField]) -> Result<BoardSnapshot, SourceError> {
5509        let mut after: Option<String> = None;
5510        let mut snapshot: Option<BoardSnapshot> = None;
5511        loop {
5512            let data = self
5513                .graphql(
5514                    graphql::STATUS_OPTIONS_SNAPSHOT,
5515                    json!({
5516                        "owner": self.owner, "number": self.project_number,
5517                        "first": MAX_PAGE_SIZE, "after": after, "nestedFirst": MAX_PAGE_SIZE,
5518                    }),
5519                )
5520                .await?;
5521            let board = data
5522                .pointer("/owner/projectV2")
5523                .filter(|board| board.is_object())
5524                .ok_or_else(|| SourceError::Refused {
5525                    message: format!(
5526                        "source {} has no accessible GitHub Projects board",
5527                        self.name
5528                    ),
5529                })?;
5530            if board
5531                .pointer("/fields/pageInfo/hasNextPage")
5532                .and_then(Value::as_bool)
5533                != Some(false)
5534            {
5535                return Err(SourceError::Malformed {
5536                    message:
5537                        "GitHub project fields is incomplete or has malformed pageInfo.hasNextPage"
5538                            .into(),
5539                });
5540            }
5541            let mut fields = BTreeMap::new();
5542            // Only the fields this setup owns, by name: a node the single-select fragment did not
5543            // match carries no name, and a person's own single-select field — a `Size`, a
5544            // `Team` — is none of this setup's business, so nothing about it can refuse one. A
5545            // `Status` or `Priority` field without its options is malformed, not absent.
5546            // llmlint: ignore[boundary_inputs_validated] The field page this loop reads is validated as complete immediately above: any `fields.pageInfo.hasNextPage` other than `false` is refused as malformed before a node is read, so an incomplete page is never taken for the board's whole field set.
5547            for (owned, field) in board
5548                .pointer("/fields/nodes")
5549                .and_then(Value::as_array)
5550                .ok_or_else(|| SourceError::Malformed {
5551                    message: "GitHub project fields.nodes is not an array".into(),
5552                })?
5553                .iter()
5554                .filter_map(|field| {
5555                    let named = BoardField::named(field.get("name")?.as_str()?)?;
5556                    owned.contains(&named).then_some((named, field))
5557                })
5558            {
5559                let options = field
5560                    .get("options")
5561                    .and_then(Value::as_array)
5562                    .ok_or_else(|| SourceError::Malformed {
5563                        message: "GitHub single-select field options is not an array".into(),
5564                    })?
5565                    .iter()
5566                    .map(|option| {
5567                        Ok(StatusOption {
5568                            id: StatusOptionId::try_from(required_str(option, "id")?.to_owned())
5569                                .map_err(|message| SourceError::Malformed { message })?,
5570                            name: ColumnName::try_from(required_str(option, "name")?.to_owned())
5571                                .map_err(|message| SourceError::Malformed {
5572                                    message: format!(
5573                                        "GitHub single-select option name is invalid: {message}"
5574                                    ),
5575                                })?,
5576                            color: serde_json::from_value(
5577                                option.get("color").cloned().unwrap_or(Value::Null),
5578                            )
5579                            .map_err(|error| {
5580                                SourceError::Malformed {
5581                                    message: format!(
5582                                        "GitHub single-select option color is invalid: {error}"
5583                                    ),
5584                                }
5585                            })?,
5586                            description: optional_str(option, "description")?
5587                                .unwrap_or_default()
5588                                .to_owned(),
5589                        })
5590                    })
5591                    .collect::<Result<Vec<_>, SourceError>>()?;
5592                let snapshot = SnapshotField {
5593                    field_id: required_nonblank_str(field, "id")?.to_owned(),
5594                    options,
5595                };
5596                // A board's field names are unique, so a second one is an answer that cannot
5597                // say which field the setup would act on — refused rather than one chosen.
5598                if fields.insert(owned, snapshot).is_some() {
5599                    return Err(SourceError::Malformed {
5600                        message: format!(
5601                            "GitHub answered two {} fields for this board",
5602                            owned.name()
5603                        ),
5604                    });
5605                }
5606            }
5607            let board_id = required_nonblank_str(board, "id")?.to_owned();
5608            let current = snapshot.get_or_insert_with(|| BoardSnapshot {
5609                board_id,
5610                fields,
5611                items: Vec::new(),
5612            });
5613            let items = board
5614                .pointer("/items/nodes")
5615                .and_then(Value::as_array)
5616                .ok_or_else(|| SourceError::Malformed {
5617                    message: "GitHub project items.nodes is not an array".into(),
5618                })?;
5619            for item in items {
5620                let field_values =
5621                    item.get("fieldValues")
5622                        .ok_or_else(|| SourceError::Malformed {
5623                            message: "GitHub project item is missing fieldValues".into(),
5624                        })?;
5625                if field_values
5626                    .pointer("/pageInfo/hasNextPage")
5627                    .and_then(Value::as_bool)
5628                    != Some(false)
5629                {
5630                    return Err(SourceError::Malformed {
5631                        message: "GitHub project item fieldValues is incomplete or has malformed pageInfo.hasNextPage".into(),
5632                    });
5633                }
5634                let values = item
5635                    .pointer("/fieldValues/nodes")
5636                    .and_then(Value::as_array)
5637                    .ok_or_else(|| SourceError::Malformed {
5638                        message: "GitHub project item fieldValues.nodes is not an array".into(),
5639                    })?;
5640                let item_id = required_nonblank_str(item, "id")?;
5641                let mut assigned = BTreeMap::new();
5642                for value in values {
5643                    let Some(field) = value
5644                        .pointer("/field/name")
5645                        .and_then(Value::as_str)
5646                        .and_then(BoardField::named)
5647                        .filter(|field| owned.contains(field))
5648                    else {
5649                        continue;
5650                    };
5651                    let held = assigned.insert(
5652                        field,
5653                        AssignedStatusOption {
5654                            id: StatusOptionId::try_from(
5655                                required_str(value, "optionId")?.to_owned(),
5656                            )
5657                            .map_err(|message| SourceError::Malformed { message })?,
5658                            name: ColumnName::try_from(required_str(value, "name")?.to_owned())
5659                                .map_err(|message| SourceError::Malformed {
5660                                    message: format!(
5661                                        "GitHub assigned {} name is invalid: {message}",
5662                                        field.name()
5663                                    ),
5664                                })?,
5665                        },
5666                    );
5667                    // An item holds one value of a field, so a second one leaves no way to
5668                    // tell which it holds — and a verification or recovery built on either
5669                    // could restore the wrong one.
5670                    if held.is_some() {
5671                        return Err(SourceError::Malformed {
5672                            message: format!(
5673                                "GitHub answered two {} values for board item {item_id}",
5674                                field.name()
5675                            ),
5676                        });
5677                    }
5678                }
5679                current.items.push((item_id.to_owned(), assigned));
5680            }
5681            let page = board.get("items").ok_or_else(|| SourceError::Malformed {
5682                message: "GitHub project is missing items".into(),
5683            })?;
5684            let has_next = page
5685                .pointer("/pageInfo/hasNextPage")
5686                .and_then(Value::as_bool)
5687                .ok_or_else(|| SourceError::Malformed {
5688                    message: "GitHub project items.pageInfo.hasNextPage is not a boolean".into(),
5689                })?;
5690            if !has_next {
5691                break;
5692            }
5693            let next =
5694                required_nonblank_str(page.get("pageInfo").unwrap_or(&Value::Null), "endCursor")?;
5695            validate_cursor_progress(after.as_deref(), next)?;
5696            after = Some(next.to_owned());
5697        }
5698        snapshot.ok_or_else(|| SourceError::Malformed {
5699            message: "GitHub returned no board field snapshot".into(),
5700        })
5701    }
5702    // llmlint: ignore-end[changed_behavior_has_e2e]
5703
5704    /// Report every board field this source's configuration names and, with
5705    /// [`SetupMode::Apply`], set each up: add the options a field lacks, and create
5706    /// the `Priority` field when the board has none.
5707    ///
5708    /// The fields are `Status`, always, with the options `status_mapping` resolves to; and
5709    /// `Priority`, when `priority_mapping` is set, with its four mapped options — created in
5710    /// the order urgent, high, medium, low. An option a field already has keeps its id, name,
5711    /// color and description: the whole option list goes back with every existing id, because
5712    /// a re-minted id clears every item's value.
5713    ///
5714    /// # Errors
5715    ///
5716    /// Refuses a board without a single-select `Status` field. After an apply the board is
5717    /// read again, and a pre-existing option or any item's value of either field that moved is
5718    /// refused with the complete pre-write assignments in the diagnostic, for recovery.
5719    // llmlint: ignore[changed_behavior_has_e2e] The `sources fields` journeys drive plan,
5720    // unchanged apply, a created field, an added option to each field, drift refusal, a board
5721    // with no Status field and a non-github-projects source through the compiled CLI against
5722    // the loopback board. Transport errors are the shared `graphql` boundary's behavior.
5723    pub async fn fields(&self, mode: SetupMode) -> Result<FieldsReport, SourceError> {
5724        let owned: Vec<BoardField> = if self.priorities.is_some() {
5725            vec![BoardField::Status, BoardField::Priority]
5726        } else {
5727            vec![BoardField::Status]
5728        };
5729        let before = self.board_snapshot(&owned).await?;
5730        let mut plans = vec![FieldPlan {
5731            field: BoardField::Status,
5732            wanted: self.statuses.wanted(),
5733        }];
5734        if !before.fields.contains_key(&BoardField::Status) {
5735            return Err(self.no_status_field());
5736        }
5737        if let Some(mapping) = &self.priorities {
5738            plans.push(FieldPlan {
5739                field: BoardField::Priority,
5740                wanted: mapping.names().map(str::to_owned).collect(),
5741            });
5742        }
5743        // The snapshot reads single-select fields alone, so a field it did not find may still
5744        // be on the board under the name, of another type: creating one beside it would fail
5745        // part way, or leave two fields of one name. Asked of the board's own field list, and
5746        // only when a field is missing.
5747        if plans
5748            .iter()
5749            .any(|plan| !before.fields.contains_key(&plan.field))
5750        {
5751            let board = self.board_fields().await?;
5752            for plan in plans
5753                .iter()
5754                .filter(|plan| !before.fields.contains_key(&plan.field))
5755            {
5756                if let Some(field) = Board::field(&board.fields, plan.field.name())? {
5757                    return Err(SourceError::Refused {
5758                        message: format!(
5759                            "source {}'s board has a {} field that is not a single-select field \
5760                             (it is a {}), so it cannot hold this source's options; next: rename \
5761                             or remove that field, then run this again",
5762                            self.name,
5763                            plan.field.name(),
5764                            optional_str(field, "__typename")?.unwrap_or("field of another type")
5765                        ),
5766                    });
5767                }
5768            }
5769        }
5770        let mut reports = Vec::new();
5771        for plan in &plans {
5772            let held = before.fields.get(&plan.field);
5773            let existing = held.map(|field| field.options.clone()).unwrap_or_default();
5774            let mut missing: Vec<String> = Vec::new();
5775            for wanted in &plan.wanted {
5776                let present = existing
5777                    .iter()
5778                    .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
5779                    || missing
5780                        .iter()
5781                        .any(|named| named.eq_ignore_ascii_case(wanted));
5782                if !present {
5783                    missing.push(wanted.clone());
5784                }
5785            }
5786            let kinds = match plan.field {
5787                BoardField::Status => self.statuses.missing_by_kind(&existing),
5788                BoardField::Priority => Vec::new(),
5789            };
5790            reports.push(FieldReport {
5791                field: plan.field,
5792                exists: held.is_some(),
5793                kinds,
5794                outcome: match (mode, held.is_some(), missing.is_empty()) {
5795                    (SetupMode::Plan, _, _) => FieldOutcome::Planned,
5796                    (SetupMode::Apply, true, true) => FieldOutcome::Unchanged,
5797                    (SetupMode::Apply, true, false) => FieldOutcome::Applied,
5798                    (SetupMode::Apply, false, _) => FieldOutcome::Created,
5799                },
5800                missing,
5801                existing,
5802            });
5803        }
5804        // A projected field is a text field, which the single-select snapshot cannot see, so
5805        // it is asked of the board's own field list — and only when one is configured.
5806        let mut metadata_fields = Vec::new();
5807        if !self.metadata_fields.is_empty() {
5808            let board = self.board_fields().await?;
5809            for projection in &self.metadata_fields {
5810                let conflict = match Board::field(&board.fields, &projection.field)? {
5811                    None => None,
5812                    Some(field) => {
5813                        let typename = optional_str(field, "__typename")?;
5814                        let data_type = optional_str(field, "dataType")?;
5815                        if typename == Some("ProjectV2Field") && data_type == Some("TEXT") {
5816                            None
5817                        } else {
5818                            let named = data_type
5819                                .filter(|kind| *kind != "TEXT")
5820                                .or(typename)
5821                                .unwrap_or("field of another type");
5822                            Some(NonTextFieldType::try_from(named.to_owned()).map_err(
5823                                |message| SourceError::Malformed {
5824                                    message: format!(
5825                                        "GitHub answered the board's {} field with a type this \
5826                                         setup cannot read: {message}",
5827                                        &*projection.field
5828                                    ),
5829                                },
5830                            )?)
5831                        }
5832                    }
5833                };
5834                let exists =
5835                    conflict.is_none() && Board::field(&board.fields, &projection.field)?.is_some();
5836                metadata_fields.push(MetadataFieldReport {
5837                    field: projection.field.to_string(),
5838                    key: projection.key.to_string(),
5839                    path: projection.path.clone(),
5840                    exists,
5841                    outcome: match (mode, exists || conflict.is_some()) {
5842                        (SetupMode::Plan, _) => FieldOutcome::Planned,
5843                        (SetupMode::Apply, true) => FieldOutcome::Unchanged,
5844                        (SetupMode::Apply, false) => FieldOutcome::Created,
5845                    },
5846                    conflict,
5847                });
5848            }
5849        }
5850        let report = FieldsReport {
5851            source: self.name.clone(),
5852            fields: reports,
5853            metadata_fields,
5854        };
5855        let writes: Vec<&FieldReport> = report
5856            .fields
5857            .iter()
5858            .filter(|field| !field.missing.is_empty() || !field.exists)
5859            .collect();
5860        let creates: Vec<&MetadataFieldReport> = report
5861            .metadata_fields
5862            .iter()
5863            .filter(|field| field.outcome == FieldOutcome::Created)
5864            .collect();
5865        if mode == SetupMode::Plan || (writes.is_empty() && creates.is_empty()) {
5866            return Ok(report);
5867        }
5868        let mut landed: Vec<&str> = Vec::new();
5869        for field in &writes {
5870            let added = field
5871                .missing
5872                .iter()
5873                .map(|name| json!({"name": name, "color": "GRAY", "description": ""}));
5874            let sent = match before.fields.get(&field.field) {
5875                Some(held) => {
5876                    let mut options = held
5877                        .options
5878                        .iter()
5879                        .map(|option| {
5880                            json!({
5881                                "id": option.id, "name": option.name, "color": option.color,
5882                                "description": option.description,
5883                            })
5884                        })
5885                        .collect::<Vec<_>>();
5886                    options.extend(added);
5887                    self.graphql(
5888                        graphql::STATUS_OPTIONS_UPDATE,
5889                        json!({"input": {
5890                            "fieldId": held.field_id,
5891                            "singleSelectOptions": options,
5892                        }}),
5893                    )
5894                    .await
5895                }
5896                None => {
5897                    self.graphql(
5898                        graphql::CREATE_FIELD,
5899                        json!({"input": {
5900                            "projectId": before.board_id, "dataType": "SINGLE_SELECT",
5901                            "name": field.field.name(),
5902                            "singleSelectOptions": added.collect::<Vec<_>>(),
5903                        }}),
5904                    )
5905                    .await
5906                }
5907            };
5908            // A mutation that failed does not establish that GitHub left its field as it was,
5909            // so every failure from here on carries the recovery data a drift refusal does.
5910            match sent {
5911                Ok(_) => landed.push(field.field.name()),
5912                Err(error) => {
5913                    let changed = if landed.is_empty() {
5914                        String::new()
5915                    } else {
5916                        format!("changed the {} field and then ", landed.join(" and "))
5917                    };
5918                    return Err(SourceError::Refused {
5919                        message: format!(
5920                            "the guarded field setup {changed}failed on the {} field, which it may \
5921                             have changed part way: {error}; the pre-write item assignments \
5922                             are:\n{}",
5923                            field.field.name(),
5924                            recovery(&report, &before)?
5925                        ),
5926                    });
5927                }
5928            }
5929        }
5930        for field in &creates {
5931            let sent = self
5932                .graphql(
5933                    graphql::CREATE_FIELD,
5934                    json!({"input": {
5935                        "projectId": before.board_id, "dataType": "TEXT", "name": field.field,
5936                    }}),
5937                )
5938                .await;
5939            if let Err(error) = sent {
5940                let changed = if landed.is_empty() {
5941                    String::new()
5942                } else {
5943                    format!("changed the {} field and then ", landed.join(" and "))
5944                };
5945                return Err(SourceError::Refused {
5946                    message: format!(
5947                        "the guarded field setup {changed}failed creating the {} text field: \
5948                         {error}; run it again to create what is still missing",
5949                        field.field
5950                    ),
5951                });
5952            }
5953            landed.push(&field.field);
5954        }
5955        // The board has been written, so a verification read that fails leaves it unverified
5956        // rather than unchanged, and says what to put back.
5957        let after = match self.board_snapshot(&owned).await {
5958            Ok(after) => after,
5959            Err(error) => {
5960                return Err(SourceError::Refused {
5961                    message: format!(
5962                        "the guarded field setup changed the {} field and then could not read the \
5963                         board back to verify it: {error}; the pre-write item assignments are:\n{}",
5964                        landed.join(" and "),
5965                        recovery(&report, &before)?
5966                    ),
5967                });
5968            }
5969        };
5970        let mut moved = Vec::new();
5971        for field in &report.fields {
5972            let name = field.field.name();
5973            let now = after
5974                .fields
5975                .get(&field.field)
5976                .map(|held| held.options.as_slice())
5977                .unwrap_or_default();
5978            if !field.existing.iter().all(|old| now.contains(old)) {
5979                moved.push(format!(
5980                    "a pre-existing {name} option id, name, color or description"
5981                ));
5982            }
5983            if !field.missing.iter().all(|wanted| {
5984                now.iter()
5985                    .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
5986            }) {
5987                moved.push(format!("an added {name} option"));
5988            }
5989            if after.assignments(field.field) != before.assignments(field.field) {
5990                moved.push(format!("an item's {name} value"));
5991            }
5992        }
5993        if !creates.is_empty() {
5994            // Read afresh: the view held for this command is the one from before the creates.
5995            *self.fields_cache()? = None;
5996            let board = match self.board_fields().await {
5997                Ok(board) => board,
5998                Err(error) => {
5999                    return Err(SourceError::Refused {
6000                        message: format!(
6001                            "the guarded field setup changed the {} field and then could not \
6002                             read the board back to verify it: {error}; run it again to verify \
6003                             it, which creates nothing a second time",
6004                            landed.join(" and ")
6005                        ),
6006                    });
6007                }
6008            };
6009            for field in &creates {
6010                let text = Board::field(&board.fields, &field.field)?.is_some_and(|held| {
6011                    held.get("__typename").and_then(Value::as_str) == Some("ProjectV2Field")
6012                        && held.get("dataType").and_then(Value::as_str) == Some("TEXT")
6013                });
6014                if !text {
6015                    moved.push(format!("the created {} text field", field.field));
6016                }
6017            }
6018        }
6019        if !moved.is_empty() {
6020            return Err(SourceError::Refused {
6021                message: format!(
6022                    "GitHub changed {} after the guarded field setup; the pre-write item \
6023                     assignments are:\n{}",
6024                    moved.join(", "),
6025                    recovery(&report, &before)?
6026                ),
6027            });
6028        }
6029        Ok(report)
6030    }
6031
6032    /// Validate configuration and capture the named credential without exposing it.
6033    ///
6034    /// # Errors
6035    ///
6036    /// Returns [`SourceError::Config`] for a configuration this instance cannot use and
6037    /// [`SourceError::Auth`] when the named credential is missing or empty.
6038    pub fn new(
6039        name: &SourceName,
6040        config: GitHubProjectsConfig,
6041        secrets: &dyn SecretResolver,
6042    ) -> Result<Self, SourceError> {
6043        Self::recording_into(name, config, secrets, Arc::new(Accounting::new()))
6044    }
6045
6046    /// The same, recording every request it sends into an accounting the caller holds too.
6047    ///
6048    /// [`Self::new`] is this with an accounting of its own. A caller that is also making
6049    /// its own calls to GitHub — a lane verifying a schema, sweeping residue or cleaning
6050    /// up — passes the one it records those into, so the session total accounts for the
6051    /// whole session rather than for this source's share of it.
6052    ///
6053    /// # Errors
6054    ///
6055    /// Exactly [`Self::new`]'s: [`SourceError::Config`] for a configuration this instance
6056    /// cannot use and [`SourceError::Auth`] when the named credential is missing or empty.
6057    pub fn recording_into(
6058        name: &SourceName,
6059        config: GitHubProjectsConfig,
6060        secrets: &dyn SecretResolver,
6061        ledger: Arc<Accounting>,
6062    ) -> Result<Self, SourceError> {
6063        if !valid_github_owner(&config.owner) {
6064            return Err(SourceError::Config {
6065                message: "owner must be 1-39 ASCII letters, digits, or single hyphens, and cannot start or end with a hyphen".into(),
6066            });
6067        }
6068        if config.project_number == 0 || config.project_number > i32::MAX as u32 {
6069            return Err(SourceError::Config {
6070                message: format!("project_number must be between 1 and {}", i32::MAX),
6071            });
6072        }
6073        if !valid_environment_name(&config.token_env) {
6074            return Err(SourceError::Config {
6075                message: "token_env must be a valid environment-variable name".into(),
6076            });
6077        }
6078        let repository = config
6079            .repository
6080            .as_deref()
6081            .map(RepositoryTarget::parse)
6082            .transpose()?;
6083        if let Some(entry) = config
6084            .creation_owners
6085            .iter()
6086            .find(|entry| !valid_github_owner(entry))
6087        {
6088            return Err(SourceError::Config {
6089                message: format!(
6090                    "creation_owners entry {entry:?} is not a GitHub login: a login is 1-39 ASCII \
6091                     letters, digits, or single hyphens, and cannot start or end with a hyphen"
6092                ),
6093            });
6094        }
6095        let endpoint = Url::parse(&config.endpoint).map_err(|e| SourceError::Config {
6096            message: format!("endpoint is not a valid URL: {e}"),
6097        })?;
6098        if endpoint.scheme() != "https"
6099            && !(endpoint.scheme() == "http"
6100                && endpoint
6101                    .host_str()
6102                    .is_some_and(|h| h == "127.0.0.1" || h == "localhost" || h == "::1"))
6103        {
6104            return Err(SourceError::Config {
6105                message:
6106                    "endpoint must use HTTPS (HTTP is accepted only for a loopback test server)"
6107                        .into(),
6108            });
6109        }
6110        let token = secrets.get(&config.token_env).filter(|token| !token.expose_secret().trim().is_empty()).ok_or_else(|| SourceError::Auth {
6111            message: format!("environment variable {} is missing or empty; set it to a fine-grained GitHub token granting Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board", config.token_env),
6112        })?;
6113        Ok(Self {
6114            name: name.clone(),
6115            owner: config.owner,
6116            project_number: config.project_number,
6117            repository,
6118            creation_owners: config.creation_owners,
6119            asset_client: std::sync::OnceLock::new(),
6120            body_markup: std::sync::OnceLock::new(),
6121            endpoint,
6122            token,
6123            credential_name: config.token_env,
6124            statuses: BoardStatuses::resolve(&config.status_mapping, name)?,
6125            priorities: config
6126                .priority_mapping
6127                .map(|mapping| PriorityMapping::resolve(mapping, name))
6128                .transpose()?,
6129            metadata_fields: MetadataField::resolve(config.metadata_fields, name)?,
6130            sub_issues: config.sub_issues,
6131            assignees: config.assignees,
6132            people: Mutex::new(BTreeMap::new()),
6133            forgotten: Mutex::new(Vec::new()),
6134            spellings: Mutex::new(BTreeMap::new()),
6135            link_types: onetaskgraph_plugin_api::LinkTypes::checked(
6136                KIND,
6137                &config.link_types,
6138                &[relations::RELATES_TO],
6139                relations::REFUSED_WORDS,
6140            )
6141            .map_err(|error| match error {
6142                SourceError::Config { message } => SourceError::Config {
6143                    message: format!("source {name}: {message}"),
6144                },
6145                other => other,
6146            })?,
6147            client: std::sync::OnceLock::new(),
6148            created: Mutex::new(Vec::new()),
6149            updated: Mutex::new(Vec::new()),
6150            commented: Mutex::new(Vec::new()),
6151            pacing: Pacing::resolve(config.pacing, name)?,
6152            last_mutation: Mutex::new(None),
6153            last_served: Mutex::new(None),
6154            windows: Mutex::new(pacing::Windows::default()),
6155            task_children: Mutex::new(BTreeMap::new()),
6156            written: Mutex::new(BTreeMap::new()),
6157            deferred: Mutex::new(None),
6158            held_updates: Mutex::new(Vec::new()),
6159            held_comments: Mutex::new(BTreeMap::new()),
6160            task_writes: Mutex::new(None),
6161            written_tokens: Mutex::new(BTreeMap::new()),
6162            clock: system_clock(),
6163            declared_private: std::sync::atomic::AtomicBool::new(false),
6164            numeric_repositories: tokio::sync::Mutex::new(BTreeMap::new()),
6165            board_cache: Mutex::new(None),
6166            search_cache: Mutex::new(None),
6167            narrowed_cache: Mutex::new(BTreeMap::new()),
6168            resolved_cache: Mutex::new(BTreeMap::new()),
6169            read_ahead: Mutex::new(BTreeMap::new()),
6170            pending_origins: Mutex::new(Vec::new()),
6171            member_classes: Mutex::new(BTreeMap::new()),
6172            carried: Mutex::new(BTreeMap::new()),
6173            held_cache: Mutex::new(BTreeMap::new()),
6174            children_cache: Mutex::new(BTreeMap::new()),
6175            search_next: Mutex::new(BTreeMap::new()),
6176            fields_cache: Mutex::new(None),
6177            repository_cache: Mutex::new(BTreeMap::new()),
6178            ledger,
6179            expected: expected::Held::default(),
6180            projection: projection::Held::default(),
6181        })
6182    }
6183
6184    /// The client every API request goes through, built on the first one.
6185    ///
6186    /// Not with the source: building a client loads the system's certificate store, which
6187    /// costs tens of milliseconds, and a command that configures this board but never sends to
6188    /// it — a read of another source — should not pay that in its process.
6189    fn client(&self) -> Result<&Client, SourceError> {
6190        built(&self.client, || {
6191            Client::builder()
6192                .user_agent("onetaskgraph")
6193                .build()
6194                .map_err(|e| SourceError::Config {
6195                    message: format!("cannot build HTTP client: {e}"),
6196                })
6197        })
6198    }
6199
6200    /// The client attachment requests go through, with its own redirect policy, built on the
6201    /// first one for the reason [`Self::client`] gives.
6202    fn asset_client(&self) -> Result<&Client, SourceError> {
6203        built(&self.asset_client, || assets::client(&self.endpoint))
6204    }
6205
6206    /// A snapshot of every request this source has sent, and what each cost.
6207    ///
6208    /// A value to hold and compare rather than a borrow of the accounting itself, so two
6209    /// of them can sit side by side. When this source was built with
6210    /// [`Self::recording_into`] the snapshot is the whole shared session, which is the
6211    /// point of building it that way.
6212    #[must_use]
6213    pub fn accounting(&self) -> accounting::Session {
6214        self.ledger.snapshot()
6215    }
6216
6217    /// Send one GraphQL document, pacing this source's own mutations and waiting out a
6218    /// rate limit rather than handing it straight back as an error.
6219    ///
6220    /// Retrying is safe for every document here, including the mutations, and the reason
6221    /// is that only a *refusal* is retried: [`Limiter::classify`] rules on a response
6222    /// GitHub sent, and a request GitHub refused for a rate limit did not run, so nothing
6223    /// this replays has already taken effect. An outcome this source cannot know — the
6224    /// send failed, or the body could not be read, so the mutation may well have landed —
6225    /// is [`Attempt::Failed`] in [`send_once`] and leaves this loop without a second
6226    /// attempt. A duplicate write would come from replaying one of those, and none is
6227    /// replayed.
6228    async fn graphql(&self, query: &str, variables: Value) -> Result<Value, SourceError> {
6229        // Updates held back go out before any other request, so whatever it reads or writes
6230        // sees the board as though each had been sent when it was made.
6231        Box::pin(self.send_held_updates()).await?;
6232        // Origins held back for a read ahead that never came are sent before anything else.
6233        if query != graphql::ORIGIN_LOOKUPS && query != graphql::ORIGIN_LOOKUPS_WITH_MEMBERS {
6234            Box::pin(self.send_pending_origins(None)).await?;
6235        }
6236        let journaling = self.expected.journaling();
6237        let spelling = self.spelling();
6238        if !journaling && !spelling {
6239            return self.graphql_sent(query, variables).await;
6240        }
6241        // While a write the store's cache expects runs, its mutations select the whole issue
6242        // they leave behind, so the response vouches for what the cache keeps — and every
6243        // request is recorded, so the write's parts are reported from their own responses.
6244        // A targeted update sends a twin of each selecting the issue's token parts inline, at
6245        // the same price, so the version it answers is the one its own last response spells.
6246        let (query, variables) = match (journaling, graphql::whole_twin(query)) {
6247            (true, Some(twin)) => (twin, expected::whole_variables(variables)),
6248            _ => match graphql::token_twin(query).filter(|_| spelling) {
6249                Some(twin) => (twin, token_variables(variables)),
6250                None => (query, variables),
6251            },
6252        };
6253        let sent = self.graphql_sent(query, variables.clone()).await;
6254        if spelling && let Ok(data) = &sent {
6255            self.record_written_token(query, &variables, data);
6256        }
6257        if journaling {
6258            self.journal(query, &variables, &sent).await;
6259        }
6260        sent
6261    }
6262
6263    /// Whether a targeted update of this source is running, whose mutations are each sent as
6264    /// the twin selecting the whole issue (see [`Self::written_tokens`]).
6265    fn spelling(&self) -> bool {
6266        SPELLING
6267            .try_with(|source| *source == std::ptr::from_ref(self) as usize)
6268            .unwrap_or(false)
6269    }
6270
6271    /// Record the change token the issue a mutation's response shows whole holds now, as
6272    /// [`TaskSource::written_task`] answers it; a response showing no whole issue records
6273    /// nothing.
6274    fn record_written_token(&self, document: &str, variables: &Value, data: &Value) {
6275        let (issue, _) = expected::read_back(document, variables, data);
6276        if let Some(issue) = issue {
6277            self.record_written_issue(issue);
6278        }
6279    }
6280
6281    /// Record the change token `issue`, as a write's own answer shows it whole, holds now — or,
6282    /// where that answer lacks a part of one, that it was shown and spells none.
6283    fn record_written_issue(&self, issue: &Value) {
6284        // An answer naming the issue by its id alone did not show it, so it says nothing.
6285        if issue.get("updatedAt").is_none() {
6286            return;
6287        }
6288        let Some(id) = issue.get("id").and_then(Value::as_str) else {
6289            return;
6290        };
6291        let (item, token) = match self.written_token_of(issue) {
6292            Some((item, token)) => (item, Some(token)),
6293            None => {
6294                // Answered whole, but without every part of a token: its board item's id, where
6295                // it says one, so a later write naming that item still drops the entry.
6296                let item = issue
6297                    .pointer("/projectItems/nodes")
6298                    .and_then(Value::as_array)
6299                    .and_then(|nodes| self.board_entry(nodes))
6300                    .and_then(|entry| entry.get("id"))
6301                    .and_then(Value::as_str)
6302                    .unwrap_or_default()
6303                    .to_owned();
6304                (item, None)
6305            }
6306        };
6307        if let Ok(mut tokens) = self.written_tokens.lock() {
6308            tokens.insert(NativeId(id.to_owned()), (item, token));
6309        }
6310    }
6311
6312    /// Record `token` as the change token the task `item` holds after this command's write.
6313    fn remember_written_token(&self, item: &Resolved, token: String) {
6314        if let Ok(mut tokens) = self.written_tokens.lock() {
6315            tokens.insert(item.id.clone(), (item.item_id.clone(), Some(token)));
6316        }
6317    }
6318
6319    /// The change token the task `id` holds after this command's latest write of it, when that
6320    /// write's own response — or the read made right after it — showed one.
6321    fn written_token(&self, id: &NativeId) -> Option<String> {
6322        self.written_answer(id).flatten()
6323    }
6324
6325    /// What this command's latest write of the task `id` showed of it: `Some` once a response
6326    /// showed the issue whole — its token, or `None` where that response could not spell one —
6327    /// and `None` where no response did.
6328    fn written_answer(&self, id: &NativeId) -> Option<Option<String>> {
6329        self.written_tokens
6330            .lock()
6331            .ok()?
6332            .get(id)
6333            .map(|(_, token)| token.clone())
6334    }
6335
6336    /// Drop the written token of every task `variables` names, by its id or its board item's,
6337    /// before a mutation that may move it is sent.
6338    fn forget_written_tokens(&self, variables: &Value) {
6339        let Ok(mut tokens) = self.written_tokens.lock() else {
6340            return;
6341        };
6342        if tokens.is_empty() {
6343            return;
6344        }
6345        let named: Vec<&str> = variables
6346            .as_object()
6347            .into_iter()
6348            .flat_map(|arguments| arguments.values())
6349            .flat_map(|input| {
6350                WRITTEN_NAMES
6351                    .iter()
6352                    .filter_map(|key| input.get(key).and_then(Value::as_str))
6353            })
6354            .collect();
6355        tokens.retain(|id, (item, _)| {
6356            !named
6357                .iter()
6358                .any(|name| *name == id.0 || *name == item.as_str())
6359        });
6360    }
6361
6362    /// One document sent, retried while GitHub asks for a wait, exactly as asked.
6363    async fn graphql_sent(&self, query: &str, variables: Value) -> Result<Value, SourceError> {
6364        if is_mutation(query) {
6365            self.forget_written_tokens(&variables);
6366        }
6367        if is_mutation(query)
6368            && ![
6369                graphql::ADD_COMMENT,
6370                graphql::UPDATE_COMMENT,
6371                graphql::DELETE_COMMENT,
6372                graphql::ADD_COMMENT_WHOLE,
6373                graphql::UPDATE_COMMENT_WHOLE,
6374            ]
6375            .contains(&query)
6376        {
6377            let mut cache = self.resolved_cache()?;
6378            let mut ahead = self.read_ahead()?;
6379            let mut carried = self.carried()?;
6380            for argument in ["input", "second", "third", "clear"] {
6381                if let Some(input) = variables.get(argument) {
6382                    let names = |id: &NativeId, item_id: Option<&str>| {
6383                        ["id", "issueId", "subjectId", "itemId"].iter().any(|key| {
6384                            input
6385                                .get(key)
6386                                .and_then(Value::as_str)
6387                                .is_some_and(|value| value == id.0 || Some(value) == item_id)
6388                        })
6389                    };
6390                    cache.retain(|id, item| !names(id, Some(&item.item_id)));
6391                    ahead.retain(|id, item| {
6392                        !names(id, item.as_ref().map(|item| item.item_id.as_str()))
6393                    });
6394                    carried.retain(|id, item| !names(id, Some(&item.item_id)));
6395                }
6396            }
6397        }
6398        let doing = operation_description(query);
6399        let mutation = is_mutation(query);
6400        let charge = pacing::Charge::graphql(query, &variables);
6401        let mut waited = Duration::ZERO;
6402        let mut waits = 0_u32;
6403        let mut backoff = self.pacing.retry_backoff;
6404        loop {
6405            let ticket = self.pace(charge, mutation).await;
6406            // Every write but a create is asked for immediately before it is sent — a create's
6407            // fields, its relationships, its content and the delete that takes it back included
6408            // — so a copy that owns the create renews its hold first, and one that has lost it
6409            // sends nothing more. Asked again before a retry, which is sent later.
6410            if mutation
6411                && !query.contains("createIssue(")
6412                && let Err(refused) = <dyn onetaskgraph_plugin_api::WriteGuard>::check().await
6413            {
6414                self.paced(ticket, mutation);
6415                return Err(refused);
6416            }
6417            // And of a caller's request gate, before every request this source sends — a retry
6418            // as its own — so a caller pacing its own floor inside one call waits or stops here.
6419            let admitted = match <dyn onetaskgraph_plugin_api::RequestGate>::before(&gated_graphql(
6420                query, &variables,
6421            ))
6422            .await
6423            {
6424                Ok(admitted) => admitted,
6425                Err(refused) => {
6426                    self.paced(ticket, mutation);
6427                    return Err(refused);
6428                }
6429            };
6430            let attempt = self.send_once(query, &variables, waits + 1).await;
6431            // Over however it ended — answered, refused or failed before any header — and
6432            // ended before any wait for a retry, which is asked for as a request of its own.
6433            admitted.end();
6434            self.paced(ticket, mutation);
6435            let remaining = self.pacing.retry_budget.saturating_sub(waited);
6436            let (wait, cause) = match attempt {
6437                Ok(data) => return Ok(data),
6438                Err(Attempt::Failed(error)) => return Err(error),
6439                Err(Attempt::Conflicted(said)) => {
6440                    // A create is never replayed: see `CONFLICT_WORDINGS`.
6441                    if query.contains("createIssue(") || backoff.is_zero() || backoff > remaining {
6442                        return Err(SourceError::Unavailable {
6443                            message: format!(
6444                                "GitHub refused this source while {doing} as a temporary \
6445                                 conflict ({said}); it retried {} over {} and the conflict \
6446                                 did not clear within the {} one call may spend waiting. \
6447                                 next: run the command again once nothing else is writing to \
6448                                 the same items",
6449                                plural(waits, "time"),
6450                                seconds(waited),
6451                                seconds(self.pacing.retry_budget),
6452                            ),
6453                        });
6454                    }
6455                    (backoff, pacing::cause::BACKOFF)
6456                }
6457                Err(Attempt::Limited(limited)) => {
6458                    let (wait, cause) = limited.wait(backoff);
6459                    // A wait of nothing spends none of the budget, so it is exhaustion rather
6460                    // than a retry. `Pacing::resolve` rules out every way of configuring one
6461                    // except a budget of zero, where reporting the first refusal is the ask.
6462                    if wait.is_zero() || wait > remaining {
6463                        return Err(limited.exhausted(
6464                            doing,
6465                            waits,
6466                            waited,
6467                            wait,
6468                            self.pacing.retry_budget,
6469                        ));
6470                    }
6471                    (wait, cause)
6472                }
6473            };
6474            self.clock.sleep_because(wait, cause).await;
6475            waited += wait;
6476            waits += 1;
6477            backoff = backoff.saturating_mul(2);
6478        }
6479    }
6480
6481    /// Hold one request charging `charge` until every secondary window it charges has room for
6482    /// the whole of it — and, for a mutation of an instance configured with
6483    /// `pacing.min_mutation_interval_ms`, until that interval has passed since the last one
6484    /// finished — then count it, answering the ticket [`Self::paced`] finishes it with.
6485    ///
6486    /// The moment is decided and counted under the lock and waited out outside it, so two
6487    /// callers take two places rather than the same one, and no lock is held across an await.
6488    /// A request with room goes out at once: nothing here waits that a window does not ask for.
6489    async fn pace(&self, charge: pacing::Charge, mutation: bool) -> pacing::Ticket {
6490        let (wait, cause, ticket) = {
6491            // A poisoned lock here costs pacing, not correctness, and refusing the write over
6492            // it would turn an earlier failure into a second one for no gain.
6493            let mut windows = self
6494                .windows
6495                .lock()
6496                .unwrap_or_else(std::sync::PoisonError::into_inner);
6497            let now = self.clock.now();
6498            let (mut at, mut cause) = if self.pacing.windows {
6499                windows.room(now, charge)
6500            } else {
6501                (now, None)
6502            };
6503            if mutation && !self.pacing.min_mutation_interval.is_zero() {
6504                let mut last = self
6505                    .last_mutation
6506                    .lock()
6507                    .unwrap_or_else(std::sync::PoisonError::into_inner);
6508                // `checked_add` rather than `+`: adding durations can panic on overflow, and
6509                // pacing is not worth a panic even at a bound `MAX_PACING_MS` already rules out.
6510                if let Some(earliest) = last
6511                    .and_then(|previous| previous.checked_add(self.pacing.min_mutation_interval))
6512                    && earliest > at
6513                {
6514                    at = earliest;
6515                    cause = Some(pacing::cause::MIN_INTERVAL);
6516                }
6517                *last = Some(at);
6518            }
6519            let ticket = windows.charge(at, charge);
6520            (at.saturating_sub(now), cause, ticket)
6521        };
6522        if let (false, Some(cause)) = (wait.is_zero(), cause) {
6523            self.clock.sleep_because(wait, cause).await;
6524        }
6525        ticket
6526    }
6527
6528    /// Record that the request `ticket` was charged for has finished, so each window — and
6529    /// the configured spacing — counts it from here rather than from the moment it left.
6530    ///
6531    /// This source can only choose when a request *departs*; GitHub's limiter counts when it
6532    /// *arrives*, and the two differ by whatever the request spent in transit. Counting from
6533    /// departure would hand the limiter a window that looked roomier than it is, so a source
6534    /// pacing exactly at a limit could still be seen arriving over it — which is how a copy
6535    /// paced well inside a board's threshold was once refused by it on a slower machine while
6536    /// passing on a quick one. The previous request had arrived before its response came back,
6537    /// so counting from here is never earlier than the limiter does, whatever transit costs
6538    /// and on whatever platform: the safe side of a limit that punishes being wrong by refusing
6539    /// reads for the next fifty minutes.
6540    ///
6541    /// A failed attempt is finished too: a request refused by the limiter still arrived, and
6542    /// one that never left costs only room nobody needed.
6543    fn paced(&self, ticket: pacing::Ticket, mutation: bool) {
6544        let now = self.clock.now();
6545        self.windows
6546            .lock()
6547            .unwrap_or_else(std::sync::PoisonError::into_inner)
6548            .finish(ticket, now);
6549        if mutation && !self.pacing.min_mutation_interval.is_zero() {
6550            let mut last = self
6551                .last_mutation
6552                .lock()
6553                .unwrap_or_else(std::sync::PoisonError::into_inner);
6554            // `max` rather than an assignment: a concurrent caller may already have reserved a
6555            // slot further out, and completing this request must never pull that slot back in.
6556            *last = Some(last.map_or(now, |reserved| reserved.max(now)));
6557        }
6558    }
6559
6560    /// One HTTP attempt, classified into an answer, a rate limit to wait out, or a
6561    /// failure that waiting cannot help — and recorded, whichever of the three it was.
6562    ///
6563    /// This is the one place a request leaves this crate, which is why the accounting is
6564    /// here rather than at each of the callers: a read path added later is counted without
6565    /// anybody remembering to count it, and
6566    /// `the_session_report_counts_every_request_the_board_served_and_what_each_cost` fails
6567    /// when one is not.
6568    async fn send_once(
6569        &self,
6570        query: &str,
6571        variables: &Value,
6572        number: u32,
6573    ) -> Result<Value, Attempt> {
6574        // A lookup goes out sized to the people it names, and the record names and counts it as
6575        // what it is; everything that decides how it is retried or read compares `query`, the
6576        // constant it was written as.
6577        let sized = graphql::sized(query, variables);
6578        let executed = self.ledger.priced_document(sized.as_ref());
6579        let Attempted {
6580            result,
6581            limits,
6582            reported_cost,
6583            response_outcome,
6584        } = self.attempt(executed.as_ref(), variables).await;
6585        // No `otherwise` name: every document this source sends is one of its own, and the
6586        // inventory gate on `graphql::DOCUMENTS` is what keeps that true.
6587        let sending = accounting::Request::graphql(sized.as_ref(), variables, None, reported_cost);
6588        let outcome = match &result {
6589            Ok(_) => accounting::Outcome::Answered,
6590            Err(Attempt::Limited(_)) => accounting::Outcome::RateLimited,
6591            Err(Attempt::Failed(_) | Attempt::Conflicted(_)) => accounting::Outcome::Refused,
6592        };
6593        self.ledger
6594            .record(sending.finished(outcome, limits).with_execution(
6595                Some(executed.into_owned()),
6596                response_outcome,
6597                number,
6598            ));
6599        result
6600    }
6601
6602    /// The attempt itself, with what its response said about the rate limit alongside.
6603    ///
6604    /// The two are returned together rather than recorded here because every one of the
6605    /// early exits below is a different outcome, and a record written at each of them is a
6606    /// record one of them can be added without.
6607    async fn attempt(&self, query: &str, variables: &Value) -> Attempted {
6608        let mut limits = accounting::RateLimit::default();
6609        let mut reported_cost = None;
6610        let mut response_outcome = accounting::ResponseOutcome::TransportError;
6611        // Spelled here, at the one place a document leaves for GitHub, and nowhere earlier:
6612        // everything that decides how a document is retried or how its answer is read compares
6613        // it with the constant it was written as.
6614        let spelled = self
6615            .assignees
6616            .then(|| graphql::with_assignees(query))
6617            .flatten();
6618        let result = self
6619            .attempted(
6620                query,
6621                spelled.as_deref().unwrap_or(query),
6622                variables,
6623                &mut limits,
6624                &mut reported_cost,
6625                &mut response_outcome,
6626            )
6627            .await;
6628        Attempted {
6629            result,
6630            limits,
6631            reported_cost,
6632            response_outcome,
6633        }
6634    }
6635
6636    /// One HTTP attempt, filling in what its response said about the rate limit as it goes.
6637    async fn attempted(
6638        &self,
6639        query: &str,
6640        sent: &str,
6641        variables: &Value,
6642        limits: &mut accounting::RateLimit,
6643        reported_cost: &mut Option<u64>,
6644        response_outcome: &mut accounting::ResponseOutcome,
6645    ) -> Result<Value, Attempt> {
6646        let response = self
6647            .client()
6648            .map_err(Attempt::Failed)?
6649            .post(self.endpoint.clone())
6650            .bearer_auth(self.token.expose_secret())
6651            .json(&json!({"query": sent, "variables": variables}))
6652            .send()
6653            .await
6654            .map_err(|e| {
6655                Attempt::Failed(SourceError::Unavailable {
6656                    message: format!("GitHub GraphQL request failed: {}", transport_error(&e)),
6657                })
6658            })?;
6659        let status = response.status();
6660        if !status.is_success() {
6661            *response_outcome = accounting::ResponseOutcome::HttpError;
6662        }
6663        let header = |name: &str| whole_seconds(response.headers().get(name));
6664        let served = response
6665            .headers()
6666            .get(reqwest::header::DATE)
6667            .and_then(|value| value.to_str().ok())
6668            .and_then(|value| DateTime::parse_from_rfc2822(value).ok())
6669            .map(|at| at.with_timezone(&Utc));
6670        *limits = accounting::RateLimit::read(|name| {
6671            response
6672                .headers()
6673                .get(name)
6674                .and_then(|value| value.to_str().ok())
6675                .map(str::to_owned)
6676        });
6677        // Each response's own reading, as it gave it: never merged with another window's.
6678        <dyn onetaskgraph_plugin_api::RequestGate>::after(&quota::header_readings(limits));
6679        // Exactly `0` is exhaustion and everything else — a count, an empty value, bytes
6680        // that are not text at all — is "not known to be exhausted". This never makes a
6681        // response a refusal on its own: it says which limiter a refusal is attributed to
6682        // and where its hint comes from, so a value this cannot read costs a hint rather
6683        // than an answer.
6684        let exhausted = response
6685            .headers()
6686            .get("x-ratelimit-remaining")
6687            .and_then(|value| value.to_str().ok())
6688            == Some("0");
6689        // `retry-after` is what GitHub asks for when it asks; when it does not and the
6690        // primary budget is spent, `x-ratelimit-reset` says when that budget comes back,
6691        // which is the same question answered as an absolute time. Nothing else here is a
6692        // hint, and a schedule is what answers a refusal that carries none.
6693        let retry_after = header("retry-after");
6694        let hinted_by = if retry_after.is_some() || !exhausted {
6695            Hint::RetryAfter
6696        } else {
6697            Hint::PrimaryReset
6698        };
6699        let hint = retry_after.or_else(|| {
6700            exhausted
6701                .then(|| header("x-ratelimit-reset"))
6702                .flatten()
6703                .map(|reset| reset.saturating_sub(Utc::now().timestamp().max(0).unsigned_abs()))
6704        });
6705        // Read before it is parsed, because the evidence which tells a secondary rate
6706        // limit from a rejected credential is in the body of a response whose status says
6707        // only "forbidden" — and a non-success response was never parsed at all.
6708        let body = response.text().await.map_err(|e| {
6709            Attempt::Failed(SourceError::Unavailable {
6710                message: format!(
6711                    "GitHub GraphQL response could not be read: {}",
6712                    transport_error(&e)
6713                ),
6714            })
6715        })?;
6716        *reported_cost = serde_json::from_str::<Value>(&body)
6717            .ok()
6718            .as_ref()
6719            .and_then(|body| body.pointer("/data/rateLimit/cost"))
6720            .and_then(Value::as_u64);
6721        let parsed = serde_json::from_str::<Value>(&body).ok();
6722        *response_outcome = accounting::ResponseOutcome::of_graphql_reply(status, parsed.as_ref());
6723        if let Some(limiter) = Limiter::classify(status, exhausted, &body) {
6724            return Err(Attempt::Limited(Limited {
6725                limiter,
6726                hint,
6727                hinted_by,
6728            }));
6729        }
6730        if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
6731            return Err(Attempt::Failed(SourceError::Auth {
6732                message: format!(
6733                    "GitHub rejected the configured credential with HTTP {status}; grant it Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board"
6734                ),
6735            }));
6736        }
6737        if !status.is_success() {
6738            return Err(Attempt::Failed(SourceError::Unavailable {
6739                message: format!("GitHub GraphQL returned HTTP {status}"),
6740            }));
6741        }
6742        let said = refusal_wording(status, &body);
6743        let normalized = said.to_ascii_lowercase();
6744        if CONFLICT_WORDINGS
6745            .iter()
6746            .any(|wording| normalized.contains(wording))
6747        {
6748            return Err(Attempt::Conflicted(said));
6749        }
6750        // A lookup is read as the inventoried document it was sized from.
6751        let query = graphql::inventoried(query);
6752        let answered = if query == graphql::ISSUES_BY_REFERENCE {
6753            self.answer_unresolved(&body)
6754        } else if [
6755            graphql::CREATE_ISSUES,
6756            graphql::SEARCH_BATCH,
6757            graphql::USER_IDS,
6758            graphql::ADD_COMMENTS,
6759            graphql::WRITE_TASKS,
6760            graphql::SET_PARENTS,
6761            graphql::ADD_RELATES_TO,
6762            graphql::REMOVE_RELATES_TO,
6763        ]
6764        .contains(&query)
6765        {
6766            answer_with_errors(&body).map_or_else(|| self.answer(&body), Ok)
6767        } else {
6768            self.answer(&body)
6769        };
6770        let mut data = answered.map_err(Attempt::Failed)?;
6771        if let Some(served) = served {
6772            *self
6773                .last_served
6774                .lock()
6775                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(served);
6776            stamp_served(&mut data, &served.to_rfc3339());
6777        }
6778        Ok(data)
6779    }
6780
6781    /// What one successful HTTP response says, once its GraphQL errors are read.
6782    /// [`Self::answer`], for a read of issues by reference: a reference GitHub cannot resolve
6783    /// for this credential — a repository it cannot see, an issue number it does not hold —
6784    /// is answered `null` beside a `NOT_FOUND` error naming it, and that is an answer about
6785    /// that reference rather than a failure of the others. Any other error refuses the read,
6786    /// as there.
6787    fn answer_unresolved(&self, body: &str) -> Result<Value, SourceError> {
6788        let parsed: Option<Value> = serde_json::from_str(body).ok();
6789        // Each error is a `NOT_FOUND` whose path names one slot of the batch, `r<n>` or its
6790        // `issue`, and the answer holds `null` at exactly that path: anything else — another
6791        // kind of error, one naming no slot, or one beside a value it says is not there — is a
6792        // refusal of the whole read.
6793        let unresolved = |data: &Value, error: &Value| {
6794            error.get("type").and_then(Value::as_str) == Some("NOT_FOUND")
6795                && error
6796                    .get("path")
6797                    .and_then(Value::as_array)
6798                    .is_some_and(|path| {
6799                        let alias = path.first().and_then(Value::as_str).and_then(|alias| {
6800                            alias
6801                                .strip_prefix('r')
6802                                .and_then(|slot| slot.parse::<usize>().ok())
6803                                .filter(|slot| *slot < REFERENCE_BATCH)
6804                                .map(|_| alias)
6805                        });
6806                        match (alias, path.get(1).and_then(Value::as_str), path.len()) {
6807                            (Some(alias), None, 1) => data.get(alias).is_some_and(Value::is_null),
6808                            (Some(alias), Some("issue"), 2) => data
6809                                .get(alias)
6810                                .and_then(|repository| repository.get("issue"))
6811                                .is_some_and(Value::is_null),
6812                            _ => false,
6813                        }
6814                    })
6815        };
6816        let unresolved_only = parsed.as_ref().is_some_and(|parsed| {
6817            parsed.get("data").is_some_and(|data| {
6818                data.is_object()
6819                    && parsed
6820                        .get("errors")
6821                        .and_then(Value::as_array)
6822                        .is_some_and(|errors| errors.iter().all(|error| unresolved(data, error)))
6823            })
6824        });
6825        match parsed {
6826            Some(parsed) if unresolved_only => Ok(parsed["data"].clone()),
6827            _ => self.answer(body),
6828        }
6829    }
6830
6831    fn answer(&self, body: &str) -> Result<Value, SourceError> {
6832        let body: Value = serde_json::from_str(body).map_err(|e| SourceError::Malformed {
6833            message: format!("GitHub returned invalid JSON: {e}"),
6834        })?;
6835        let errors = body
6836            .get("errors")
6837            .map(|value| {
6838                value.as_array().ok_or_else(|| SourceError::Malformed {
6839                    message: "GitHub response errors is not an array".into(),
6840                })
6841            })
6842            .transpose()?;
6843        if let Some(errors) = errors.filter(|errors| !errors.is_empty()) {
6844            let messages = errors
6845                .iter()
6846                .filter_map(|e| e.get("message").and_then(Value::as_str))
6847                .collect::<Vec<_>>()
6848                .join("; ");
6849            let message = if messages.is_empty() {
6850                "GitHub returned GraphQL errors".into()
6851            } else {
6852                messages
6853            };
6854            let normalized = message.to_ascii_lowercase();
6855            if normalized.contains("resource not accessible") || normalized.contains("scope") {
6856                return Err(SourceError::Auth {
6857                    message: format!(
6858                        "{message}; grant {} Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board",
6859                        self.credential_name
6860                    ),
6861                });
6862            }
6863            return Err(SourceError::Refused { message });
6864        }
6865        body.get("data")
6866            .filter(|data| data.is_object())
6867            .cloned()
6868            .ok_or_else(|| SourceError::Malformed {
6869                message: "GitHub response has no data object".into(),
6870            })
6871    }
6872
6873    // llmlint: ignore[boundary_inputs_validated] GitHub caps nested connections at 100 and
6874    // GraphQL cannot independently page them inside the outer item page. This source page is
6875    // deliberately bounded at that published maximum; the live drift journey exercises it.
6876    async fn board_page(
6877        &self,
6878        items_after: Option<&str>,
6879        items_first: u32,
6880    ) -> Result<Value, SourceError> {
6881        let data = self
6882            .graphql(
6883                graphql::BOARD,
6884                json!({"owner":self.owner,"number":self.project_number,
6885                       "first":items_first.min(MAX_PAGE_SIZE),"after":items_after,
6886                       "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
6887            )
6888            .await?;
6889        data.pointer("/owner/projectV2")
6890            .filter(|v| !v.is_null())
6891            .cloned()
6892            .ok_or_else(|| SourceError::Refused {
6893                message: format!(
6894                    "GitHub project {}/{} was not found or is not visible to the token",
6895                    self.owner, self.project_number
6896                ),
6897            })
6898    }
6899
6900    /// The search that finds the issues of this board, narrowed by `also` when it is
6901    /// given.
6902    ///
6903    /// `project:owner/number` is what scopes a search to one board, and `is:issue` is what
6904    /// keeps pull requests out of it: GitHub's `ISSUE` search type covers both, and a pull
6905    /// request is somebody's change rather than a unit of plan. `-has:parent` is *not*
6906    /// here on purpose — GitHub accepts it and silently ignores it, so a project is told
6907    /// from a task by the `parent` field each issue carries rather than by the search.
6908    fn board_search(&self, also: Option<&str>) -> String {
6909        let scope = format!("project:{}/{} is:issue", self.owner, self.project_number);
6910        match also {
6911            Some(also) => format!("{scope} {also}"),
6912            None => scope,
6913        }
6914    }
6915
6916    /// One issue this source reached directly, as the board item a read of the board would
6917    /// have produced — or `None` when this board does not hold it.
6918    ///
6919    /// The board half of an issue rides along on `Issue.projectItems`, so the value handed
6920    /// to [`Self::resolve`] is the very shape a `ProjectV2.items` read gives it: the board
6921    /// item's own id, that item's field values, and the issue as its content. One resolver
6922    /// for both routes is what makes an issue read through a search, through its own node
6923    /// id, or through its project's sub-issues report the same title, the same status, the
6924    /// same labels and the same qualified id.
6925    ///
6926    /// An issue with no entry for *this* board is not this source's to report, which is
6927    /// what keeps an id naming some other repository's issue from being answered as an item
6928    /// of this board. That answer is given about an **exhausted** connection and never
6929    /// about an unread page: the entry is looked for on the page in hand, and only if that
6930    /// page reports more of the connection, in [`Self::board_membership`]'s walk of the
6931    /// rest of it.
6932    async fn resolve_issue(&self, issue: &Value) -> Result<Option<Resolved>, SourceError> {
6933        self.resolve_issue_as(issue, true).await
6934    }
6935
6936    /// [`Self::resolve_issue`], remembering what it resolves for this command's later reads
6937    /// and writes only when `remember` says to.
6938    async fn resolve_issue_as(
6939        &self,
6940        issue: &Value,
6941        remember: bool,
6942    ) -> Result<Option<Resolved>, SourceError> {
6943        if optional_str(issue, "__typename")? != Some("Issue") {
6944            return Ok(None);
6945        }
6946        let memberships = issue
6947            .get("projectItems")
6948            .ok_or_else(|| SourceError::Malformed {
6949                message: "GitHub issue is missing projectItems".into(),
6950            })?;
6951        let nodes = memberships
6952            .get("nodes")
6953            .and_then(Value::as_array)
6954            .ok_or_else(|| SourceError::Malformed {
6955                message: "GitHub issue projectItems.nodes is not an array".into(),
6956            })?;
6957        let held = match self.board_entry(nodes) {
6958            Some(held) => held.clone(),
6959            None => {
6960                let info = memberships
6961                    .get("pageInfo")
6962                    .ok_or_else(|| SourceError::Malformed {
6963                        message: "GitHub issue projectItems has no pageInfo".into(),
6964                    })?;
6965                // The page held no entry for this board. Whether that means the issue is
6966                // not on it is a question about the rest of the connection, and only a
6967                // connection with no rest answers it here.
6968                if !required_bool(info, "hasNextPage")? {
6969                    return Ok(None);
6970                }
6971                let cursor = required_str(info, "endCursor")?;
6972                validate_cursor_progress(None, cursor)?;
6973                let issue_id = required_str(issue, "id")?;
6974                match self.board_membership(issue_id, cursor).await? {
6975                    Some(held) => held,
6976                    None => return Ok(None),
6977                }
6978            }
6979        };
6980        // The membership's own `updatedAt` rides along: it is the board half of the item's change
6981        // token, which a field change moves where the issue's own time does not.
6982        let item = json!({
6983            "id": required_str(&held, "id")?,
6984            "updatedAt": held.get("updatedAt"),
6985            "project": held.get("project"),
6986            "fieldValues": held.get("fieldValues"),
6987            "content": issue,
6988        });
6989        if remember {
6990            self.resolve(&item)
6991        } else {
6992            self.resolve_unremembered(&item)
6993        }
6994    }
6995
6996    /// This board's own entry among one page of an issue's `Issue.projectItems`.
6997    ///
6998    /// One spelling of *which membership is this board's*, so the page a read carries and
6999    /// the pages [`Self::board_membership`] walks are searched by the same rule.
7000    fn board_entry<'a>(&self, nodes: &'a [Value]) -> Option<&'a Value> {
7001        nodes.iter().find(|node| {
7002            node.pointer("/project/number").and_then(Value::as_u64)
7003                == Some(u64::from(self.project_number))
7004        })
7005    }
7006
7007    /// The rest of one issue's board memberships, from `after`, for this board's entry.
7008    ///
7009    /// The recovery read: a page of memberships that holds no entry for this board says
7010    /// nothing about the memberships past it, so the connection is walked to exhaustion
7011    /// before an issue is reported as one this board does not hold. `Ok(None)` is that
7012    /// positive answer — the whole connection was read and no entry named this board —
7013    /// rather than a failure, and the walk is held to
7014    /// [`validate_cursor_progress`] like every other page walk here, so a source answering
7015    /// with a cursor that does not advance is refused instead of spun on.
7016    async fn board_membership(
7017        &self,
7018        issue: &str,
7019        after: &str,
7020    ) -> Result<Option<Value>, SourceError> {
7021        let mut after = after.to_owned();
7022        loop {
7023            let data = self
7024                .graphql(
7025                    graphql::ISSUE_BOARD_ITEMS,
7026                    json!({"id":issue,"first":MAX_PAGE_SIZE,"after":after,
7027                           "nestedFirst":NESTED_PAGE_SIZE}),
7028                )
7029                .await?;
7030            let Some(connection) = data
7031                .pointer("/node/projectItems")
7032                .filter(|value| !value.is_null())
7033            else {
7034                // The id resolved to nothing, or to something with no memberships to walk —
7035                // which is the same answer as a connection holding no entry for this board.
7036                return Ok(None);
7037            };
7038            let nodes = connection
7039                .get("nodes")
7040                .and_then(Value::as_array)
7041                .ok_or_else(|| SourceError::Malformed {
7042                    message: "GitHub issue projectItems.nodes is not an array".into(),
7043                })?;
7044            if let Some(held) = self.board_entry(nodes) {
7045                return Ok(Some(held.clone()));
7046            }
7047            let info = connection
7048                .get("pageInfo")
7049                .ok_or_else(|| SourceError::Malformed {
7050                    message: "GitHub issue projectItems has no pageInfo".into(),
7051                })?;
7052            let next = required_bool(info, "hasNextPage")?
7053                .then(|| required_str(info, "endCursor"))
7054                .transpose()?;
7055            match next {
7056                Some(next) => {
7057                    validate_cursor_progress(Some(&after), next)?;
7058                    after = next.to_owned();
7059                }
7060                None => return Ok(None),
7061            }
7062        }
7063    }
7064
7065    /// One page of a board-scoped issue search, and where the next page resumes.
7066    async fn search_page(
7067        &self,
7068        search: &str,
7069        first: u32,
7070        after: Option<&str>,
7071    ) -> Result<(Vec<Resolved>, Option<String>), SourceError> {
7072        let data = self
7073            .graphql(
7074                graphql::SEARCH_ISSUES,
7075                json!({"search":search,"type":"ISSUE","first":first.min(MAX_PAGE_SIZE),
7076                       "after":after,"nestedFirst":NESTED_PAGE_SIZE,
7077                       "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
7078            )
7079            .await?;
7080        let connection = data.get("search").ok_or_else(|| SourceError::Malformed {
7081            message: "GitHub search response has no search connection".into(),
7082        })?;
7083        let mut found = Vec::new();
7084        for node in connection
7085            .get("nodes")
7086            .and_then(Value::as_array)
7087            .ok_or_else(|| SourceError::Malformed {
7088                message: "GitHub search nodes is not an array".into(),
7089            })?
7090        {
7091            if let Some(resolved) = self.resolve_issue(node).await? {
7092                found.push(resolved);
7093            }
7094        }
7095        let info = connection
7096            .get("pageInfo")
7097            .ok_or_else(|| SourceError::Malformed {
7098                message: "GitHub search connection has no pageInfo".into(),
7099            })?;
7100        let next = required_bool(info, "hasNextPage")?
7101            .then(|| required_str(info, "endCursor"))
7102            .transpose()?
7103            .map(str::to_owned);
7104        if let Some(next) = &next {
7105            validate_cursor_progress(after, next)?;
7106        }
7107        Ok((found, next))
7108    }
7109
7110    /// Every issue this board holds, completed with what this run wrote.
7111    ///
7112    /// The completion is not an optimisation and it is not a cache: GitHub's issue search
7113    /// is an index and is eventually consistent, so an issue this run created seconds ago
7114    /// can be absent from it, and a project listed straight after being written would
7115    /// otherwise be missing from its own board. What is added back is only what this
7116    /// process itself wrote, out of [`Self::created`], which lives and dies with the
7117    /// process.
7118    async fn board_issues(&self) -> Result<Vec<Resolved>, SourceError> {
7119        let found = self.searched_issues().await?;
7120        self.completed_with_written(found, |_| true)
7121    }
7122
7123    /// Every issue this board's own search reports, walked to exhaustion, read once per
7124    /// source.
7125    ///
7126    /// The uncompleted half of [`Self::board_issues`], separated because [`Self::board`]
7127    /// needs it too and the two would otherwise walk the same search twice in one command.
7128    /// See [`Self::search_cache`] for why holding it is the same bargain holding the board
7129    /// is.
7130    async fn searched_issues(&self) -> Result<Vec<Resolved>, SourceError> {
7131        let cached = self.search_cache()?.clone();
7132        if let Some(held) = cached {
7133            return Ok(held);
7134        }
7135        let mut after: Option<String> = None;
7136        let mut found = Vec::new();
7137        let search = self.board_search(None);
7138        loop {
7139            let (page, next) = self
7140                .search_page(&search, MAX_PAGE_SIZE, after.as_deref())
7141                .await?;
7142            found.extend(page);
7143            match next {
7144                Some(next) => after = Some(next),
7145                None => break,
7146            }
7147        }
7148        *self.search_cache()? = Some(found.clone());
7149        Ok(found)
7150    }
7151
7152    /// Every issue this board's own search reports with `also` beside its scope, walked to
7153    /// exhaustion — held for no later read, which may not be narrowed alike.
7154    async fn searched_narrowly(&self, also: &str) -> Result<Vec<Resolved>, SourceError> {
7155        let mut after: Option<String> = None;
7156        let mut found = Vec::new();
7157        let search = self.board_search(Some(also));
7158        loop {
7159            let (page, next) = self
7160                .search_page(&search, MAX_PAGE_SIZE, after.as_deref())
7161                .await?;
7162            found.extend(page);
7163            match next {
7164                Some(next) => after = Some(next),
7165                None => return Ok(found),
7166            }
7167        }
7168    }
7169
7170    /// This process's own view of the board's issues, or the refusal a poisoned lock is.
7171    fn search_cache(
7172        &self,
7173    ) -> Result<std::sync::MutexGuard<'_, Option<Vec<Resolved>>>, SourceError> {
7174        self.search_cache
7175            .lock()
7176            .map_err(|_| SourceError::Unavailable {
7177                message: "this source's view of the board's issues was left inconsistent by an \
7178                      earlier failure; next: run the command again"
7179                    .into(),
7180            })
7181    }
7182
7183    /// `found`, with everything this run wrote that `keep` accepts and the read did not
7184    /// report.
7185    ///
7186    /// See [`Self::created`] and [`Self::board_issues`] for why a read has to be completed
7187    /// at all: the search index is behind, and a node read of an item filed moments ago can
7188    /// be too.
7189    fn completed_with_written(
7190        &self,
7191        mut found: Vec<Resolved>,
7192        keep: impl Fn(&Resolved) -> bool,
7193    ) -> Result<Vec<Resolved>, SourceError> {
7194        for own in self.created()?.iter().filter(|own| keep(own)) {
7195            if !found.iter().any(|item| item.id == own.id) {
7196                found.push(own.clone());
7197            }
7198        }
7199        Ok(found)
7200    }
7201
7202    /// What resolving one node id reached.
7203    ///
7204    /// Three answers rather than an `Option`, because a board *draft* is none of the other
7205    /// two: it is not an issue, so the issue fragment reads nothing of it, and a read of one
7206    /// is completed by a read of the draft itself rather than reported as nothing.
7207    async fn reach(&self, id: &NativeId) -> Result<Reached, SourceError> {
7208        let asked = self
7209            .graphql(
7210                graphql::ISSUE,
7211                json!({"id":id.0,"first":MAX_PAGE_SIZE,"nestedFirst":NESTED_PAGE_SIZE,
7212                       "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
7213            )
7214            .await;
7215        let data = match asked {
7216            Ok(data) => data,
7217            // A string that is not a node id at all is not a failure to report: it is an id
7218            // this board does not hold, which is what every read of one already answers.
7219            Err(error) if unresolvable_node(&error) => return Ok(Reached::Nothing),
7220            Err(error) => return Err(error),
7221        };
7222        let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
7223            return Ok(Reached::Nothing);
7224        };
7225        if optional_str(node, "__typename")? == Some("DraftIssue") {
7226            return Ok(Reached::Draft);
7227        }
7228        Ok(match self.resolve_issue(node).await? {
7229            Some(item) => Reached::Held(Box::new(item)),
7230            None => Reached::Nothing,
7231        })
7232    }
7233
7234    /// One item of this board by its own id, whatever kind it is.
7235    ///
7236    /// Resolved from the identifier alone: no search, board-wide or otherwise. What this
7237    /// run wrote is read first, because a node read of an item created moments ago can
7238    /// still be behind the board field values written onto it — see [`Self::created`].
7239    async fn item_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7240        if let Some(own) = self.created()?.iter().find(|own| own.id == *id) {
7241            return Ok(Some(own.clone()));
7242        }
7243        if let Some(held) = self.read_ahead()?.remove(id) {
7244            return Ok(held);
7245        }
7246        match self.reach(id).await? {
7247            Reached::Held(item) => Ok(Some(*item)),
7248            Reached::Nothing => Ok(None),
7249            Reached::Draft => self.draft_by_id(id).await,
7250        }
7251    }
7252
7253    /// [`Self::item_by_id`] for a document: one [`graphql::DOCUMENT_IN_PROJECT`] read, which
7254    /// answers the project it is filed under and that project's members beside it.
7255    ///
7256    /// Each is held for this command as a read of it would have been: the project for the
7257    /// next read of it by its id, and — when its page of members is the whole of them — the
7258    /// members for the next listing of that project. So a write held to who may read the
7259    /// document, which reads all three, is answered by this one request.
7260    async fn document_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7261        if self.created()?.iter().any(|own| own.id == *id) || self.read_ahead()?.contains_key(id) {
7262            return self.item_by_id(id).await;
7263        }
7264        let asked = self
7265            .graphql(
7266                graphql::DOCUMENT_IN_PROJECT,
7267                json!({"id":id.0,"first":MAX_PAGE_SIZE,"memberFirst":MEMBER_PAGE_SIZE,
7268                       "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
7269                       "duplicates":true}),
7270            )
7271            .await;
7272        let data = match asked {
7273            Ok(data) => data,
7274            Err(error) if unresolvable_node(&error) => return Ok(None),
7275            Err(error) => return Err(error),
7276        };
7277        let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
7278            return Ok(None);
7279        };
7280        if optional_str(node, "__typename")? == Some("DraftIssue") {
7281            return self.draft_by_id(id).await;
7282        }
7283        let Some(item) = self.resolve_issue(node).await? else {
7284            return Ok(None);
7285        };
7286        // An answer for another issue than the one asked about says nothing of that one.
7287        if item.id != *id {
7288            return Err(SourceError::Malformed {
7289                message: format!(
7290                    "GitHub answered issue {} when asked for document {}",
7291                    item.id.0, id.0
7292                ),
7293            });
7294        }
7295        if let Some(project) = node.get("project").filter(|value| !value.is_null())
7296            && let Some(parent) = self
7297                .resolve_issue(project)
7298                .await?
7299                .filter(|parent| Some(&parent.id) == item.parent.as_ref())
7300        {
7301            let members = project.get("subIssues").filter(|value| !value.is_null());
7302            let whole = members
7303                .and_then(|members| members.pointer("/pageInfo/hasNextPage"))
7304                .and_then(Value::as_bool)
7305                == Some(false);
7306            if whole {
7307                let nodes = members
7308                    .and_then(|members| members.get("nodes"))
7309                    .and_then(Value::as_array)
7310                    .ok_or_else(|| SourceError::Malformed {
7311                        message: "GitHub subIssues.nodes is not an array".into(),
7312                    })?;
7313                let mut children = Vec::new();
7314                for member in nodes {
7315                    if let Some(resolved) = self.resolve_issue(member).await? {
7316                        children.push(resolved);
7317                    }
7318                }
7319                // Held as the project's members only when every one resolved and says it is
7320                // filed under it: a page with any other answers nothing of all the members.
7321                if children.len() == nodes.len()
7322                    && children
7323                        .iter()
7324                        .all(|child| child.parent.as_ref() == Some(&parent.id))
7325                {
7326                    self.children_cache()?
7327                        .insert(parent.id.clone(), (parent.id.clone(), children));
7328                }
7329            }
7330            self.read_ahead()?.insert(parent.id.clone(), Some(parent));
7331        }
7332        Ok(Some(item))
7333    }
7334
7335    /// Several items of this board, each by its own id, in order — what [`Self::item_by_id`]
7336    /// answers for each, read [`DETAIL_BATCH`] at a time with [`graphql::ISSUE_DETAILS`] rather
7337    /// than one request per id.
7338    ///
7339    /// What this run wrote answers first, as it does there, and only the rest is read. One id
7340    /// left to read is read by [`Self::item_by_id`] itself, which costs what a batch does. A
7341    /// batch GitHub refuses because one of its ids resolves to no node at all is read again one
7342    /// id at a time, so that id is answered as not held and the others as themselves; a draft
7343    /// is completed by a read of the draft, exactly as there.
7344    async fn items_by_ids(&self, ids: &[NativeId]) -> Result<Vec<Option<Resolved>>, SourceError> {
7345        let mut found: Vec<Option<Option<Resolved>>> = {
7346            let created = self.created()?;
7347            ids.iter()
7348                .map(|id| {
7349                    created
7350                        .iter()
7351                        .find(|own| own.id == *id)
7352                        .map(|own| Some(own.clone()))
7353                })
7354                .collect()
7355        };
7356        let unread: Vec<NativeId> = ids
7357            .iter()
7358            .zip(&found)
7359            .filter(|(_, found)| found.is_none())
7360            .map(|(id, _)| id.clone())
7361            .collect();
7362        let mut read = Vec::with_capacity(unread.len());
7363        if let [one] = unread.as_slice() {
7364            read.push(self.item_by_id(one).await?);
7365        } else {
7366            for batch in unread.chunks(DETAIL_BATCH) {
7367                let data = match self
7368                    .graphql(graphql::ISSUE_DETAILS, detail_batch(batch, None))
7369                    .await
7370                {
7371                    Ok(data) => data,
7372                    Err(error) if unresolvable_node(&error) => {
7373                        for id in batch {
7374                            read.push(self.item_by_id(id).await?);
7375                        }
7376                        continue;
7377                    }
7378                    Err(error) => return Err(error),
7379                };
7380                for (slot, id) in batch.iter().enumerate() {
7381                    let node =
7382                        data.get(format!("i{slot}"))
7383                            .ok_or_else(|| SourceError::Malformed {
7384                                message: format!(
7385                                    "GitHub answered a batch read with no item for {}",
7386                                    id.0
7387                                ),
7388                            })?;
7389                    read.push(if node.is_null() {
7390                        None
7391                    } else if optional_str(node, "__typename")? == Some("DraftIssue") {
7392                        self.draft_by_id(id).await?
7393                    } else {
7394                        if optional_str(node, "__typename")? == Some("Issue")
7395                            && required_str(node, "id")? != id.0
7396                        {
7397                            return Err(SourceError::Malformed {
7398                                message: format!(
7399                                    "GitHub answered the read of {} with issue {}",
7400                                    id.0,
7401                                    required_str(node, "id")?
7402                                ),
7403                            });
7404                        }
7405                        self.resolve_issue(node).await?
7406                    });
7407                }
7408            }
7409        }
7410        let mut read = read.into_iter();
7411        Ok(found
7412            .iter_mut()
7413            .map(|slot| slot.take().unwrap_or_else(|| read.next().flatten()))
7414            .collect())
7415    }
7416
7417    fn read_ahead(
7418        &self,
7419    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Option<Resolved>>>, SourceError> {
7420        self.read_ahead
7421            .lock()
7422            .map_err(|_| SourceError::Unavailable {
7423                message:
7424                    "items read ahead for a copy were left inconsistent; run the command again"
7425                        .into(),
7426            })
7427    }
7428
7429    fn resolved_cache(
7430        &self,
7431    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Resolved>>, SourceError> {
7432        self.resolved_cache
7433            .lock()
7434            .map_err(|_| SourceError::Unavailable {
7435                message: "resolved item records were left inconsistent; run the command again"
7436                    .into(),
7437            })
7438    }
7439
7440    /// Reuse a record this invocation already resolved. The mutation sender invalidates
7441    /// it before writing, so a partial failure cannot leave a pre-write binding behind.
7442    async fn bound_item(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7443        let cached = self.resolved_cache()?.get(id).cloned();
7444        if let Some(item) = cached {
7445            return Ok(Some(item));
7446        }
7447        self.item_by_id(id).await
7448    }
7449
7450    /// Take out the item an issue read by reference reached for `id`, when one is held: the
7451    /// status write it was read for is the one caller, so no other read or write is ever
7452    /// answered from a read that selected only what that write needs.
7453    fn take_held(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7454        Ok(self
7455            .held_cache
7456            .lock()
7457            .map_err(|_| SourceError::Unavailable {
7458                message: "items read by issue reference were left inconsistent; run the \
7459                          command again"
7460                    .into(),
7461            })?
7462            .remove(id))
7463    }
7464
7465    /// One board draft by its own id, with the board item it sits in — or `None` when no
7466    /// item of this board is that draft's.
7467    ///
7468    /// The same decision [`Self::resolve_issue`] makes for an issue, over the draft's own
7469    /// `projectV2Items`: an entry naming this board is what makes it this board's. GitHub
7470    /// links a draft to one board item, so the page this read carries is the whole of that
7471    /// connection, and a page that reports more than it holds is refused rather than read
7472    /// as an answer about memberships nobody read.
7473    async fn draft_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7474        let data = self
7475            .graphql(
7476                graphql::DRAFT,
7477                json!({"id":id.0,"nestedFirst":NESTED_PAGE_SIZE,
7478                       "boardItems":BOARD_ITEMS_PAGE_SIZE}),
7479            )
7480            .await?;
7481        // Gone between the two reads is an answer — the draft is no longer there. Anything
7482        // else than the draft [`Self::reach`] was just told this id is, is not one.
7483        let Some(draft) = data.get("node").filter(|node| !node.is_null()) else {
7484            return Ok(None);
7485        };
7486        if optional_str(draft, "__typename")? != Some("DraftIssue") {
7487            return Err(SourceError::Malformed {
7488                message: format!(
7489                    "GitHub answered {} as a draft and then as something else",
7490                    id.0
7491                ),
7492            });
7493        }
7494        if required_str(draft, "id")? != id.0 {
7495            return Err(SourceError::Malformed {
7496                message: format!("GitHub answered a different draft for {}", id.0),
7497            });
7498        }
7499        let memberships = draft
7500            .get("projectV2Items")
7501            .ok_or_else(|| SourceError::Malformed {
7502                message: format!("GitHub draft {} is missing projectV2Items", id.0),
7503            })?;
7504        let nodes = memberships
7505            .get("nodes")
7506            .and_then(Value::as_array)
7507            .ok_or_else(|| SourceError::Malformed {
7508                message: format!("GitHub draft {} projectV2Items.nodes is not an array", id.0),
7509            })?;
7510        let info = memberships
7511            .get("pageInfo")
7512            .ok_or_else(|| SourceError::Malformed {
7513                message: format!("GitHub draft {} projectV2Items has no pageInfo", id.0),
7514            })?;
7515        // Read whether or not this board's entry is on the page: a page claiming more than
7516        // the one item GitHub links a draft to is a malformed answer either way.
7517        if required_bool(info, "hasNextPage")? || nodes.len() > 1 {
7518            return Err(SourceError::Malformed {
7519                message: format!(
7520                    "GitHub draft {} reports more board items than the one GitHub links a draft \
7521                     to",
7522                    id.0
7523                ),
7524            });
7525        }
7526        if let Some(node) = nodes.first()
7527            && node
7528                .pointer("/project/number")
7529                .and_then(Value::as_u64)
7530                .is_none()
7531        {
7532            return Err(SourceError::Malformed {
7533                message: format!(
7534                    "GitHub draft {} board item has no numeric project number",
7535                    id.0
7536                ),
7537            });
7538        }
7539        let Some(held) = self.board_entry(nodes) else {
7540            return Ok(None);
7541        };
7542        if required_str(
7543            held.get("project").ok_or_else(|| SourceError::Malformed {
7544                message: format!("GitHub draft {} board item has no project", id.0),
7545            })?,
7546            "id",
7547        )? != self.board_fields().await?.id.as_str()
7548        {
7549            return Ok(None);
7550        }
7551        let item = json!({
7552            "id": required_str(held, "id")?,
7553            "project": held.get("project"),
7554            "fieldValues": held.get("fieldValues"),
7555            "content": draft,
7556        });
7557        self.resolve(&item)
7558    }
7559
7560    /// The board's own id and field definitions, for a write whose item does not carry
7561    /// them — never its items.
7562    ///
7563    /// A board this command has already listed supplies them, since it read them beside its
7564    /// items; otherwise they come from [`graphql::BOARD_FIELDS`], once per command. Neither
7565    /// is consulted about which items the board holds: see the module documentation for
7566    /// why a question about one known item is answered by reading that item.
7567    async fn board_fields(&self) -> Result<BoardFields, SourceError> {
7568        if let Some(board) = self.board_cache()?.as_ref() {
7569            return Ok(BoardFields {
7570                id: BoardId::parse(&board.id)?,
7571                fields: board.fields.clone(),
7572            });
7573        }
7574        if let Some(held) = self.fields_cache()?.clone() {
7575            return Ok(held);
7576        }
7577        let data = self
7578            .graphql(
7579                graphql::BOARD_FIELDS,
7580                json!({"owner":self.owner,"number":self.project_number,
7581                       "nestedFirst":NESTED_PAGE_SIZE}),
7582            )
7583            .await?;
7584        self.fields_read(&data)
7585    }
7586
7587    /// The board's id and fields out of an answer carrying the `boardFields` root, held for
7588    /// the rest of this command.
7589    fn fields_read(&self, data: &Value) -> Result<BoardFields, SourceError> {
7590        let board = data
7591            .pointer("/boardFields/projectV2")
7592            .filter(|value| !value.is_null())
7593            .ok_or_else(|| SourceError::Refused {
7594                message: format!(
7595                    "GitHub project {}/{} was not found or is not visible to the token",
7596                    self.owner, self.project_number
7597                ),
7598            })?;
7599        let read = BoardFields {
7600            id: BoardId::parse(required_str(board, "id")?)?,
7601            fields: board.get("fields").cloned().unwrap_or(Value::Null),
7602        };
7603        *self.fields_cache()? = Some(read.clone());
7604        Ok(read)
7605    }
7606
7607    /// Read what creating an issue in `repository` needs and this command has not read yet —
7608    /// the board's fields and the repository's node id — in one request when it needs both.
7609    ///
7610    /// When either is already known this sends nothing, and the other is read by its own
7611    /// document where it is asked for, so no create reads anything twice.
7612    async fn creation_context(
7613        &self,
7614        repository: &RepositoryTarget,
7615        incoming: &Incoming<'_>,
7616    ) -> Result<(), SourceError> {
7617        let fields_known = self.board_cache()?.is_some() || self.fields_cache()?.is_some();
7618        if fields_known || self.repository_cache()?.contains_key(repository) {
7619            return Ok(());
7620        }
7621        // A placement an earlier process kept is taken only while the project issue this create
7622        // has just read shows its setup-context token unchanged; see `projection`.
7623        if self.placed_by_kept(repository, incoming.parent) {
7624            return Ok(());
7625        }
7626        let data = self
7627            .graphql(
7628                graphql::CREATION_CONTEXT,
7629                json!({"owner":self.owner,"number":self.project_number,
7630                       "nestedFirst":NESTED_PAGE_SIZE,"repositoryOwner":repository.owner,
7631                       "repositoryName":repository.name}),
7632            )
7633            .await?;
7634        self.fields_read(&data)?;
7635        self.repository_read(&data, repository, incoming)?;
7636        Ok(())
7637    }
7638
7639    /// This process's own view of the board's fields, or the refusal a poisoned lock is.
7640    fn fields_cache(&self) -> Result<std::sync::MutexGuard<'_, Option<BoardFields>>, SourceError> {
7641        self.fields_cache
7642            .lock()
7643            .map_err(|_| SourceError::Unavailable {
7644                message: "this source's view of the board's fields was left inconsistent by an \
7645                      earlier failure; next: run the command again"
7646                    .into(),
7647            })
7648    }
7649
7650    /// What a write to `item` needs of the board, read off that item when it says enough and
7651    /// off [`Self::board_fields`] when it does not.
7652    ///
7653    /// A node read of an item names its board and carries the definition of every field it
7654    /// holds a value of — so an item naming its board, holding a value of the origin field
7655    /// when the write carries an origin, and, when the write carries a status, holding a
7656    /// `Status` value, needs no read of the board at all. **Nothing the item does not say is
7657    /// guessed:** a field it holds no value of may still be on the board, and a view reading it
7658    /// as absent would refuse a write the board can take or skip a field write the board
7659    /// needs, so such an item — and a create, which has no item yet — takes the board's fields
7660    /// from their own read instead. A write carrying no origin to an item holding none — every
7661    /// write out of a source declared private — writes no origin whatever the board defines,
7662    /// so it needs no definition of that field.
7663    async fn fields_for(
7664        &self,
7665        item: Option<&Resolved>,
7666        writes_origin: bool,
7667        writes_status: bool,
7668        selects_priority: bool,
7669    ) -> Result<BoardFields, SourceError> {
7670        if let Some(board) = item.and_then(Resolved::carried_board) {
7671            return Ok(board);
7672        }
7673        if let Some(item) = item
7674            && let Some(board_id) = item.named_board()
7675            && (!writes_origin || item.defines(ORIGIN_FIELD))
7676            && (!writes_status || item.defines("Status"))
7677            && (!selects_priority || item.defines(PRIORITY_FIELD))
7678            && self
7679                .metadata_fields
7680                .iter()
7681                .all(|projection| item.defines(&projection.field))
7682        {
7683            return Ok(BoardFields {
7684                id: board_id,
7685                fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
7686            });
7687        }
7688        self.board_fields().await
7689    }
7690
7691    /// Everything filed under one issue of this board, walked to exhaustion — or `None`
7692    /// when that id names nothing here with a sub-issue relationship to walk.
7693    ///
7694    /// `None` and an empty answer are different: `None` is *this is not an issue of this
7695    /// GitHub*, which is what sends a project selector on to be read as a name, and an
7696    /// empty vector is a project that holds nothing.
7697    async fn sub_issues(&self, id: &NativeId) -> Result<Option<Vec<Resolved>>, SourceError> {
7698        let mut after: Option<String> = None;
7699        let mut children = Vec::new();
7700        // The project issue as the first page carried it, held once the walk has ended.
7701        let mut parent: Option<Resolved> = None;
7702        loop {
7703            let asked = self
7704                .graphql(
7705                    graphql::SUB_ISSUES,
7706                    json!({"id":id.0,"memberFirst":MEMBER_PAGE_SIZE,"after":after,
7707                           "nestedFirst":NESTED_PAGE_SIZE,
7708                           "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
7709                )
7710                .await;
7711            let data = match asked {
7712                Ok(data) => data,
7713                // A string that is not a node id at all is not a failure to report: it is
7714                // the ordinary answer to a selector naming a project by its name.
7715                Err(error) if unresolvable_node(&error) => return Ok(None),
7716                Err(error) => return Err(error),
7717            };
7718            let Some(connection) = data
7719                .pointer("/node/subIssues")
7720                .filter(|value| !value.is_null())
7721            else {
7722                // No such node, or one with no sub-issue relationship — a board draft is
7723                // the one this board can really hold.
7724                return Ok(None);
7725            };
7726            if after.is_none()
7727                && let Some(node) = data.get("node").filter(|node| node.get("id").is_some())
7728            {
7729                parent = self
7730                    .resolve_issue(node)
7731                    .await?
7732                    .filter(|resolved| resolved.id == *id);
7733            }
7734            for node in connection
7735                .get("nodes")
7736                .and_then(Value::as_array)
7737                .ok_or_else(|| SourceError::Malformed {
7738                    message: "GitHub subIssues.nodes is not an array".into(),
7739                })?
7740            {
7741                if let Some(resolved) = self.resolve_issue(node).await? {
7742                    children.push(resolved);
7743                }
7744            }
7745            let info = connection
7746                .get("pageInfo")
7747                .ok_or_else(|| SourceError::Malformed {
7748                    message: "GitHub subIssues connection has no pageInfo".into(),
7749                })?;
7750            let next = required_bool(info, "hasNextPage")?
7751                .then(|| required_str(info, "endCursor"))
7752                .transpose()?;
7753            match next {
7754                Some(next) => {
7755                    validate_cursor_progress(after.as_deref(), next)?;
7756                    after = Some(next.to_owned());
7757                }
7758                None => {
7759                    // Held only once the walk has ended, so one failing part way holds
7760                    // nothing and every read it would have answered is made.
7761                    // The project issue the first page carried answers the next read of the
7762                    // project by its id in this command, as a read of it made now would: what
7763                    // classifying a project for a write reads straight after its members.
7764                    if let Some(parent) = &parent {
7765                        self.read_ahead()?
7766                            .entry(parent.id.clone())
7767                            .or_insert_with(|| Some(parent.clone()));
7768                    }
7769                    let mut carried = self.carried()?;
7770                    for item in parent.into_iter().chain(children.iter().cloned()) {
7771                        carried.insert(item.id.clone(), item);
7772                    }
7773                    return Ok(Some(children));
7774                }
7775            }
7776        }
7777    }
7778
7779    fn carried(
7780        &self,
7781    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Resolved>>, SourceError> {
7782        self.carried.lock().map_err(|_| SourceError::Unavailable {
7783            message: "items a project's listing carried were left inconsistent; run the \
7784                      command again"
7785                .into(),
7786        })
7787    }
7788
7789    /// Which issue of this board a project *name* is, or `None` when none is.
7790    ///
7791    /// One bounded query which filters on that name at the server, rather than a walk of
7792    /// every issue the board holds. The name is compared again here: the qualifier narrows
7793    /// what GitHub sends, and this source decides what it names.
7794    async fn project_by_name(&self, name: &str) -> Result<Option<NativeId>, SourceError> {
7795        let search = self.board_search(Some(&title_qualifier(name)));
7796        let mut after = None;
7797        loop {
7798            let (candidates, next) = self
7799                .search_page(&search, SEARCH_PAGE_SIZE, after.as_deref())
7800                .await?;
7801            if let Some(item) = candidates.into_iter().find(|item| {
7802                item.kind == BoardKind::Work(ItemKind::Project)
7803                    && item.title.eq_ignore_ascii_case(name)
7804            }) {
7805                return Ok(Some(item.id));
7806            }
7807            match next {
7808                Some(next) => after = Some(next),
7809                None => return Ok(None),
7810            }
7811        }
7812    }
7813
7814    /// Everything filed under one project of this board: the sub-issues of the issue that
7815    /// project is.
7816    ///
7817    /// Tasks *and* documents, because a document filed under a project is a sub-issue of it
7818    /// too — the caller keeps the kind it asked for. Nothing about this grows as the board
7819    /// gains projects, or as another project gains tasks.
7820    ///
7821    /// A qualified id names the issue and is asked for its sub-issues directly: one
7822    /// request, no search of any kind. Only a selector GitHub cannot resolve that way is
7823    /// read as a project *name*, which costs the one bounded search
7824    /// [`Self::project_by_name`] makes.
7825    ///
7826    /// What GitHub answered is held for the rest of the command — see [`Self::children_cache`]
7827    /// — and each answer is still cut to the items whose parent is this project, so one this
7828    /// process has since filed elsewhere is not reported here, and completed with what this
7829    /// process filed under it.
7830    async fn project_children(&self, selector: &NativeId) -> Result<Vec<Resolved>, SourceError> {
7831        let held = self.children_cache()?.get(selector).cloned();
7832        let (project, children) = match held {
7833            Some(held) => held,
7834            None => {
7835                let answered = match self.sub_issues(selector).await? {
7836                    Some(children) => (selector.clone(), children),
7837                    None => match self.project_by_name(&selector.0).await? {
7838                        Some(project) => {
7839                            let children = self.sub_issues(&project).await?.unwrap_or_default();
7840                            (project, children)
7841                        }
7842                        None => return Ok(Vec::new()),
7843                    },
7844                };
7845                self.children_cache()?
7846                    .insert(selector.clone(), answered.clone());
7847                answered
7848            }
7849        };
7850        let mut children: Vec<Resolved> = children
7851            .into_iter()
7852            .filter(|child| child.parent.as_ref() == Some(&project))
7853            .collect();
7854        for own in self.updated()?.iter() {
7855            if own.parent.as_ref() == Some(&project) && !children.iter().any(|c| c.id == own.id) {
7856                children.push(own.clone());
7857            }
7858        }
7859        self.completed_with_written(children, |own| own.parent.as_ref() == Some(&project))
7860    }
7861
7862    /// Every issue of this board GitHub's issue search reports updated at or after `since`,
7863    /// completed with what this run wrote — the candidates a comment-activity read confirms.
7864    ///
7865    /// Scoped by the board and by nothing else: `project:<owner>/<number>` reaches every issue
7866    /// on the board whatever repository, and whatever owner, it lives in, so no repository or
7867    /// owner qualifier is added and none is needed. What makes the `updated:` qualifier
7868    /// sufficient is a fact about GitHub rather than about this source: a comment written on an
7869    /// issue **and a comment edited on it** both move that issue's `updatedAt`. The credentialed
7870    /// journey `an_edited_comment_moves_its_issue_and_is_selected_since` in `tests/journey`
7871    /// re-takes that fact on every run of the lane, so a change on GitHub's side fails there
7872    /// rather than silently narrowing a caller's answer.
7873    ///
7874    /// The instant is written to the second, rounded down, which can only widen what the
7875    /// search returns; confirmation against each candidate's own comments is what makes the
7876    /// answer exact. The search is an index that lags a write by a second or two — the module
7877    /// documentation records it — so a caller that asks again from its last instant should
7878    /// overlap the two by more than that.
7879    async fn updated_since(&self, since: DateTime<Utc>) -> Result<Vec<Resolved>, SourceError> {
7880        let found = self.searched(&updated_qualifier(since)).await?;
7881        self.completed_with_written(found, |_| true)
7882    }
7883
7884    /// Every issue of this board GitHub's issue search reports for the board-scoped search
7885    /// narrowed by `also`, in pages of [`SEARCH_PAGE_SIZE`].
7886    ///
7887    /// Uncompleted: what this process wrote is added by the caller, which knows whether its
7888    /// own record is the fresher of the two.
7889    async fn searched(&self, also: &str) -> Result<Vec<Resolved>, SourceError> {
7890        let search = self.board_search(Some(also));
7891        let mut after: Option<String> = None;
7892        let mut found = Vec::new();
7893        loop {
7894            let (page, next) = self
7895                .search_page(&search, SEARCH_PAGE_SIZE, after.as_deref())
7896                .await?;
7897            found.extend(page);
7898            match next {
7899                Some(next) => after = Some(next),
7900                None => return Ok(found),
7901            }
7902        }
7903    }
7904
7905    /// A bounded task answer; the versioned cursor carries the connection position, how
7906    /// many rows of the page starting there were already handed out, and the own-write ids
7907    /// already observed, including across a new source instance.
7908    ///
7909    /// Every page is sent at [`SEARCH_PAGE_SIZE`] whatever the caller's limit, and a limit is
7910    /// sliced from the pages it needs; why is the module documentation's paging contract.
7911    async fn search_tasks(
7912        &self,
7913        query: &TaskQuery,
7914        page: &PageRequest,
7915        also: &str,
7916    ) -> Result<Page<Task>, SourceError> {
7917        let mut position = match &page.cursor {
7918            None => SearchPosition::default(),
7919            Some(cursor) => serde_json::from_str::<SearchPosition>(&cursor.0)
7920                .ok()
7921                .filter(|position| {
7922                    position.version == SEARCH_CURSOR_VERSION
7923                        && position.connection.valid_resume(position.offset)
7924                })
7925                .ok_or_else(|| SourceError::Config {
7926                    message: "page cursor is invalid".into(),
7927                })?,
7928        };
7929        let search = self.board_search(Some(also));
7930        let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
7931        let own = self.with_own_writes(Vec::new())?;
7932        // An issue this process commented on is a candidate of a comment-activity read
7933        // whether or not the search has caught up with the comment; see `Self::commented`.
7934        let commented = match query.commented_since {
7935            Some(_) => self.commented()?.clone(),
7936            None => Vec::new(),
7937        };
7938        for id in own.iter().map(|item| &item.id).chain(&commented) {
7939            if !position.own.contains(id) {
7940                position.own.push(id.clone());
7941            }
7942        }
7943        let mut tasks = Vec::new();
7944        while !position.connection.exhausted() && tasks.len() < limit {
7945            let first = SEARCH_PAGE_SIZE;
7946            // Page size is part of the key: a short cached answer cannot answer a wider ask.
7947            let key =
7948                serde_json::to_string(&("page", &search, &position.connection.after(), first))
7949                    .expect("search page key is serializable");
7950            let cached = if query.commented_since.is_none() {
7951                self.narrowed_cache()?.get(&key).cloned()
7952            } else {
7953                None
7954            };
7955            let (found, next) = match cached {
7956                Some(found) => {
7957                    let next = self
7958                        .search_next
7959                        .lock()
7960                        .map_err(|_| SourceError::Unavailable {
7961                            message:
7962                                "search pagination was left inconsistent; run the command again"
7963                                    .into(),
7964                        })?
7965                        .get(&key)
7966                        .cloned()
7967                        .flatten();
7968                    (found, next)
7969                }
7970                None => {
7971                    let (found, next) = self
7972                        .search_page(&search, first, position.connection.after())
7973                        .await?;
7974                    if query.commented_since.is_none() {
7975                        self.search_next
7976                            .lock()
7977                            .map_err(|_| SourceError::Unavailable {
7978                                message:
7979                                    "search pagination was left inconsistent; run the command again"
7980                                        .into(),
7981                            })?
7982                            .insert(key.clone(), next.clone());
7983                        self.narrowed_cache()?.insert(key, found.clone());
7984                    }
7985                    (found, next)
7986                }
7987            };
7988            let rows = found.len();
7989            // Every candidate of the page this read confirms by its comments is read together.
7990            let candidates =
7991                self.comment_candidates(found.iter().skip(position.offset), query, &query.project)?;
7992            self.hold_comment_pages(&candidates).await?;
7993            for mut item in found.into_iter().skip(position.offset) {
7994                if tasks.len() == limit {
7995                    break;
7996                }
7997                position.offset += 1;
7998                if position.own.contains(&item.id) {
7999                    if position.seen.contains(&item.id) {
8000                        continue;
8001                    }
8002                    position.seen.push(item.id.clone());
8003                    // The search's own copy of an issue this process only commented on is as
8004                    // good as a node read of it, since its comments are read either way.
8005                    let only_commented = commented.contains(&item.id)
8006                        && !own.iter().any(|written| written.id == item.id);
8007                    if !only_commented {
8008                        let updated_at = item.updated_at;
8009                        let Some(written) = self.search_written(&own, &item.id).await? else {
8010                            continue;
8011                        };
8012                        item = written;
8013                        item.updated_at = item.updated_at.max(updated_at);
8014                        self.resolved_cache()?.insert(item.id.clone(), item.clone());
8015                    }
8016                }
8017                if item.kind == BoardKind::Work(ItemKind::Task) {
8018                    let task = item.task()?;
8019                    if task_matches(&task, query, &query.project)
8020                        && self.commented_since(&item, query.commented_since).await?
8021                    {
8022                        tasks.push(task);
8023                    }
8024                }
8025            }
8026            if position.offset < rows {
8027                continue;
8028            }
8029            position.offset = 0;
8030            position.connection = match next {
8031                Some(after) => SearchConnection::Continuing {
8032                    after: Cursor(after),
8033                },
8034                None => SearchConnection::Exhausted {},
8035            };
8036        }
8037        if position.connection.exhausted() {
8038            for id in position.own.clone() {
8039                if position.seen.contains(&id) {
8040                    continue;
8041                }
8042                if tasks.len() == limit {
8043                    break;
8044                }
8045                position.seen.push(id.clone());
8046                let Some(item) = self.search_written(&own, &id).await? else {
8047                    continue;
8048                };
8049                if item.kind == BoardKind::Work(ItemKind::Task) {
8050                    let task = item.task()?;
8051                    if task_matches(&task, query, &query.project)
8052                        && self.commented_since(&item, query.commented_since).await?
8053                    {
8054                        tasks.push(task);
8055                    }
8056                }
8057            }
8058        }
8059        let more = !position.connection.exhausted()
8060            || position.own.iter().any(|id| !position.seen.contains(id));
8061        Ok(Page {
8062            items: tasks,
8063            next: more.then(|| {
8064                Cursor(serde_json::to_string(&position).expect("search position is serializable"))
8065            }),
8066        })
8067    }
8068
8069    /// A resumed process has the ids but no write records; resolve only a record the
8070    /// current page needs, by its uncached node read rather than the lagging search index.
8071    async fn search_written(
8072        &self,
8073        own: &[Resolved],
8074        id: &NativeId,
8075    ) -> Result<Option<Resolved>, SourceError> {
8076        match own.iter().find(|item| item.id == *id) {
8077            Some(item) => Ok(Some(item.clone())),
8078            None => self.item_by_id(id).await,
8079        }
8080    }
8081
8082    /// The candidates for a task query carrying a text, metadata or origin predicate, read
8083    /// without enumerating the board — or `None` for a query carrying none of the three, which
8084    /// keeps the reads it always had.
8085    ///
8086    /// An origin is answered by [`Self::origin_candidates`], whatever else the query carries,
8087    /// because it names at most a handful of items. Text and metadata are answered by one
8088    /// board-scoped issue search carrying every term — see [`narrowing_qualifiers`] — narrowed
8089    /// further by `updated:>=` when the query also asks for comment activity, since both
8090    /// qualifiers must hold of an issue the answer keeps. Every candidate is confirmed in
8091    /// process afterwards by the same predicates [`task_matches`] applies to every read.
8092    ///
8093    /// Completed with what this process wrote, its own record winning over the index's copy
8094    /// of the same item: see [`Self::with_own_writes`].
8095    async fn narrowed(&self, query: &TaskQuery) -> Result<Option<Vec<Resolved>>, SourceError> {
8096        self.send_pending_origins(None).await?;
8097        let asked = match (&query.origin, narrowing_qualifiers(query)) {
8098            (Some(origin), _) => Narrowing::Origin(origin.clone()),
8099            (None, Some(qualifiers)) => Narrowing::Search(match query.commented_since {
8100                Some(since) => format!("{} {qualifiers}", updated_qualifier(since)),
8101                None => qualifiers,
8102            }),
8103            (None, None) => return Ok(None),
8104        };
8105        // A question about comment activity is asked afresh every time, as it always was: it
8106        // is the one a caller polls from one source while waiting for the index, and an
8107        // answer held from the first poll would be the answer to every later one.
8108        let key = query.commented_since.is_none().then(|| asked.key());
8109        let cached = match &key {
8110            Some(key) => self.narrowed_cache()?.get(key).cloned(),
8111            None => None,
8112        };
8113        let found = match cached {
8114            Some(found) => found,
8115            None => {
8116                let found = match &asked {
8117                    Narrowing::Origin(origin) => self.origin_candidates(origin).await?,
8118                    Narrowing::Search(also) => self.searched(also).await?,
8119                };
8120                if let Some(key) = key {
8121                    self.narrowed_cache()?.insert(key, found.clone());
8122                }
8123                found
8124            }
8125        };
8126        self.with_own_writes(found).map(Some)
8127    }
8128
8129    /// The candidates for a project or unscoped document query carrying a searchable text,
8130    /// read without enumerating the board — or `None` for a query with no text or a blank one,
8131    /// which keeps the read it always had.
8132    ///
8133    /// The text is sent as the very phrase a task query's text is — see [`text_qualifiers`] —
8134    /// in one board-scoped issue search walked to its end at [`SEARCH_PAGE_SIZE`], so what it
8135    /// costs is the issues that match and never the board. Its answer is held for the command
8136    /// under the same key [`Self::narrowed`] holds that search under, so a walk of the caller's
8137    /// pages asks GitHub once. Every candidate is confirmed afterwards by its kind and by the
8138    /// substring rule, exactly as an item of the wider read was, and is completed with what this
8139    /// process wrote: see [`Self::with_own_writes`].
8140    async fn text_searched(
8141        &self,
8142        text: Option<&TextQuery>,
8143    ) -> Result<Option<Vec<Resolved>>, SourceError> {
8144        let Some(also) = text_qualifiers(text) else {
8145            return Ok(None);
8146        };
8147        let key = Narrowing::Search(also.clone()).key();
8148        let cached = self.narrowed_cache()?.get(&key).cloned();
8149        let found = match cached {
8150            Some(found) => found,
8151            None => {
8152                let found = self.searched(&also).await?;
8153                self.narrowed_cache()?.insert(key, found.clone());
8154                found
8155            }
8156        };
8157        self.with_own_writes(found).map(Some)
8158    }
8159
8160    /// Every `kind` item of this board whose own origin is exactly `origin`: the candidates
8161    /// [`Self::narrowed`] reads for a task query carrying that origin — one
8162    /// [`graphql::ORIGIN_LOOKUP`] walk, held for the command under the same key, completed with
8163    /// what this process wrote — each confirmed against its own origin entry.
8164    ///
8165    /// What answers a project or document listing by origin, so finding every copy of one plan
8166    /// costs the items that carry its origin and never a page of the board.
8167    async fn copied_from(
8168        &self,
8169        origin: &str,
8170        kind: BoardKind,
8171    ) -> Result<Vec<Resolved>, SourceError> {
8172        let wanted = TaskQuery {
8173            origin: Some(origin.to_owned()),
8174            ..TaskQuery::default()
8175        };
8176        Ok(self
8177            .narrowed(&wanted)
8178            .await?
8179            .unwrap_or_default()
8180            .into_iter()
8181            .filter(|item| item.kind == kind && wanted.origin_matches(&item.metadata()))
8182            .collect())
8183    }
8184
8185    /// Every item of this board that may carry `origin` — a superset of those that do — found
8186    /// by [`graphql::ORIGIN_LOOKUP`] and never by enumerating the board.
8187    ///
8188    /// The union of the board's own field filter over the `onetaskgraph.origin` text field —
8189    /// which reads the field every carrier holds, whichever release wrote it — and the
8190    /// board-scoped issue search for the same id as a phrase in the body, where this source
8191    /// mirrors it. The caller adds the third read, this process's own writes. Candidates are
8192    /// returned unconfirmed; [`task_matches`] compares each one's own origin field with the
8193    /// query's, exactly.
8194    ///
8195    /// Both connections are walked to exhaustion, each from its own cursor. One that has
8196    /// already ended is sent its last cursor again, which answers an empty page, so the one
8197    /// document serves every page of either. What the two leave is stated in the module
8198    /// documentation: a carrier another process added within the last second or two, before
8199    /// either index has it.
8200    async fn origin_candidates(&self, origin: &str) -> Result<Vec<Resolved>, SourceError> {
8201        let filter = format!("{ORIGIN_FIELD}:{}", quoted(origin));
8202        let search = self.board_search(Some(&format!("in:body {}", quoted(&as_stored(origin)))));
8203        let mut items_after: Option<String> = None;
8204        let mut search_after: Option<String> = None;
8205        let mut found: Vec<Resolved> = Vec::new();
8206        let keep = |resolved: Resolved, found: &mut Vec<Resolved>| {
8207            if !found.iter().any(|held| held.id == resolved.id) {
8208                found.push(resolved);
8209            }
8210        };
8211        loop {
8212            let data = self
8213                .graphql(
8214                    graphql::ORIGIN_LOOKUP,
8215                    json!({"owner":self.owner,"number":self.project_number,"filter":filter,
8216                           "search":search,"type":"ISSUE","originFirst":ORIGIN_PAGE_SIZE,
8217                           "itemsAfter":items_after,"searchAfter":search_after,
8218                           "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
8219                           "duplicates":true}),
8220                )
8221                .await?;
8222            let items = data
8223                .pointer("/originItems/projectV2/items")
8224                .filter(|value| !value.is_null())
8225                .ok_or_else(|| SourceError::Refused {
8226                    message: format!(
8227                        "GitHub project {}/{} was not found or is not visible to the token",
8228                        self.owner, self.project_number
8229                    ),
8230                })?;
8231            for item in optional_nodes(Some(items), "project items")?
8232                .into_iter()
8233                .flatten()
8234            {
8235                // The board's own items list its drafts too, and a draft is not an issue: no
8236                // narrowed read answers with one, whatever its origin field holds.
8237                if let Some(resolved) = self.resolve(item)?
8238                    && resolved.content_kind == ContentKind::Issue
8239                {
8240                    keep(resolved, &mut found);
8241                }
8242            }
8243            let searched = data.get("search").ok_or_else(|| SourceError::Malformed {
8244                message: "GitHub search response has no search connection".into(),
8245            })?;
8246            for node in optional_nodes(Some(searched), "search")?
8247                .into_iter()
8248                .flatten()
8249            {
8250                if let Some(resolved) = self.resolve_issue(node).await? {
8251                    keep(resolved, &mut found);
8252                }
8253            }
8254            let items_next = resumed(items, items_after.as_deref())?;
8255            let search_next = resumed(searched, search_after.as_deref())?;
8256            if !items_next.has_more() && !search_next.has_more() {
8257                return Ok(found);
8258            }
8259            items_after = items_next.cursor();
8260            search_after = search_next.cursor();
8261        }
8262    }
8263
8264    /// `found`, with every item this process created or wrote in its place, and every one of
8265    /// them the read did not report added.
8266    ///
8267    /// This process's own record wins over the read's copy of the same item, because a read
8268    /// of an item written moments ago can still be behind what was written onto it — the
8269    /// origin field included, which is the one a narrowed read is confirmed against — and a
8270    /// read that still names an item under a predicate this process's write moved it out of
8271    /// must not return it. The one thing the read knows that the record cannot is when GitHub
8272    /// last saw the item change, which is what a comment-activity read rules a candidate out
8273    /// by, so the read's `updatedAt` is kept when the record has none of its own. See
8274    /// [`Self::created`] and [`Self::updated`](GitHubProjectsSource::updated).
8275    fn with_own_writes(&self, mut found: Vec<Resolved>) -> Result<Vec<Resolved>, SourceError> {
8276        // A board draft is not an issue, so no narrowed read returns one, and this process
8277        // having written one does not make it an answer either.
8278        let own: Vec<Resolved> = self
8279            .created()?
8280            .iter()
8281            .chain(self.updated()?.iter())
8282            .filter(|own| own.content_kind == ContentKind::Issue)
8283            .cloned()
8284            .collect();
8285        for mut own in own {
8286            self.resolved_cache()?.insert(own.id.clone(), own.clone());
8287            match found.iter_mut().find(|read| read.id == own.id) {
8288                Some(read) => {
8289                    own.updated_at = own.updated_at.max(read.updated_at);
8290                    *read = own;
8291                }
8292                None => found.push(own),
8293            }
8294        }
8295        Ok(found)
8296    }
8297
8298    /// Whether `item` has a comment created or last edited at or after `since` — always, when
8299    /// there is no instant to hold it to.
8300    ///
8301    /// The candidate's own `updatedAt` is read first, because a comment written or edited at
8302    /// or after the instant moved it there: an issue not updated since holds no such comment,
8303    /// and its comments are never asked for — unless this process commented on it in this
8304    /// command, when the `updatedAt` held may predate that comment; see [`Self::commented`]. Otherwise its comments are walked, oldest first,
8305    /// only as far as the first that matches. A board draft is not an issue and has no
8306    /// comments, so it never matches.
8307    async fn commented_since(
8308        &self,
8309        item: &Resolved,
8310        since: Option<DateTime<Utc>>,
8311    ) -> Result<bool, SourceError> {
8312        let Some(since) = since else {
8313            return Ok(true);
8314        };
8315        if item.content_kind == ContentKind::DraftIssue {
8316            return Ok(false);
8317        }
8318        // An `updatedAt` this process's own record or a lagging index holds can predate a
8319        // comment this process wrote since, so only an issue it did not comment on is ruled
8320        // out by one.
8321        if item.updated_at.is_some_and(|updated| updated < since)
8322            && !self.commented()?.contains(&item.id)
8323        {
8324            return Ok(false);
8325        }
8326        let query = TaskQuery {
8327            commented_since: Some(since),
8328            ..TaskQuery::default()
8329        };
8330        let mut after: Option<String> = None;
8331        // A first page read beside its fellow candidates answers as this read's own would.
8332        let held = self.held_comments()?.get(&item.id).cloned();
8333        if let Some(first) = held {
8334            if query.comments_match(&first.items) {
8335                return Ok(true);
8336            }
8337            match first.next {
8338                Some(next) => after = Some(next.0),
8339                None => return Ok(false),
8340            }
8341        }
8342        loop {
8343            let data = self
8344                .graphql(
8345                    graphql::ISSUE_COMMENTS,
8346                    json!({"id":item.id.0,"first":MAX_PAGE_SIZE,"after":after}),
8347                )
8348                .await?;
8349            let Some(connection) = data
8350                .get("node")
8351                .filter(|value| !value.is_null())
8352                .and_then(|node| node.get("comments"))
8353                .filter(|value| !value.is_null())
8354            else {
8355                // Removed since the search reported it: no longer an issue with comments.
8356                return Ok(false);
8357            };
8358            let comments = optional_nodes(Some(connection), "issue comments")?
8359                .into_iter()
8360                .flatten()
8361                .map(comment_from)
8362                .collect::<Result<Vec<_>, _>>()?;
8363            if query.comments_match(&comments) {
8364                return Ok(true);
8365            }
8366            match next_cursor(connection)? {
8367                Some(next) => {
8368                    validate_cursor_progress(after.as_deref(), &next.0)?;
8369                    after = Some(next.0);
8370                }
8371                None => return Ok(false),
8372            }
8373        }
8374    }
8375
8376    /// Every item on the board: the union of both enumerations GitHub offers of one.
8377    ///
8378    /// Neither contains the other, so neither is dropped — only `ProjectV2.items` lists a
8379    /// board **draft** and reads the board's own fields beside its items, and only the search
8380    /// reports an item that connection is behind on. The module documentation is where the lag and the
8381    /// measurements behind it are written down.
8382    ///
8383    /// A search result is admitted on the same terms as any other issue this source reaches
8384    /// directly — [`Self::resolve_issue`] keeps it only if that issue's own `projectItems`
8385    /// names *this* board — so an issue the index still believes is here after it was taken
8386    /// off is refused rather than reported.
8387    ///
8388    /// See [`Self::board_cache`]. Both completions happen on every call rather than once,
8389    /// which is what the cache could otherwise have broken.
8390    async fn board(&self) -> Result<Board, SourceError> {
8391        self.board_completed_by(None).await
8392    }
8393
8394    /// [`Self::board`], its search half narrowed by `also` when it is given — which an issue
8395    /// that half could add is then answered only if it holds.
8396    async fn board_completed_by(&self, also: Option<&str>) -> Result<Board, SourceError> {
8397        let cached = self.board_cache()?.clone();
8398        let mut board = match cached {
8399            Some(board) => board,
8400            None => {
8401                let read = self.read_board().await?;
8402                *self.board_cache()? = Some(read.clone());
8403                read
8404            }
8405        };
8406        let searched = match also {
8407            None => self.searched_issues().await?,
8408            Some(also) => self.searched_narrowly(also).await?,
8409        };
8410        // A complete sweep asks for every page of this view. Reconcile ids once per
8411        // view, rather than scanning the board for every search result on every page.
8412        let mut ids: std::collections::HashSet<_> =
8413            board.items.iter().map(|item| item.id.clone()).collect();
8414        for held in searched {
8415            if ids.insert(held.id.clone()) {
8416                board.items.push(held);
8417            }
8418        }
8419        for own in self.created()?.iter() {
8420            if ids.insert(own.id.clone()) {
8421                board.items.push(own.clone());
8422            }
8423        }
8424        Ok(board)
8425    }
8426
8427    /// Every open item of this board, drafts included, read through the board's own `is:open`
8428    /// filter page by page — never its unfiltered `items`, and with no issue search beside it —
8429    /// held for the command under [`OPEN_ITEMS_KEY`] on the terms every narrowed answer is
8430    /// held on, and completed with this process's own writes each time it is given.
8431    ///
8432    /// What a task listing whose every status category is open reads: an item is open exactly
8433    /// when GitHub's filter answers it, so the categories are still confirmed in process from
8434    /// each item's own node, and the answer is the whole board's filtered to the same
8435    /// categories — an open issue under a terminal card read as its card, a draft and an item
8436    /// under an option no mapping names included.
8437    async fn open_items(&self) -> Result<Vec<Resolved>, SourceError> {
8438        let key = OPEN_ITEMS_KEY.to_owned();
8439        let cached = self.narrowed_cache()?.get(&key).cloned();
8440        let mut found = match cached {
8441            Some(found) => found,
8442            None => {
8443                let found = self.read_open_items().await?;
8444                self.narrowed_cache()?.insert(key, found.clone());
8445                found
8446            }
8447        };
8448        // Every item this process wrote, drafts included: the filter answers drafts, so an
8449        // own draft is as much an answer as an own issue. Its category is confirmed below like
8450        // any other's, so one this process closed is left out there.
8451        let own: Vec<Resolved> = self
8452            .created()?
8453            .iter()
8454            .chain(self.updated()?.iter())
8455            .cloned()
8456            .collect();
8457        for own in own {
8458            match found.iter_mut().find(|read| read.id == own.id) {
8459                Some(read) => *read = own,
8460                None => found.push(own),
8461            }
8462        }
8463        Ok(found)
8464    }
8465
8466    /// Every page of [`graphql::OPEN_ITEMS`], resolved; the board's own fields are held for
8467    /// the writes that follow, as a reconcile holds them.
8468    async fn read_open_items(&self) -> Result<Vec<Resolved>, SourceError> {
8469        let mut after: Option<String> = None;
8470        let mut found = Vec::new();
8471        loop {
8472            let data = self
8473                .graphql(
8474                    graphql::OPEN_ITEMS,
8475                    json!({"owner":self.owner,"number":self.project_number,
8476                           "first":MAX_PAGE_SIZE,"after":after,"filter":OPEN_QUALIFIER,
8477                           "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
8478                )
8479                .await?;
8480            let board = data
8481                .pointer("/openItems/projectV2")
8482                .filter(|value| !value.is_null())
8483                .ok_or_else(|| SourceError::Refused {
8484                    message: format!(
8485                        "GitHub project {}/{} was not found or is not visible to the token",
8486                        self.owner, self.project_number
8487                    ),
8488                })?;
8489            *self.fields_cache()? = Some(BoardFields {
8490                id: BoardId::parse(required_str(board, "id")?)?,
8491                fields: board.get("fields").cloned().unwrap_or(Value::Null),
8492            });
8493            let items = board.get("items").ok_or_else(|| SourceError::Malformed {
8494                message: "GitHub project open items are missing".into(),
8495            })?;
8496            for item in items
8497                .get("nodes")
8498                .and_then(Value::as_array)
8499                .ok_or_else(|| SourceError::Malformed {
8500                    message: "GitHub project items.nodes is not an array".into(),
8501                })?
8502            {
8503                if let Some(resolved) = self.resolve(item)? {
8504                    found.push(resolved);
8505                }
8506            }
8507            let info = items
8508                .get("pageInfo")
8509                .ok_or_else(|| SourceError::Malformed {
8510                    message: "GitHub project items have no pageInfo".into(),
8511                })?;
8512            if !required_bool(info, "hasNextPage")? {
8513                return Ok(found);
8514            }
8515            let next = required_str(info, "endCursor")?;
8516            validate_cursor_progress(after.as_deref(), next)?;
8517            after = Some(next.to_owned());
8518        }
8519    }
8520
8521    /// This process's own view of the board, or the refusal a poisoned lock is.
8522    fn board_cache(&self) -> Result<std::sync::MutexGuard<'_, Option<Board>>, SourceError> {
8523        self.board_cache
8524            .lock()
8525            .map_err(|_| SourceError::Unavailable {
8526                message: "this source's view of the board was left inconsistent by an earlier \
8527                      failure; next: run the command again"
8528                    .into(),
8529            })
8530    }
8531
8532    /// Bring this process's own view of the board up to an item it has just written.
8533    ///
8534    /// A created item goes to `created`, which is what completes a board read GitHub's own
8535    /// eventual consistency has left behind. An item that was already there is replaced
8536    /// where it sits, so a second write of it in the same command reads its real parent
8537    /// rather than the one it had before the first write.
8538    ///
8539    /// "Where it sits" is three places, and missing an earlier one leaves a stale record
8540    /// that wins: an item this same run created is held in `created` and not in the cached
8541    /// board, and `board` completes the cached board *from* `created`, so replacing only
8542    /// the cached copy of such an item replaces nothing and the read still reports the
8543    /// title it was created with. The search is the third, and it is the one an item the
8544    /// board's own projection is behind on sits in *alone* — which is exactly the item this
8545    /// source is least able to re-read, so leaving it out would put the stale title back on
8546    /// the only items the completion in [`Self::board`] exists for.
8547    fn remember_written(&self, item: Resolved, created: bool) -> Result<(), SourceError> {
8548        self.resolved_cache()?.insert(item.id.clone(), item.clone());
8549        if created {
8550            self.created()?.push(item);
8551            return Ok(());
8552        }
8553        {
8554            let mut own = self.created()?;
8555            if let Some(held) = own.iter_mut().find(|held| held.id == item.id) {
8556                *held = item;
8557                return Ok(());
8558            }
8559        }
8560        {
8561            let mut own = self.updated()?;
8562            match own.iter_mut().find(|held| held.id == item.id) {
8563                Some(held) => *held = item.clone(),
8564                None => own.push(item.clone()),
8565            }
8566        }
8567        if let Some(board) = self.board_cache()?.as_mut()
8568            && let Some(held) = board.items.iter_mut().find(|held| held.id == item.id)
8569        {
8570            *held = item.clone();
8571        }
8572        if let Some(found) = self.search_cache()?.as_mut()
8573            && let Some(held) = found.iter_mut().find(|held| held.id == item.id)
8574        {
8575            *held = item.clone();
8576        }
8577        for found in self.narrowed_cache()?.values_mut() {
8578            if let Some(held) = found.iter_mut().find(|held| held.id == item.id) {
8579                *held = item.clone();
8580            }
8581        }
8582        for (_, found) in self.children_cache()?.values_mut() {
8583            if let Some(held) = found.iter_mut().find(|held| held.id == item.id) {
8584                *held = item.clone();
8585            }
8586        }
8587        Ok(())
8588    }
8589
8590    /// Forget one item this process has just deleted, from every half of its own view.
8591    fn forget(&self, id: &NativeId) -> Result<(), SourceError> {
8592        if let Some(Deferred::Held { created, .. }) = self.deferred()?.as_mut() {
8593            created.retain(|held| held.content != *id);
8594        }
8595        self.resolved_cache()?.remove(id);
8596        self.read_ahead()?.remove(id);
8597        self.carried()?.remove(id);
8598        self.created()?.retain(|own| own.id != *id);
8599        self.updated()?.retain(|own| own.id != *id);
8600        self.commented()?.retain(|own| own != id);
8601        if let Some(board) = self.board_cache()?.as_mut() {
8602            board.items.retain(|item| item.id != *id);
8603        }
8604        if let Some(found) = self.search_cache()?.as_mut() {
8605            found.retain(|item| item.id != *id);
8606        }
8607        for found in self.narrowed_cache()?.values_mut() {
8608            found.retain(|item| item.id != *id);
8609        }
8610        for (_, found) in self.children_cache()?.values_mut() {
8611            found.retain(|item| item.id != *id);
8612        }
8613        Ok(())
8614    }
8615
8616    /// This process's own record of each narrowed answer, or the refusal a poisoned lock is.
8617    fn narrowed_cache(
8618        &self,
8619    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<String, Vec<Resolved>>>, SourceError> {
8620        self.narrowed_cache
8621            .lock()
8622            .map_err(|_| SourceError::Unavailable {
8623                message: "this source's view of a narrowed read was left inconsistent by an \
8624                      earlier failure; next: run the command again"
8625                    .into(),
8626            })
8627    }
8628
8629    /// This process's own record of each project's sub-issues, or the refusal a poisoned lock
8630    /// is.
8631    /// The tasks `project` holds, as a copy's batched read found them this command, when it did.
8632    fn held_task_children(&self, project: &NativeId) -> Result<Option<Vec<Resolved>>, SourceError> {
8633        Ok(self.task_children()?.get(project).cloned())
8634    }
8635
8636    fn task_children(
8637        &self,
8638    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Vec<Resolved>>>, SourceError> {
8639        self.task_children
8640            .lock()
8641            .map_err(|_| SourceError::Unavailable {
8642                message: "this source's record of a project's tasks was left inconsistent by an \
8643                          earlier failure; next: run the command again"
8644                    .into(),
8645            })
8646    }
8647
8648    fn children_cache(&self) -> Result<std::sync::MutexGuard<'_, ProjectChildren>, SourceError> {
8649        self.children_cache
8650            .lock()
8651            .map_err(|_| SourceError::Unavailable {
8652                message: "this source's view of a project's tasks was left inconsistent by an \
8653                      earlier failure; next: run the command again"
8654                    .into(),
8655            })
8656    }
8657
8658    /// Every page of the board, read from GitHub.
8659    async fn read_board(&self) -> Result<Board, SourceError> {
8660        let mut after: Option<String> = None;
8661        let mut items = Vec::new();
8662        let mut board;
8663        loop {
8664            let page = self.board_page(after.as_deref(), MAX_PAGE_SIZE).await?;
8665            for item in page
8666                .pointer("/items/nodes")
8667                .and_then(Value::as_array)
8668                .ok_or_else(|| SourceError::Malformed {
8669                    message: "GitHub project items.nodes is not an array".into(),
8670                })?
8671            {
8672                if let Some(resolved) = self.resolve(item)? {
8673                    items.push(resolved);
8674                }
8675            }
8676            let info = page
8677                .pointer("/items/pageInfo")
8678                .ok_or_else(|| SourceError::Malformed {
8679                    message: "GitHub project items have no pageInfo".into(),
8680                })?;
8681            let has_next = required_bool(info, "hasNextPage")?;
8682            let next = has_next
8683                .then(|| required_str(info, "endCursor"))
8684                .transpose()?;
8685            board = page.clone();
8686            match next {
8687                Some(next) => {
8688                    validate_cursor_progress(after.as_deref(), next)?;
8689                    after = Some(next.to_owned());
8690                }
8691                None => break,
8692            }
8693        }
8694        Ok(Board {
8695            id: required_str(&board, "id")?.to_owned(),
8696            fields: board.get("fields").cloned().unwrap_or(Value::Null),
8697            items,
8698        })
8699    }
8700
8701    /// The existing items this source has written, for completing a narrowed read that is
8702    /// behind; see [`Self::updated`](GitHubProjectsSource::updated).
8703    fn updated(&self) -> Result<std::sync::MutexGuard<'_, Vec<Resolved>>, SourceError> {
8704        self.updated.lock().map_err(|_| SourceError::Unavailable {
8705            message: "this source's record of what it wrote in this run was left inconsistent \
8706                      by an earlier failure; next: run the command again"
8707                .into(),
8708        })
8709    }
8710
8711    /// The issues this source has commented on in this command; see
8712    /// [`Self::commented`](GitHubProjectsSource::commented).
8713    fn commented(&self) -> Result<std::sync::MutexGuard<'_, Vec<NativeId>>, SourceError> {
8714        self.commented.lock().map_err(|_| SourceError::Unavailable {
8715            message: "this source's record of what it commented on in this run was left \
8716                      inconsistent by an earlier failure; next: run the command again"
8717                .into(),
8718        })
8719    }
8720
8721    /// Called only once GitHub has answered the comment write, so an issue whose comment
8722    /// failed is never made a candidate a later read would pay a node read for.
8723    fn remember_commented(&self, issue: &NativeId) -> Result<(), SourceError> {
8724        // A comment page held for this command is no longer what the issue holds.
8725        self.held_comments()?.remove(issue);
8726        let mut commented = self.commented()?;
8727        if !commented.contains(issue) {
8728            commented.push(issue.clone());
8729        }
8730        Ok(())
8731    }
8732
8733    /// The items this source has created, for completing a board read that is behind.
8734    fn created(&self) -> Result<std::sync::MutexGuard<'_, Vec<Resolved>>, SourceError> {
8735        self.created.lock().map_err(|_| SourceError::Unavailable {
8736            message: "this source's record of what it created in this run was left \
8737                      inconsistent by an earlier failure; next: run the command again"
8738                .into(),
8739        })
8740    }
8741
8742    /// One board item as this source reports it, or `None` for content it ignores.
8743    ///
8744    /// A pull request is neither a project nor a task — it is somebody's change, not a
8745    /// unit of plan — and an item whose content the token cannot see has nothing to
8746    /// report at all.
8747    fn resolve(&self, item: &Value) -> Result<Option<Resolved>, SourceError> {
8748        let resolved = self.resolve_unremembered(item)?;
8749        if let Some(resolved) = &resolved {
8750            self.resolved_cache()?
8751                .insert(resolved.id.clone(), resolved.clone());
8752        }
8753        Ok(resolved)
8754    }
8755
8756    /// [`Self::resolve`], without remembering the item it resolves: what reading a token off a
8757    /// write's own response needs, which says nothing this process should answer a later read
8758    /// with.
8759    fn resolve_unremembered(&self, item: &Value) -> Result<Option<Resolved>, SourceError> {
8760        let content = item.get("content").ok_or_else(|| SourceError::Malformed {
8761            message: "GitHub project item is missing content".into(),
8762        })?;
8763        if content.is_null() {
8764            return Ok(None);
8765        }
8766        let content_kind = match required_str(content, "__typename")? {
8767            "Issue" => ContentKind::Issue,
8768            "DraftIssue" => ContentKind::DraftIssue,
8769            _ => return Ok(None),
8770        };
8771        let field_values = item
8772            .get("fieldValues")
8773            .ok_or_else(|| SourceError::Malformed {
8774                message: "GitHub project item is missing fieldValues".into(),
8775            })?;
8776        complete_connection(field_values, "project item field values", NESTED_PAGE_SIZE)?;
8777        let nodes = field_values
8778            .get("nodes")
8779            .and_then(Value::as_array)
8780            .ok_or_else(|| SourceError::Malformed {
8781                message: "GitHub project item fieldValues.nodes is not an array".into(),
8782            })?;
8783        if let Some(labels) = content.get("labels") {
8784            complete_connection(labels, "content labels", NESTED_PAGE_SIZE)?;
8785        }
8786        let raw_body = optional_str(content, "body")?.map(str::to_owned);
8787        let (body, slot) = self.visible(raw_body.clone())?;
8788        let parent = optional_str(content.get("parent").unwrap_or(&Value::Null), "id")?
8789            .map(|id| NativeId(id.to_owned()));
8790        // A draft has no sub-issues to summarise, and GitHub's schema gives it no field
8791        // to read one from; it is a task, and never a project.
8792        let sub_issues = match content_kind {
8793            ContentKind::Issue => sub_issue_total(content)?,
8794            ContentKind::DraftIssue => 0,
8795        };
8796        let content_id = required_str(content, "id")?;
8797        let marked = ItemKind::from_metadata(&slot).map_err(|message| SourceError::Malformed {
8798            message: format!("GitHub issue {content_id}: {message}"),
8799        })?;
8800        let raw_title = required_str(content, "title")?;
8801        // Read as children, a sub-issue is filed under no project and nothing is a project: the
8802        // GitHub parent is the parent relation instead.
8803        let (kind, parent, issue_parent) = match self.sub_issues {
8804            SubIssues::Project => (
8805                BoardKind::of(raw_title, parent.is_some(), sub_issues, marked),
8806                parent,
8807                None,
8808            ),
8809            SubIssues::Parent => (
8810                if raw_title.starts_with(DESIGN_TITLE_PREFIX) {
8811                    BoardKind::Document
8812                } else {
8813                    BoardKind::Work(ItemKind::Task)
8814                },
8815                None,
8816                parent,
8817            ),
8818        };
8819        // The title a person wrote, which for a document is the one without the prefix —
8820        // the same way `content` above is the body without this source's metadata slot.
8821        let title = match kind {
8822            BoardKind::Document => raw_title[DESIGN_TITLE_PREFIX.len()..].to_owned(),
8823            BoardKind::Work(_) => raw_title.to_owned(),
8824        };
8825        let own_repository = content
8826            .pointer("/repository/nameWithOwner")
8827            .and_then(Value::as_str)
8828            .map(|origin| Repository::try_from(format!("{}/{origin}", RepositoryTarget::HOST)))
8829            .transpose()
8830            .map_err(|message| SourceError::Malformed { message })?;
8831        let repositories = if slot.contains_key(Repository::METADATA_KEY) {
8832            Repository::from_metadata(&slot)
8833                .map_err(|message| SourceError::Malformed { message })?
8834        } else {
8835            own_repository.clone().into_iter().collect()
8836        };
8837        let classification = Classification::from_metadata(&slot)
8838            .map_err(|message| SourceError::Malformed { message })?;
8839        let id = NativeId(content_id.to_owned());
8840        // Read only for a task, because only a task has either list: a project or a
8841        // document holding one of these keys holds nothing this source reports, and the
8842        // keys are left out of its caller-visible metadata all the same.
8843        let (delivers, delivered_by) = if kind == BoardKind::Work(ItemKind::Task) {
8844            let listed = |key: &str| {
8845                TaskRef::from_value(key, &id, Some(&self.name), slot.get(key))
8846                    .map_err(|message| SourceError::Malformed { message })
8847            };
8848            (
8849                listed(TaskRef::DELIVERS_KEY)?,
8850                listed(TaskRef::DELIVERED_BY_KEY)?,
8851            )
8852        } else {
8853            (Vec::new(), Vec::new())
8854        };
8855        let (option, closed, reason) = Self::status_parts(nodes, content)?;
8856        let priority = self.held_priority(nodes)?;
8857        let item_labels = labels(content)?;
8858        // Present when the item was reached through its own issue, whose board entry
8859        // names the board; a read of the board's own items has the board already. An
8860        // empty id names nothing a field write could address, so it is read as absent and
8861        // the write goes back to reading the board.
8862        let board_id = item
8863            .pointer("/project/id")
8864            .and_then(Value::as_str)
8865            .filter(|id| !id.is_empty());
8866        let resolved = Resolved {
8867            item_id: required_str(item, "id")?.to_owned(),
8868            id,
8869            content_kind,
8870            kind,
8871            title,
8872            body: body.filter(|value| !value.is_empty()),
8873            raw_body,
8874            status: self
8875                .statuses
8876                .status(kind.status_kind(), option, closed, reason),
8877            option: option.map(str::to_owned),
8878            priority,
8879            closed,
8880            reason: closed.then(|| reason.map(str::to_owned)).flatten(),
8881            delivers,
8882            delivered_by,
8883            labels: item_labels.clone(),
8884            parent,
8885            issue_parent,
8886            origin: text_field(nodes, ORIGIN_FIELD)?.filter(|value| !value.is_empty()),
8887            projected: self.held_projections(nodes)?,
8888            number: match content_kind {
8889                ContentKind::Issue => Some(issue_number(content)?),
8890                // A draft is filed in no repository, so nothing ever numbered it:
8891                // `DraftIssue` declares no `number` at all, exactly as it declares no
8892                // `subIssuesSummary` the branch above reads.
8893                ContentKind::DraftIssue => None,
8894            },
8895            url: optional_str(content, "url")?.map(str::to_owned),
8896            created_at: optional_time(content, "createdAt")?,
8897            updated_at: optional_time(content, "updatedAt")?,
8898            item_updated_at: optional_time(item, "updatedAt")?,
8899            comment_count: content
8900                .pointer("/commentCount/totalCount")
8901                .and_then(Value::as_u64),
8902            relationship_events: content
8903                .pointer("/relationshipEvents/totalCount")
8904                .and_then(Value::as_u64),
8905            // The issue node is stamped wherever it was read; a board item a read of the issue
8906            // put together from its memberships is not.
8907            served_at: match optional_time(content, SERVED_AT)? {
8908                Some(served) => Some(served),
8909                None => optional_time(item, SERVED_AT)?,
8910            },
8911            // Both connections were read to their end above — one reporting a further page is
8912            // refused — so these are every field value and every label the item holds. A
8913            // response that did not select the labels at all says nothing of them, and gives
8914            // no facets.
8915            facets: content.get("labels").is_some().then(|| {
8916                change_token::Facets::new(kind.facet(), facet_fields(nodes), &item_labels).digest()
8917            }),
8918            own_repository,
8919            repositories,
8920            classification,
8921            slot,
8922            board_id: board_id.map(str::to_owned),
8923            fields: field_definitions(nodes),
8924            board_fields: Self::carried_board_fields(content, board_id)?,
8925            blocked_by: carried_blocked_by(content)?,
8926            assignees: if self.assignees {
8927                Some(assignees::assignee_logins(content)?)
8928            } else {
8929                None
8930            },
8931        };
8932        Ok(Some(resolved))
8933    }
8934
8935    /// The field definitions of the board `board_id` names — the project this issue's own
8936    /// board item is on — off the `boards` page a read of an issue by its own id carries, or
8937    /// `None` when the read carried none, carried no entry for that board, or the board item
8938    /// named no board, which a write then answers by reading the board's fields itself.
8939    ///
8940    /// Matched by the board's node id and never by its number alone: a project number is
8941    /// unique only within its owner, so another owner's board numbered alike can sit on the
8942    /// same page, and its field and option ids address nothing on this one.
8943    fn carried_board_fields(
8944        content: &Value,
8945        board_id: Option<&str>,
8946    ) -> Result<Option<Value>, SourceError> {
8947        let (Some(nodes), Some(board_id)) = (
8948            content.pointer("/boards/nodes").and_then(Value::as_array),
8949            board_id,
8950        ) else {
8951            return Ok(None);
8952        };
8953        let Some(board) = nodes.iter().find_map(|node| {
8954            let project = node.get("project")?;
8955            (project.get("id").and_then(Value::as_str) == Some(board_id)).then_some(project)
8956        }) else {
8957            return Ok(None);
8958        };
8959        let Some(fields) = board.get("fields").filter(|fields| !fields.is_null()) else {
8960            return Ok(None);
8961        };
8962        complete_connection(fields, "board fields", NESTED_PAGE_SIZE)?;
8963        Ok(Some(fields.clone()))
8964    }
8965
8966    /// What one board item's `Priority` field says, through this instance's mapping.
8967    ///
8968    /// An instance with no mapping holds no priority, so every item reads as `none` whatever
8969    /// its board holds. With one, no value is `none`, a mapped option is its level, and an
8970    /// option the mapping does not name is kept as itself — never read as a level or as
8971    /// `none` — for a read of the task to report by name.
8972    fn held_priority(&self, field_values: &[Value]) -> Result<HeldPriority, SourceError> {
8973        let Some(mapping) = &self.priorities else {
8974            return Ok(HeldPriority::Read(Priority::None));
8975        };
8976        // A value of the field that names no option — a text field someone called `Priority` —
8977        // is malformed rather than `none`: reading it as no priority would let the next copy
8978        // clear one a person set.
8979        let Some(option) = field_values
8980            .iter()
8981            .find(|value| {
8982                value.pointer("/field/name").and_then(Value::as_str) == Some(PRIORITY_FIELD)
8983            })
8984            .map(|value| required_str(value, "name"))
8985            .transpose()?
8986        else {
8987            return Ok(HeldPriority::Read(Priority::None));
8988        };
8989        Ok(mapping.priority_of(option).map_or_else(
8990            || HeldPriority::Unmapped(option.to_owned()),
8991            HeldPriority::Read,
8992        ))
8993    }
8994
8995    /// What each projected metadata field holds for one board item, by field name — every text
8996    /// value GitHub answers, an empty one included.
8997    fn held_projections(
8998        &self,
8999        field_values: &[Value],
9000    ) -> Result<BTreeMap<String, String>, SourceError> {
9001        let mut held = BTreeMap::new();
9002        for projection in &self.metadata_fields {
9003            if let Some(text) = text_field(field_values, &projection.field)? {
9004                held.insert(projection.field.to_string(), text);
9005            }
9006        }
9007        Ok(held)
9008    }
9009
9010    /// What one board item's status is read from: its `Status` option, whether its issue
9011    /// is closed, and the reason it was closed with. [`BoardStatuses::status`] turns the
9012    /// three into the status it reports.
9013    fn status_parts<'a>(
9014        field_values: &'a [Value],
9015        content: &'a Value,
9016    ) -> Result<(Option<&'a str>, bool, Option<&'a str>), SourceError> {
9017        let option = field_values
9018            .iter()
9019            .find(|value| value.pointer("/field/name").and_then(Value::as_str) == Some("Status"))
9020            .map(|value| required_str(value, "name"))
9021            .transpose()?;
9022        let closed = optional_str(content, "state")? == Some("CLOSED");
9023        Ok((option, closed, optional_str(content, "stateReason")?))
9024    }
9025
9026    /// The board Status option this write selects, or the refusal that says why not.
9027    ///
9028    /// The mapped option is required for both open and terminal targets. A terminal write
9029    /// validates it before changing either representation, so it can never fall back to
9030    /// closing an issue whose board cannot display the matching status.
9031    ///
9032    /// Answers the field's id, the option's id, and the option's name as the board spells
9033    /// it — which is the name a read of the item reports once it sits there.
9034    fn column_for(
9035        &self,
9036        fields: &Value,
9037        kind: ItemKind,
9038        category: StatusCategory,
9039        target: &StatusTarget,
9040    ) -> Result<Option<(String, String, String)>, SourceError> {
9041        let Some(wanted) = target.option() else {
9042            return Ok(None);
9043        };
9044        let missing = |detail: &str| SourceError::Refused {
9045            message: format!(
9046                "{} status {} of source {} needs the board Status option {wanted:?}, and \
9047                 {detail}; next: add that option to the board, which `onetaskgraph sources \
9048                 fields {} --apply` does, or point status_mapping.{}.{} of this source at one \
9049                 it has",
9050                kind.marker(),
9051                category_name(category),
9052                self.name,
9053                self.name,
9054                category_name(category),
9055                kind.marker()
9056            ),
9057        };
9058        let Some(field) = Board::field(fields, "Status")? else {
9059            return Err(missing("this board has no Status field"));
9060        };
9061        if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
9062            return Err(missing(
9063                "this board's Status field is not a single-select field",
9064            ));
9065        }
9066        let option = field
9067            .get("options")
9068            .and_then(Value::as_array)
9069            .and_then(|options| {
9070                options.iter().find(|option| {
9071                    option
9072                        .get("name")
9073                        .and_then(Value::as_str)
9074                        .is_some_and(|name| name.eq_ignore_ascii_case(wanted))
9075                })
9076            });
9077        match option {
9078            None => Err(missing("this board does not have it")),
9079            Some(option) => Ok(Some((
9080                required_str(field, "id")?.to_owned(),
9081                required_str(option, "id")?.to_owned(),
9082                required_str(option, "name")?.to_owned(),
9083            ))),
9084        }
9085    }
9086
9087    /// The refusal a status that closes an issue is answered with over a board draft.
9088    fn closes_a_draft(&self, category: StatusCategory) -> SourceError {
9089        SourceError::Refused {
9090            message: format!(
9091                "status {} of source {} closes the item's issue, and GitHub draft items have \
9092                 no open or closed state",
9093                category_name(category),
9094                self.name
9095            ),
9096        }
9097    }
9098
9099    /// What a status write to one item needs of the board: the board's id and the
9100    /// definition of its `Status` field, read off the item when the item says both.
9101    ///
9102    /// The same reasoning as [`Self::fields_for`]: a node read of the item names its board,
9103    /// and its `Status` value carries that field's definition, options and all. An item that
9104    /// does not say — no board id, or no `Status` value to read the field off — takes them
9105    /// from [`Self::board_fields`], which reads no item.
9106    async fn status_board(&self, item: &Resolved) -> Result<BoardFields, SourceError> {
9107        if let Some(board) = item.carried_board() {
9108            return Ok(board);
9109        }
9110        if item.defines("Status")
9111            && let Some(board_id) = item.named_board()
9112        {
9113            return Ok(BoardFields {
9114                id: board_id,
9115                fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
9116            });
9117        }
9118        self.board_fields().await
9119    }
9120
9121    /// Set one task's or one project's status and nothing else; see
9122    /// [`TaskSource::set_task_status`] and [`TaskSource::set_project_status`].
9123    async fn set_status(
9124        &self,
9125        id: &NativeId,
9126        kind: ItemKind,
9127        category: StatusCategory,
9128    ) -> Result<Option<Status>, SourceError> {
9129        // Refused before anything is read, in the words a write of the same status is.
9130        let target = self.resolved_target(kind, category)?;
9131        // An item read by issue reference carries only what this write needs, so what it
9132        // becomes is never remembered for a later read to be answered from.
9133        let held = self.take_held(id)?;
9134        let by_reference = held.is_some();
9135        let bound = match held {
9136            Some(item) => Some(item),
9137            None => self.bound_item(id).await?,
9138        };
9139        let Some(mut item) = bound.filter(|item| item.kind == BoardKind::Work(kind)) else {
9140            return Ok(None);
9141        };
9142        let board = self.status_board(&item).await?;
9143        let (field, option, name) = self
9144            .column_for(&board.fields, kind, category, &target)?
9145            .ok_or_else(|| SourceError::Malformed {
9146                message: format!(
9147                    "status {} of source {} names no board Status option",
9148                    category_name(category),
9149                    self.name
9150                ),
9151            })?;
9152        // The card already shows the target's option. That alone is not the status: an open
9153        // issue under a terminal card reads that card's category while GitHub, its
9154        // notifications and a search of open issues all say the work is not finished, and a
9155        // closed issue under an open column's card reads as its closure. So the write is no
9156        // write only where the issue's open or closed state is also what the target needs —
9157        // closed, for a reason reading this category, for a terminal one; open for a column.
9158        let at_option = item
9159            .option
9160            .as_deref()
9161            .is_some_and(|held| held.eq_ignore_ascii_case(&name));
9162        let issue = item.content_kind == ContentKind::Issue;
9163        let state_holds = match &target {
9164            StatusTarget::Terminal(_, _) => {
9165                !issue || (item.closed && closed_category(item.reason.as_deref()) == category)
9166            }
9167            _ => !issue || !item.closed,
9168        };
9169        if item.status.category == category && at_option && state_holds {
9170            return Ok(Some(item.status));
9171        }
9172        match &target {
9173            StatusTarget::Terminal(_, reason) => {
9174                if item.content_kind == ContentKind::DraftIssue {
9175                    return Err(self.closes_a_draft(category));
9176                }
9177                // The option first, so a refused selection leaves an open issue open rather
9178                // than closed behind a card that still reads open. A card already showing it
9179                // is sent nothing: only the issue's state is out of line.
9180                if !at_option {
9181                    self.set_item_field(
9182                        board.id.as_str(),
9183                        &item.item_id,
9184                        &field,
9185                        json!({"singleSelectOptionId": option}),
9186                    )
9187                    .await?;
9188                }
9189                // An issue already closed in a way that reads as this category keeps its state
9190                // and its reason: only its card was out of line, and closing it again would
9191                // overwrite a reason — a duplicate's — that says more than this write does.
9192                let already = item.closed && item.status.category == category;
9193                if !already {
9194                    self.update_content(
9195                        ContentKind::Issue,
9196                        &item.id,
9197                        json!({"stateInput": state_input(Some(&target))}),
9198                    )
9199                    .await?;
9200                }
9201                let reason = if already {
9202                    item.reason.clone()
9203                } else {
9204                    Some(reason.reason().to_owned())
9205                };
9206                item.closed = true;
9207                item.status = self
9208                    .statuses
9209                    .status(kind, Some(&name), true, reason.as_deref());
9210                item.option = Some(name);
9211                item.reason = reason;
9212            }
9213            StatusTarget::Column(_) => {
9214                // An option is what an open item's status is, so a closed issue is reopened
9215                // first — sitting closed in the column, it would read back as closed. A draft has
9216                // no state to reopen.
9217                if item.content_kind == ContentKind::Issue && item.closed {
9218                    self.update_content(
9219                        ContentKind::Issue,
9220                        &item.id,
9221                        json!({"stateInput": state_input(Some(&target))}),
9222                    )
9223                    .await?;
9224                    item.closed = false;
9225                }
9226                if !at_option {
9227                    self.set_item_field(
9228                        board.id.as_str(),
9229                        &item.item_id,
9230                        &field,
9231                        json!({"singleSelectOptionId": option}),
9232                    )
9233                    .await?;
9234                }
9235                item.status = self.statuses.status(kind, Some(&name), false, None);
9236                item.option = Some(name);
9237            }
9238            StatusTarget::Disabled(_) => {
9239                unreachable!("resolved_target refused a disabled status")
9240            }
9241        }
9242        let status = item.status.clone();
9243        if !by_reference {
9244            self.remember_written(item, false)?;
9245        }
9246        Ok(Some(status))
9247    }
9248
9249    /// Replace one task's `delivered_by` and nothing else; see
9250    /// [`TaskSource::set_delivered_by`].
9251    ///
9252    /// One update of the body, which differs from the body GitHub holds only inside the
9253    /// metadata slot — see [`with_slot`]. A body that would not change is not sent at all.
9254    async fn replace_delivered_by(
9255        &self,
9256        id: &NativeId,
9257        delivered_by: &[TaskRef],
9258    ) -> Result<Option<()>, SourceError> {
9259        let entries = TaskRef::listed(
9260            TaskRef::DELIVERED_BY_KEY,
9261            id,
9262            Some(&self.name),
9263            delivered_by.to_vec(),
9264        )
9265        .map_err(|message| SourceError::Refused { message })?;
9266        let Some(mut item) = self
9267            .bound_item(id)
9268            .await?
9269            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9270        else {
9271            return Ok(None);
9272        };
9273        let mut slot = item.slot.clone();
9274        set_task_list(&mut slot, TaskRef::DELIVERED_BY_KEY, &entries);
9275        self.write_slot(&mut item, &slot).await?;
9276        item.delivered_by = entries;
9277        self.remember_written(item, false)?;
9278        Ok(Some(()))
9279    }
9280
9281    /// Set one caller key of the metadata slot of one issue of `kind`, and nothing else;
9282    /// see [`TaskSource::set_task_metadata`].
9283    ///
9284    /// `None` when this board holds no item by that id, or holds one of another kind. The
9285    /// answer is the item as this source now reads it, so what a caller is told the key
9286    /// holds is what the slot holds.
9287    ///
9288    /// A key already holding the value is answered without a write, compared as JSON rather
9289    /// than as the body's bytes: a slot a person spelled with other whitespace would
9290    /// otherwise be re-encoded, which is a write that changes nothing the caller asked for.
9291    async fn set_slot_key(
9292        &self,
9293        id: &NativeId,
9294        kind: BoardKind,
9295        key: &MetadataKey,
9296        value: &Value,
9297    ) -> Result<Option<Resolved>, SourceError> {
9298        let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
9299            return Ok(None);
9300        };
9301        if item.slot.get(key.as_str()) == Some(value) {
9302            return Ok(Some(item));
9303        }
9304        let mut slot = item.slot.clone();
9305        slot.insert(key.as_str().to_owned(), value.clone());
9306        // A key a board text field projects moves that field first, so the body — the value's
9307        // one authoritative home — is written last, as every write of an existing item is.
9308        if self
9309            .metadata_fields
9310            .iter()
9311            .any(|projection| &*projection.key == key.as_str())
9312        {
9313            let board = self.projection_board(&item).await?;
9314            let (writes, projected) = self.projection_writes(
9315                &board.fields,
9316                Some(&item.projected),
9317                &slot,
9318                Some(&[key.as_str()]),
9319            )?;
9320            let (mut values, mut clears) = (Vec::new(), Vec::new());
9321            for write in &writes {
9322                write.join(&mut values, &mut clears);
9323            }
9324            self.set_item_fields(board.id.as_str(), &item.item_id, &values, &clears)
9325                .await?;
9326            item.projected = projected;
9327        }
9328        self.write_slot(&mut item, &slot).await?;
9329        self.remember_written(item.clone(), false)?;
9330        Ok(Some(item))
9331    }
9332
9333    /// What a projection write to `item` needs of the board, read off the item when it says
9334    /// enough, as [`Self::fields_for`] reads it.
9335    async fn projection_board(&self, item: &Resolved) -> Result<BoardFields, SourceError> {
9336        if let Some(board) = item.carried_board() {
9337            return Ok(board);
9338        }
9339        if let Some(board_id) = item.named_board()
9340            && self
9341                .metadata_fields
9342                .iter()
9343                .all(|projection| item.defines(&projection.field))
9344        {
9345            return Ok(BoardFields {
9346                id: board_id,
9347                fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
9348            });
9349        }
9350        self.board_fields().await
9351    }
9352
9353    /// Put `slot` in one item's metadata slot with a single update of its body, and bring
9354    /// `item` up to what that write left.
9355    ///
9356    /// The body sent differs from the body GitHub holds only inside the slot — see
9357    /// [`with_slot`] — and a body that would not change is not sent at all. It goes through
9358    /// the mutation the item's content takes, so a board draft's body is written with
9359    /// `updateProjectV2DraftIssue` exactly as an issue's is with `updateIssue`.
9360    async fn write_slot(
9361        &self,
9362        item: &mut Resolved,
9363        slot: &BTreeMap<String, Value>,
9364    ) -> Result<(), SourceError> {
9365        let held = item.raw_body.clone().unwrap_or_default();
9366        let body = with_slot(&held, slot)?;
9367        if body != held {
9368            self.update_content(item.content_kind, &item.id, json!({"body": body}))
9369                .await?;
9370        }
9371        let (visible, slot) = self.visible(Some(body.clone()))?;
9372        item.body = visible.filter(|value| !value.is_empty());
9373        item.raw_body = Some(body);
9374        item.slot = slot;
9375        Ok(())
9376    }
9377
9378    /// This instance's target for a category written to an item of `kind`, refusing one
9379    /// that kind has no option for — before anything is read or written.
9380    ///
9381    /// Nothing here mutates the board's option set to make room for a status. GitHub
9382    /// documents `UpdateProjectV2FieldInput.singleSelectOptions` as *"provided values
9383    /// overwrite existing options"*, so no addition is additive and a mistake destroys the
9384    /// field and every item's status.
9385    fn resolved_target(
9386        &self,
9387        kind: ItemKind,
9388        category: StatusCategory,
9389    ) -> Result<StatusTarget, SourceError> {
9390        let target = self.statuses.target(kind, category).clone();
9391        let StatusTarget::Disabled(why) = target else {
9392            return Ok(target);
9393        };
9394        let refusal = why.refusal(&self.name, category, kind);
9395        // Why there is no shipped default, which is the question a person meeting this
9396        // refusal on a source that never mentioned the category asks.
9397        let shipped_none = match category {
9398            StatusCategory::Draft => Some(
9399                "draft has no shipped default because GitHub draft issues cannot have \
9400                 sub-issues, and this source stores a project's tasks as its issue's sub-issues",
9401            ),
9402            StatusCategory::Unknown => Some(
9403                "unknown has no shipped default because this board keeps no open-ended status \
9404                 word: every word classified unknown is written to the one board Status option \
9405                 status_mapping.unknown names",
9406            ),
9407            _ => None,
9408        };
9409        Err(match (refusal, shipped_none, why) {
9410            (SourceError::Refused { message }, Some(note), UnmappedStatus::Unconfigured) => {
9411                SourceError::Refused {
9412                    message: format!("{message}; {note}"),
9413                }
9414            }
9415            (refusal, _, _) => refusal,
9416        })
9417    }
9418
9419    /// What writing `priority` does to one item's `Priority` field on this board, or the
9420    /// refusal naming what the board lacks.
9421    ///
9422    /// `none` is no value, so it clears the field — and asks nothing of an item that holds
9423    /// none already, or of an item not created yet. Every other priority selects the option
9424    /// the mapping names, matched case-insensitively; a board with no `Priority` field, or
9425    /// without that option, is refused rather than given one: reads and writes never create
9426    /// a field or an option.
9427    fn priority_write(
9428        &self,
9429        fields: &Value,
9430        existing: Option<&Resolved>,
9431        priority: Priority,
9432    ) -> Result<Option<PriorityWrite>, SourceError> {
9433        let Some(mapping) = &self.priorities else {
9434            return Err(self.holds_no_priority());
9435        };
9436        let Some(wanted) = mapping.option(priority) else {
9437            if !existing.is_some_and(Resolved::holds_priority) {
9438                return Ok(None);
9439            }
9440            let field =
9441                Board::field(fields, PRIORITY_FIELD)?.ok_or_else(|| SourceError::Malformed {
9442                    message: format!(
9443                        "an item holding a {PRIORITY_FIELD} value was read without that field"
9444                    ),
9445                })?;
9446            return Ok(Some(PriorityWrite::Clear {
9447                field: required_str(field, "id")?.to_owned(),
9448            }));
9449        };
9450        let missing = |detail: &str| SourceError::Refused {
9451            message: format!(
9452                "priority {priority} of source {} needs the board {PRIORITY_FIELD} option \
9453                 {wanted:?}, and {detail}; run `onetaskgraph sources fields {} --apply` to add \
9454                 it, or point priority_mapping.{priority} of this source at an option the board \
9455                 has",
9456                self.name, self.name
9457            ),
9458        };
9459        let Some(field) = Board::field(fields, PRIORITY_FIELD)? else {
9460            return Err(missing(&format!(
9461                "this board has no {PRIORITY_FIELD} field"
9462            )));
9463        };
9464        if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
9465            return Err(missing(&format!(
9466                "this board's {PRIORITY_FIELD} field is not a single-select field"
9467            )));
9468        }
9469        // An options list that is absent or not a list is an answer this source cannot read,
9470        // not a board lacking the option: `sources fields --apply` is no remedy for it.
9471        let option = field
9472            .get("options")
9473            .and_then(Value::as_array)
9474            .ok_or_else(|| SourceError::Malformed {
9475                message: format!("GitHub {PRIORITY_FIELD} field options is not an array"),
9476            })?
9477            .iter()
9478            .find(|option| {
9479                option
9480                    .get("name")
9481                    .and_then(Value::as_str)
9482                    .is_some_and(|name| name.eq_ignore_ascii_case(wanted))
9483            })
9484            .ok_or_else(|| missing("this board does not have it"))?;
9485        Ok(Some(PriorityWrite::Select {
9486            field: required_str(field, "id")?.to_owned(),
9487            option: required_str(option, "id")?.to_owned(),
9488        }))
9489    }
9490
9491    /// What writing `metadata` does to each projected text field of one item, and what those
9492    /// fields hold after it — or the refusal, before anything is sent.
9493    ///
9494    /// `held` is what the item's fields hold now, `None` for an item not created yet. `keys`
9495    /// narrows the work to the entries projecting one of those metadata keys, for a write that
9496    /// touches only them; `None` is every entry. A string the field already holds, and nothing
9497    /// for a field holding nothing, sends nothing. A value no text field can hold is refused,
9498    /// and so is a board without the field, or with a field of that name that is not a text
9499    /// field: reads and writes never create a field.
9500    fn projection_writes(
9501        &self,
9502        fields: &Value,
9503        held: Option<&BTreeMap<String, String>>,
9504        metadata: &BTreeMap<String, Value>,
9505        keys: Option<&[&str]>,
9506    ) -> Result<(Vec<ProjectionWrite>, BTreeMap<String, String>), SourceError> {
9507        let mut projected = held.cloned().unwrap_or_default();
9508        let mut writes = Vec::new();
9509        for projection in self
9510            .metadata_fields
9511            .iter()
9512            .filter(|projection| keys.is_none_or(|keys| keys.contains(&&*projection.key)))
9513        {
9514            let wanted = projection.projected(metadata, &self.name)?;
9515            let field = self.projection_field(fields, projection)?;
9516            let holding = projected.get(&*projection.field);
9517            match wanted {
9518                Projected::Text(text) if holding != Some(&text) => {
9519                    writes.push(ProjectionWrite::Set {
9520                        field,
9521                        text: text.clone(),
9522                    });
9523                    projected.insert(projection.field.to_string(), text);
9524                }
9525                Projected::Nothing if holding.is_some() => {
9526                    writes.push(ProjectionWrite::Clear { field });
9527                    projected.remove(&*projection.field);
9528                }
9529                Projected::Text(_) | Projected::Nothing => {}
9530            }
9531        }
9532        Ok((writes, projected))
9533    }
9534
9535    /// The id of the board text field one projection writes, or the refusal naming what the
9536    /// board has instead.
9537    fn projection_field(
9538        &self,
9539        fields: &Value,
9540        projection: &MetadataField,
9541    ) -> Result<String, SourceError> {
9542        let refuse = |detail: String| SourceError::Refused {
9543            message: format!(
9544                "source {} projects metadata key {:?} onto the board text field {:?}, and \
9545                 {detail}; next: run `onetaskgraph sources fields {} --apply` to create it as a \
9546                 text field, or name another field in metadata_fields",
9547                self.name, &*projection.key, &*projection.field, self.name
9548            ),
9549        };
9550        let Some(field) = Board::field(fields, &projection.field)? else {
9551            return Err(refuse("this board has no field of that name".to_owned()));
9552        };
9553        let typename = optional_str(field, "__typename")?.unwrap_or("field of another type");
9554        let data_type = optional_str(field, "dataType")?;
9555        if typename != "ProjectV2Field" || data_type != Some("TEXT") {
9556            return Err(refuse(format!(
9557                "this board's field of that name is not a text field (it is a {}), so it is \
9558                 left as it is; rename or remove that field first",
9559                data_type.unwrap_or(typename)
9560            )));
9561        }
9562        Ok(required_str(field, "id")?.to_owned())
9563    }
9564
9565    /// Apply one priority write to one board item.
9566    async fn write_priority(
9567        &self,
9568        board_id: &str,
9569        item_id: &str,
9570        write: &PriorityWrite,
9571    ) -> Result<(), SourceError> {
9572        match write {
9573            PriorityWrite::Select { field, option } => {
9574                self.set_item_field(
9575                    board_id,
9576                    item_id,
9577                    field,
9578                    json!({"singleSelectOptionId": option}),
9579                )
9580                .await
9581            }
9582            PriorityWrite::Clear { field } => {
9583                let data = self
9584                    .graphql(
9585                        graphql::CLEAR_FIELD,
9586                        json!({"input":{"projectId":board_id,"itemId":item_id,"fieldId":field},
9587                            "readPriority":false,"priorityName":PRIORITY_FIELD}),
9588                    )
9589                    .await?;
9590                let returned = data
9591                    .pointer("/clearProjectV2ItemFieldValue/projectV2Item")
9592                    .ok_or_else(|| SourceError::Malformed {
9593                        message: "GitHub field clear returned no project item".into(),
9594                    })?;
9595                if required_str(returned, "id")? != item_id {
9596                    return Err(SourceError::Malformed {
9597                        message: "GitHub field clear returned the wrong project item".into(),
9598                    });
9599                }
9600                Ok(())
9601            }
9602        }
9603    }
9604
9605    /// The refusal a priority is answered with by an instance configured with no
9606    /// `priority_mapping`, which holds none.
9607    fn holds_no_priority(&self) -> SourceError {
9608        SourceError::Refused {
9609            message: format!(
9610                "source {} holds no task priority: its configuration sets no priority_mapping; \
9611                 next: set priority_mapping on this source, then run `onetaskgraph sources \
9612                 fields {} --apply` to set its board up",
9613                self.name, self.name
9614            ),
9615        }
9616    }
9617
9618    /// Set one task's priority and nothing else; see [`TaskSource::set_task_priority`].
9619    ///
9620    /// One field write — a select, or a clear for `none` — and no title, body, label, state
9621    /// or `Status` request. Clearing a priority an item does not hold sends nothing.
9622    async fn set_priority(
9623        &self,
9624        id: &NativeId,
9625        priority: Priority,
9626    ) -> Result<Option<Priority>, SourceError> {
9627        if self.priorities.is_none() {
9628            return Err(self.holds_no_priority());
9629        }
9630        let Some(mut item) = self
9631            .bound_item(id)
9632            .await?
9633            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9634        else {
9635            return Ok(None);
9636        };
9637        if priority == Priority::None && !item.holds_priority() {
9638            return Ok(Some(priority));
9639        }
9640        // The item's own read carries the field's definition whenever it holds a value of
9641        // it, which a clear always does; a select onto an item holding none reads the board.
9642        let board = match (item.carried_board(), item.named_board()) {
9643            (Some(board), _) => board,
9644            (None, Some(id)) if item.defines(PRIORITY_FIELD) => BoardFields {
9645                id,
9646                fields: json!({"nodes": item.fields.clone(), "pageInfo": {"hasNextPage": false}}),
9647            },
9648            _ => self.board_fields().await?,
9649        };
9650        let Some(write) = self.priority_write(&board.fields, Some(&item), priority)? else {
9651            return Ok(Some(priority));
9652        };
9653        let (document, root, input) = match write {
9654            PriorityWrite::Select { field, option } => (
9655                graphql::UPDATE_FIELD,
9656                "updateProjectV2ItemFieldValue",
9657                json!({"projectId":board.id.as_str(),"itemId":item.item_id,"fieldId":field,"value":{"singleSelectOptionId":option}}),
9658            ),
9659            PriorityWrite::Clear { field } => (
9660                graphql::CLEAR_FIELD,
9661                "clearProjectV2ItemFieldValue",
9662                json!({"projectId":board.id.as_str(),"itemId":item.item_id,"fieldId":field}),
9663            ),
9664        };
9665        let data = self
9666            .graphql(
9667                document,
9668                json!({"input":input,"readPriority":true,"priorityName":PRIORITY_FIELD}),
9669            )
9670            .await?;
9671        let returned = data
9672            .get(root)
9673            .and_then(|value| value.get("projectV2Item"))
9674            .ok_or_else(|| SourceError::Malformed {
9675                message: "GitHub priority write returned no project item".into(),
9676            })?;
9677        if required_str(returned, "id")? != item.item_id {
9678            return Err(SourceError::Malformed {
9679                message: "GitHub priority write returned the wrong project item".into(),
9680            });
9681        }
9682        let value = returned
9683            .get("fieldValueByName")
9684            .ok_or_else(|| SourceError::Malformed {
9685                message: "GitHub priority write returned no priority read-back".into(),
9686            })?;
9687        if !value.is_null()
9688            && value.pointer("/field/name").and_then(Value::as_str) != Some(PRIORITY_FIELD)
9689        {
9690            return Err(SourceError::Malformed {
9691                message: "GitHub priority read-back is not a Priority field value".into(),
9692            });
9693        }
9694        let values = if value.is_null() {
9695            Vec::new()
9696        } else {
9697            vec![value.clone()]
9698        };
9699        item.priority = self.held_priority(&values)?;
9700        let answer = item.task()?.priority;
9701        self.remember_written(item, false)?;
9702        Ok(Some(answer))
9703    }
9704
9705    /// Replace one task's visible body and nothing else; see
9706    /// [`TaskSource::set_task_content`].
9707    ///
9708    /// One update of the body, which differs from the body GitHub holds only outside the
9709    /// metadata slot — the slot is kept byte for byte, so every caller key and every list
9710    /// this source keeps there reads back as it was. A body that would not change is not
9711    /// sent at all.
9712    async fn replace_content(
9713        &self,
9714        id: &NativeId,
9715        content: &str,
9716    ) -> Result<Option<()>, SourceError> {
9717        let Some(mut item) = self
9718            .bound_item(id)
9719            .await?
9720            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9721        else {
9722            return Ok(None);
9723        };
9724        let held = item.raw_body.clone().unwrap_or_default();
9725        // The task's `## Links` section, re-rendered from the links it holds, stays with it.
9726        let content = &onetaskgraph_plugin_api::relinked(content, item.body.as_deref(), &item.slot);
9727        let body = with_content(&held, &self.marked(content))?;
9728        // Checked before anything is sent: content ending in what this source reads as its own
9729        // metadata slot would read back as metadata rather than as the content it was.
9730        let (visible, slot) = self.visible(Some(body.clone()))?;
9731        if visible.as_deref().unwrap_or_default() != content || slot != item.slot {
9732            return Err(SourceError::Refused {
9733                message: format!(
9734                    "this content ends in what source {} reads as its own metadata slot \
9735                     ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
9736                     as content; next: remove that trailing block from the content",
9737                    self.name
9738                ),
9739            });
9740        }
9741        if body != held {
9742            self.update_content(item.content_kind, &item.id, json!({"body": body}))
9743                .await?;
9744        }
9745        item.body = visible.filter(|value| !value.is_empty());
9746        item.raw_body = Some(body);
9747        item.slot = slot;
9748        self.remember_written(item, false)?;
9749        Ok(Some(()))
9750    }
9751
9752    /// Apply one targeted update to one task; see [`TaskSource::update_task`].
9753    ///
9754    /// One read of the item — which carries the board's field definitions and the issue's
9755    /// `blockedBy`, so neither is read again — and then only what differs from it: the
9756    /// `Status` option and the `Priority` field together in one request, the `blockedBy`
9757    /// additions and removals the named edges differ by, and last one `updateIssue` carrying
9758    /// the title, the body — visible content and metadata slot together — and a state change.
9759    /// So an update naming any of title, body, metadata, status and priority is one read and
9760    /// at most two writes. The body goes last so that a write refused part-way leaves it, and
9761    /// the metadata in it, as it stood. A terminal status selects its option and then closes,
9762    /// as a whole write does; an open one selects its option and then reopens. The origin
9763    /// field is never written: an update is of an item that already exists, whose origin is
9764    /// what it is.
9765    ///
9766    /// The task answered is the item as those writes left it, built from the read and what was
9767    /// sent rather than read again — the same record a later read in this run answers from.
9768    ///
9769    /// Its `version` is the one the task holds after the writes: the change token the last
9770    /// mutation's own response spells — each sent as the twin selecting the whole issue, at
9771    /// the price of the plain document — or, where that mutation shows no whole issue (several
9772    /// board fields written together, or `blockedBy` alone), the token one read right after
9773    /// the writes spells. Never the token the item was read at before them. Against GitHub
9774    /// itself that token has not settled yet (`change_token::SETTLED`), so a read gives none
9775    /// until it has, and a write held to it before then is refused rather than let through;
9776    /// once settled, a read gives exactly this token unless the task changed again.
9777    async fn targeted_update(
9778        &self,
9779        id: &NativeId,
9780        update: &TaskUpdate,
9781    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
9782        Box::pin(SPELLING.scope(
9783            std::ptr::from_ref(self) as usize,
9784            self.composed_update(id, update),
9785        ))
9786        .await
9787    }
9788
9789    /// [`Self::targeted_update`], inside the scope that has its mutations answer whole.
9790    async fn composed_update(
9791        &self,
9792        id: &NativeId,
9793        update: &TaskUpdate,
9794    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
9795        // Everything this source can refuse without reading the item is refused first, in the
9796        // words a whole write of the same fields is refused with.
9797        update.consistent()?;
9798        // A duplicate close is the `cancelled` it implies where it names no status.
9799        let closing = update.duplicate_of.as_ref().map(|_| TaskUpdate {
9800            status: update.effective_status(),
9801            ..update.clone()
9802        });
9803        let update = closing.as_ref().unwrap_or(update);
9804        if update.assignees.is_some() && !self.assignees {
9805            return Err(onetaskgraph_plugin_api::unwritable_field(KIND, "assignees"));
9806        }
9807        if update
9808            .title
9809            .as_deref()
9810            .is_some_and(|title| title.starts_with(DESIGN_TITLE_PREFIX))
9811        {
9812            return Err(SourceError::Refused {
9813                message: format!(
9814                    "the title of this task begins {DESIGN_TITLE_PREFIX:?}, which is how source {} \
9815                     spells a document, so it would read back as one rather than as a task; \
9816                     retitle it",
9817                    self.name
9818                ),
9819            });
9820        }
9821        if let Some(delivers) = &update.delivers {
9822            TaskRef::listed(
9823                TaskRef::DELIVERS_KEY,
9824                id,
9825                Some(&self.name),
9826                delivers.clone(),
9827            )
9828            .map_err(|message| SourceError::Refused { message })?;
9829        }
9830        if self.priorities.is_none()
9831            && update
9832                .priority
9833                .is_some_and(|priority| priority != Priority::None)
9834        {
9835            return Err(self.holds_no_priority());
9836        }
9837        let target = update
9838            .status
9839            .as_ref()
9840            .map(|status| self.resolved_target(ItemKind::Task, status.category))
9841            .transpose()?;
9842        let Some(mut item) = self
9843            .bound_item(id)
9844            .await?
9845            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9846        else {
9847            return Ok(None);
9848        };
9849        let before = item.task()?;
9850        // The issue a duplicate close names as its survivor, refused naming both before anything
9851        // is written when it is not an issue of this board's own.
9852        let survivor = match &update.duplicate_of {
9853            Some(survivor) => Some(self.duplicate_survivor(id, &item, survivor).await?),
9854            None => None,
9855        };
9856        // The people it is to be assigned to, by node id, when they are not exactly whom it
9857        // holds: looked up — unless this process already has — and refused for a login GitHub
9858        // does not know, before anything is sent.
9859        let assignee_ids = match &update.assignees {
9860            Some(people)
9861                if item
9862                    .assignees
9863                    .as_deref()
9864                    .is_none_or(|held| !assignees::same_people(held, people)) =>
9865            {
9866                if item.content_kind == ContentKind::DraftIssue {
9867                    return Err(self.assigns_a_draft());
9868                }
9869                self.resolve_people(people).await?;
9870                Some(self.people_ids(people, &item.written_name())?)
9871            }
9872            _ => None,
9873        };
9874
9875        let mut status_move = None;
9876        if let (Some(status), Some(target)) = (&update.status, target) {
9877            let board = self.status_board(&item).await?;
9878            let (field, option, name) = self
9879                .column_for(&board.fields, ItemKind::Task, status.category, &target)?
9880                .ok_or_else(|| SourceError::Malformed {
9881                    message: format!(
9882                        "status {} of source {} names no board Status option",
9883                        category_name(status.category),
9884                        self.name
9885                    ),
9886                })?;
9887            let terminal = matches!(target, StatusTarget::Terminal(_, _));
9888            if terminal && item.content_kind == ContentKind::DraftIssue {
9889                return Err(self.closes_a_draft(status.category));
9890            }
9891            // A duplicate close lands closed as `DUPLICATE`, which reads `cancelled` as not
9892            // planned does; an issue already closed as one is not closed again.
9893            let reason = match (&target, &survivor) {
9894                (StatusTarget::Terminal(_, _), Some(_)) => Some(DUPLICATE_REASON),
9895                (StatusTarget::Terminal(_, reason), None) => Some(reason.reason()),
9896                _ => None,
9897            };
9898            let landed = self
9899                .statuses
9900                .status(ItemKind::Task, Some(&name), terminal, reason);
9901            let option_moves = item
9902                .option
9903                .as_deref()
9904                .is_none_or(|held| !held.eq_ignore_ascii_case(&name));
9905            let state_moves = item.content_kind == ContentKind::Issue
9906                && (item.closed != terminal
9907                    || (terminal && item.status != landed)
9908                    || (survivor.is_some() && item.reason.as_deref() != Some(DUPLICATE_REASON)));
9909            if let Some(moves) = Moves::of(option_moves, state_moves) {
9910                status_move = Some(StatusMove {
9911                    board: board.id,
9912                    field,
9913                    option,
9914                    name,
9915                    target,
9916                    landed,
9917                    moves,
9918                });
9919            }
9920        }
9921
9922        let mut priority_move = None;
9923        if let Some(priority) = update.priority
9924            && self.priorities.is_some()
9925            && item.priority != HeldPriority::Read(priority)
9926        {
9927            let board = match (item.carried_board(), item.named_board()) {
9928                (Some(board), _) => board,
9929                (None, Some(board)) if item.defines(PRIORITY_FIELD) => BoardFields {
9930                    id: board,
9931                    fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
9932                },
9933                _ => self.board_fields().await?,
9934            };
9935            if let Some(write) = self.priority_write(&board.fields, Some(&item), priority)? {
9936                priority_move = Some((board.id, write, priority));
9937            }
9938        }
9939
9940        // The metadata keys this update names that a board text field projects, and what
9941        // that does to those fields — refused, as a whole write refuses it, before anything
9942        // is sent.
9943        let touched: Vec<&str> = update
9944            .metadata_set
9945            .keys()
9946            .chain(update.metadata_remove.iter())
9947            .map(MetadataKey::as_str)
9948            .collect();
9949        let mut projection_move = None;
9950        if self
9951            .metadata_fields
9952            .iter()
9953            .any(|projection| touched.contains(&&*projection.key))
9954        {
9955            let mut metadata = item.slot.clone();
9956            for (key, value) in &update.metadata_set {
9957                metadata.insert(key.as_str().to_owned(), value.clone());
9958            }
9959            for key in &update.metadata_remove {
9960                metadata.remove(key.as_str());
9961            }
9962            let board = self.projection_board(&item).await?;
9963            let (writes, projected) = self.projection_writes(
9964                &board.fields,
9965                Some(&item.projected),
9966                &metadata,
9967                Some(&touched),
9968            )?;
9969            projection_move = Some((board.id, writes, projected));
9970        }
9971
9972        // Resolved before the body is composed, because a far end `blockedBy` cannot name is
9973        // recorded in the slot, and the slot travels in the one body update below.
9974        let edges = match &update.depends_on {
9975            Some(edges) => Some(
9976                self.partition_edges(
9977                    BoardKind::Work(ItemKind::Task),
9978                    item.content_kind,
9979                    item.blocked_by.as_deref(),
9980                    edges,
9981                )
9982                .await?,
9983            ),
9984            None => None,
9985        };
9986
9987        // A record primed from what a producer wrote holds no body anybody read, so an update
9988        // changing the body reads it first: by the `Status` write's own answer when the update
9989        // moves the option — the mutation answering with the issue whole — and otherwise by
9990        // reading the issue. The body is then composed against what GitHub holds now.
9991        let mut option_selected = false;
9992        // The mark stays until a read lands, so an update that writes no body, or one whose
9993        // read fails, leaves the next update of it to read the body too.
9994        if (update.content.is_some()
9995            || !update.metadata_set.is_empty()
9996            || !update.metadata_remove.is_empty()
9997            || update.delivers.is_some()
9998            || update.repositories.is_some()
9999            || edges.is_some())
10000            && self.is_unread(id)
10001        {
10002            let live = match status_move.as_ref().filter(|moving| moving.moves.option()) {
10003                Some(moving) => {
10004                    option_selected = true;
10005                    Some(
10006                        self.select_reading_body(
10007                            moving.board.as_str(),
10008                            &item.item_id,
10009                            &moving.field,
10010                            &moving.option,
10011                        )
10012                        .await?,
10013                    )
10014                }
10015                None => {
10016                    self.forget(id)?;
10017                    let Some(read) = self.item_by_id(id).await? else {
10018                        return Ok(None);
10019                    };
10020                    read.raw_body
10021                }
10022            };
10023            let (visible, read_slot) = self.visible(live.clone())?;
10024            self.mark_read(id);
10025            item.raw_body = live;
10026            item.body = visible;
10027            item.slot = read_slot;
10028        }
10029
10030        let mut slot = item.slot.clone();
10031        for (key, value) in &update.metadata_set {
10032            slot.insert(key.as_str().to_owned(), value.clone());
10033        }
10034        for key in &update.metadata_remove {
10035            slot.remove(key.as_str());
10036        }
10037        if let Some(delivers) = &update.delivers {
10038            set_task_list(&mut slot, TaskRef::DELIVERS_KEY, delivers);
10039        }
10040        // The list a whole write records, by the same rule: none when it is exactly the issue's
10041        // own repository, or empty with no issue repository to derive, and otherwise the list.
10042        if let Some(repositories) = &update.repositories {
10043            let derivable = item
10044                .own_repository
10045                .as_ref()
10046                .map_or(repositories.is_empty(), |own| {
10047                    repositories.as_slice() == std::slice::from_ref(own)
10048                });
10049            if derivable {
10050                slot.remove(Repository::METADATA_KEY);
10051            } else {
10052                slot.insert(
10053                    Repository::METADATA_KEY.to_owned(),
10054                    Value::Array(
10055                        repositories
10056                            .iter()
10057                            .map(|repository| Value::String(repository.as_str().to_owned()))
10058                            .collect(),
10059                    ),
10060                );
10061            }
10062        }
10063        if let Some((_, recorded)) = &edges {
10064            record_edges(&mut slot, recorded);
10065        }
10066        let held = item.raw_body.clone().unwrap_or_default();
10067        // A content write keeps the task's `## Links` section, re-rendered from the links the
10068        // slot holds once written.
10069        let relinked = update
10070            .content
10071            .as_deref()
10072            .map(|content| onetaskgraph_plugin_api::relinked(content, item.body.as_deref(), &slot));
10073        let content = match &relinked {
10074            Some(content) => with_content(&held, &self.marked(content))?,
10075            None => held.clone(),
10076        };
10077        // A slot holding what it held is kept byte for byte, compared as JSON rather than as
10078        // the body's bytes, as a metadata write compares it: a slot a person spelled with
10079        // other whitespace would otherwise be re-encoded, which is a write nobody asked for.
10080        let body = if slot == item.slot {
10081            content
10082        } else {
10083            with_slot(&content, &slot)?
10084        };
10085        // Checked before anything is sent, as a content write checks it: content ending in
10086        // what this source reads as its own slot would read back as metadata.
10087        let (visible, read) = self.visible(Some(body.clone()))?;
10088        let wanted = relinked.as_deref().or(item.body.as_deref());
10089        if visible.as_deref().unwrap_or_default() != wanted.unwrap_or_default() || read != slot {
10090            return Err(SourceError::Refused {
10091                message: format!(
10092                    "this content ends in what source {} reads as its own metadata slot \
10093                     ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
10094                     as content; next: remove that trailing block from the content",
10095                    self.name
10096                ),
10097            });
10098        }
10099        let recorded_moves =
10100            slot.get(DependencyEdge::RECORDED_KEY) != item.slot.get(DependencyEdge::RECORDED_KEY);
10101
10102        // One `updateIssue` carries all three, because every mutation spends the secondary
10103        // limiter and the title, body and state are one mutation's inputs.
10104        let mut fields = serde_json::Map::new();
10105        if let Some(title) = update.title.as_ref().filter(|title| **title != item.title) {
10106            fields.insert("title".to_owned(), json!(title));
10107        }
10108        if body != held {
10109            fields.insert("body".to_owned(), json!(body));
10110        }
10111        // A duplicate's closure is `closeIssue`'s, sent after this update: `stateInput` names
10112        // no survivor.
10113        if let Some(moving) = status_move
10114            .as_ref()
10115            .filter(|moving| moving.moves.state() && survivor.is_none())
10116        {
10117            fields.insert("stateInput".to_owned(), state_input(Some(&moving.target)));
10118        }
10119        let closes_as_duplicate = status_move
10120            .as_ref()
10121            .is_some_and(|moving| moving.moves.state())
10122            && survivor.is_some();
10123        // The assignees ride the same mutation: replacing whoever the issue holds, in the one
10124        // `updateIssue` this update already ends with — or as the one it sends for them alone.
10125        if let Some(ids) = &assignee_ids {
10126            fields.insert("assigneeIds".to_owned(), json!(ids));
10127        }
10128        // **The body is written last, and that is the guarantee a refusal part-way keeps.**
10129        // GitHub runs no two requests as one, and runs one document's mutation fields in order
10130        // without undoing an earlier field when a later one fails — so a body written before a
10131        // board field the board then refused would be left changed. Written after every other
10132        // write has landed, a refusal anywhere leaves the item's body, and every metadata key
10133        // it carries, exactly as they stood. So the `Status` option and the `Priority` field go
10134        // first, together in one request — a terminal option selected before the issue
10135        // closes, as a whole write does — then the `blockedBy` difference, then the body.
10136        let mut board_writes: Vec<(&BoardId, (String, Value))> = Vec::new();
10137        let mut clears: Vec<(&BoardId, &str)> = Vec::new();
10138        if let Some(moving) = status_move
10139            .as_ref()
10140            .filter(|moving| moving.moves.option() && !option_selected)
10141        {
10142            board_writes.push((
10143                &moving.board,
10144                (
10145                    moving.field.clone(),
10146                    json!({"singleSelectOptionId": moving.option}),
10147                ),
10148            ));
10149        }
10150        match &priority_move {
10151            Some((board, PriorityWrite::Select { field, option }, _)) => board_writes.push((
10152                board,
10153                (field.clone(), json!({"singleSelectOptionId": option})),
10154            )),
10155            Some((board, PriorityWrite::Clear { field }, _)) => clears.push((board, field)),
10156            None => {}
10157        }
10158        if let Some((board, writes, _)) = &projection_move {
10159            for write in writes {
10160                let (mut values, mut cleared) = (Vec::new(), Vec::new());
10161                write.join(&mut values, &mut cleared);
10162                board_writes.extend(values.into_iter().map(|value| (board, value)));
10163                clears.extend(cleared.into_iter().map(|field| (board, field)));
10164            }
10165        }
10166        let mut boards: Vec<&BoardId> = board_writes.iter().map(|(board, _)| *board).collect();
10167        boards.extend(clears.iter().map(|(board, _)| *board));
10168        boards.dedup_by(|one, other| one.as_str() == other.as_str());
10169        for board in boards {
10170            let writes = board_writes
10171                .iter()
10172                .filter(|(on, _)| on.as_str() == board.as_str())
10173                .map(|(_, write)| write.clone())
10174                .collect::<Vec<_>>();
10175            let cleared = clears
10176                .iter()
10177                .filter(|(on, _)| on.as_str() == board.as_str())
10178                .map(|(_, field)| *field)
10179                .collect::<Vec<_>>();
10180            self.set_item_fields(board.as_str(), &item.item_id, &writes, &cleared)
10181                .await?;
10182        }
10183        // Whether anything is sent: what the version answered has to come after.
10184        let sends = option_selected
10185            || !board_writes.is_empty()
10186            || !clears.is_empty()
10187            || !fields.is_empty()
10188            || closes_as_duplicate;
10189        let mut blocked_by_moved = false;
10190        if let Some((native, _)) = &edges
10191            && item.content_kind == ContentKind::Issue
10192        {
10193            blocked_by_moved = self
10194                .reconcile_blocked_by(
10195                    &item.id,
10196                    native,
10197                    Issue::Existing(item.blocked_by.as_deref()),
10198                )
10199                .await?;
10200        }
10201        if !fields.is_empty() {
10202            self.update_content(item.content_kind, &item.id, Value::Object(fields))
10203                .await?;
10204        }
10205        // Last, the duplicate's closure, with the survivor GitHub links it to: the card already
10206        // shows the `cancelled` option, so a refusal here leaves an open issue at a terminal
10207        // card, which the next write of the same status closes.
10208        if let (true, Some(survivor)) = (closes_as_duplicate, &survivor) {
10209            self.graphql(
10210                graphql::CLOSE_ISSUE,
10211                json!({"input":{"issueId":item.id.0,"stateReason":DUPLICATE_REASON,
10212                                "duplicateIssueId":survivor.0}}),
10213            )
10214            .await?;
10215        }
10216
10217        // The `blockedBy` this item was read with is what the write just changed, so it is no
10218        // answer any more: a later write in this command would reconcile against it — re-adding
10219        // what it kept and never removing what it dropped — and a forward-edge read would
10220        // answer with it. Left unknown, each asks GitHub instead.
10221        if blocked_by_moved {
10222            item.blocked_by = None;
10223        }
10224        if let Some(title) = &update.title {
10225            item.title.clone_from(title);
10226        }
10227        item.body = visible.filter(|value| !value.is_empty());
10228        item.raw_body = (!body.is_empty() || item.raw_body.is_some()).then_some(body);
10229        item.slot = slot;
10230        if let Some(delivers) = &update.delivers {
10231            item.delivers.clone_from(delivers);
10232        }
10233        if let Some(repositories) = &update.repositories {
10234            item.repositories.clone_from(repositories);
10235        }
10236        if let Some(moving) = status_move {
10237            item.closed = matches!(moving.target, StatusTarget::Terminal(_, _))
10238                && item.content_kind == ContentKind::Issue;
10239            if moving.moves.state() {
10240                item.reason = match &moving.target {
10241                    StatusTarget::Terminal(_, _) if survivor.is_some() => {
10242                        Some(DUPLICATE_REASON.to_owned())
10243                    }
10244                    StatusTarget::Terminal(_, reason) => Some(reason.reason().to_owned()),
10245                    _ => None,
10246                };
10247            }
10248            item.status = moving.landed;
10249            item.option = Some(moving.name);
10250        }
10251        if let Some((_, _, priority)) = priority_move {
10252            item.priority = HeldPriority::Read(priority);
10253        }
10254        if let Some((_, _, projected)) = projection_move {
10255            item.projected = projected;
10256        }
10257        // Only a write that assigned anyone moves whom the item holds, and they are who GitHub
10258        // says they are; one naming the people it already holds leaves its read as it was.
10259        if let (Some(people), Some(_)) = (&update.assignees, &assignee_ids) {
10260            item.assignees = Some(self.spelled(people));
10261        }
10262        let mut task = item.task()?;
10263        let mut written = update.changed(&before, &task);
10264        if blocked_by_moved || recorded_moves {
10265            written.insert(UpdatedField::DependsOn);
10266        }
10267        if closes_as_duplicate {
10268            written.insert(UpdatedField::DuplicateOf);
10269        }
10270        if sends || blocked_by_moved {
10271            // The token the item was read at is not the one it holds now. A batch of updates
10272            // holding this one's writes back reads every task it wrote once they are sent.
10273            task.version = if self.holding_writes_of(id) {
10274                None
10275            } else {
10276                self.version_after_write(id).await
10277            };
10278        }
10279        self.remember_written(item, false)?;
10280        Ok(Some(TaskUpdateOutcome {
10281            task,
10282            written,
10283            delivers_before: before.delivers,
10284        }))
10285    }
10286
10287    /// The issue `survivor` names, the one a duplicate close of `id` links GitHub's closure to:
10288    /// refused, naming both, when it is not an issue of this board's own source — a task of
10289    /// another source, a board draft, an item this board does not hold — or is `id` itself.
10290    async fn duplicate_survivor(
10291        &self,
10292        id: &NativeId,
10293        item: &Resolved,
10294        survivor: &TaskRef,
10295    ) -> Result<NativeId, SourceError> {
10296        let refused = |why: String| SourceError::Refused {
10297            message: format!(
10298                "{} cannot be closed as a duplicate of {survivor}: {why}; next: name an issue of \
10299                 source {} as the survivor",
10300                TaskRef::qualified(&self.name, id),
10301                self.name
10302            ),
10303        };
10304        let (source, native) = survivor.parts(self.name.as_str());
10305        if source != self.name.as_str() {
10306            return Err(refused(format!(
10307                "it is not a GitHub issue of source {}, which GitHub links a duplicate to",
10308                self.name
10309            )));
10310        }
10311        let native = NativeId(native.to_owned());
10312        if native == *id || native == item.id {
10313            return Err(refused("a task cannot be a duplicate of itself".to_owned()));
10314        }
10315        match self.bound_item(&native).await? {
10316            Some(held) if held.content_kind == ContentKind::Issue => Ok(held.id),
10317            Some(_) => Err(refused(
10318                "it is a board draft, which is no issue GitHub can link a duplicate to".to_owned(),
10319            )),
10320            None => Err(refused(format!("source {} holds no such issue", self.name))),
10321        }
10322    }
10323
10324    /// The change token the task `id` holds after the writes a targeted update just sent: the
10325    /// one the last mutation's own response showed, or, where none showed the whole issue, the
10326    /// one a read made now spells. `None` when that read cannot say — never the token the
10327    /// task was read at before the writes.
10328    async fn version_after_write(&self, id: &NativeId) -> Option<String> {
10329        // A response that showed the issue whole answers, a token or none: a read made now
10330        // would read the same parts.
10331        if let Some(answered) = self.written_answer(id) {
10332            return answered;
10333        }
10334        // An item this command created is answered from its own record, not read.
10335        if self.created().ok()?.iter().any(|own| own.id == *id) {
10336            return None;
10337        }
10338        let read = self.item_by_id(id).await.ok()??;
10339        let token = read.written_version()?;
10340        self.remember_written_token(&read, token.clone());
10341        Some(token)
10342    }
10343
10344    /// Replace one issue's visible body and its [`MetadataKey::TEMPLATE_KEY`] slot entry
10345    /// together, and nothing else; see [`TaskSource::set_task_rendering`].
10346    ///
10347    /// One update of the body: the content outside the slot, and inside it that one entry,
10348    /// every other entry kept as it was. This source keeps no template answers — an issue has
10349    /// no room beside itself that is not its body, and answers written there would duplicate
10350    /// what the content already says and count against GitHub's body limit — so `answers`
10351    /// reaches nothing here. A body that would not change is not sent at all.
10352    async fn replace_rendering(
10353        &self,
10354        id: &NativeId,
10355        kind: BoardKind,
10356        content: &str,
10357        provenance: &Value,
10358        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
10359    ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
10360        let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
10361            return Ok(None);
10362        };
10363        let held = item.raw_body.clone().unwrap_or_default();
10364        let mut slot = item.slot.clone();
10365        slot.insert(MetadataKey::TEMPLATE_KEY.to_owned(), provenance.clone());
10366        let rewritten;
10367        let content = if let Some(assets) = assets {
10368            let uploads = self
10369                .upload_assets(item.own_repository.as_ref(), assets)
10370                .await?;
10371            rewritten =
10372                onetaskgraph_plugin_api::serve_asset_references(content, &mut slot, &uploads);
10373            rewritten.as_str()
10374        } else {
10375            content
10376        };
10377        let relinked = onetaskgraph_plugin_api::relinked(content, item.body.as_deref(), &slot);
10378        let content = relinked.as_str();
10379        let body = with_slot(&with_content(&held, &self.marked(content))?, &slot)?;
10380        // Checked before anything is sent, as a content write checks it.
10381        let (visible, read) = self.visible(Some(body.clone()))?;
10382        if visible.as_deref().unwrap_or_default() != content || read != slot {
10383            return Err(SourceError::Refused {
10384                message: format!(
10385                    "this content ends in what source {} reads as its own metadata slot \
10386                     ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
10387                     as content; next: remove that trailing block from the template",
10388                    self.name
10389                ),
10390            });
10391        }
10392        if body != held {
10393            self.update_content(item.content_kind, &item.id, json!({"body": body}))
10394                .await?;
10395        }
10396        item.body = visible.filter(|value| !value.is_empty());
10397        item.raw_body = Some(body);
10398        // The content as a read answers it: without the `## Links` section of a linked task.
10399        let answered = onetaskgraph_plugin_api::read_content(Some(content.to_owned()), &read);
10400        item.slot = read;
10401        self.remember_written(item, false)?;
10402        Ok(Some(onetaskgraph_plugin_api::AssetsWritten {
10403            id: id.clone(),
10404            content: answered,
10405        }))
10406    }
10407
10408    async fn set_item_field(
10409        &self,
10410        board_id: &str,
10411        item_id: &str,
10412        field_id: &str,
10413        value: Value,
10414    ) -> Result<(), SourceError> {
10415        let data = self
10416            .graphql(
10417                graphql::UPDATE_FIELD,
10418                json!({"input":{
10419                    "projectId":board_id,"itemId":item_id,"fieldId":field_id,"value":value
10420                },"readPriority":false,"priorityName":PRIORITY_FIELD}),
10421            )
10422            .await?;
10423        field_update_item(&data, item_id).map(|_| ())
10424    }
10425
10426    /// GitHub accepts one value per field mutation; aliases combine those mutations in
10427    /// one request — writes in the order given, then clears. A lone write is
10428    /// [`graphql::UPDATE_FIELD`] and a lone clear [`graphql::CLEAR_FIELD`]; more than one
10429    /// request's slots hold go in further requests of the same document, in order. Every
10430    /// returned item id is checked, including optional aliases.
10431    async fn set_item_fields(
10432        &self,
10433        board: &str,
10434        item: &str,
10435        fields: &[(String, Value)],
10436        clears: &[&str],
10437    ) -> Result<(), SourceError> {
10438        if !(fields.is_empty() && clears.is_empty())
10439            && self.hold_fields(board, item, fields, clears)?
10440        {
10441            return Ok(());
10442        }
10443        match (fields, clears) {
10444            ([], []) => return Ok(()),
10445            ([(field, value)], []) => {
10446                return self.set_item_field(board, item, field, value.clone()).await;
10447            }
10448            ([], [field]) => {
10449                return self
10450                    .write_priority(
10451                        board,
10452                        item,
10453                        &PriorityWrite::Clear {
10454                            field: (*field).to_owned(),
10455                        },
10456                    )
10457                    .await;
10458            }
10459            _ => {}
10460        }
10461        // Any field of the request stands in for an input a slot leaves out, which GitHub
10462        // still requires to be well formed although it never runs it.
10463        let filler = fields
10464            .first()
10465            .map_or_else(|| clears[0], |(field, _)| field.as_str());
10466        let mut writes = fields.iter();
10467        let mut cleared = clears.iter();
10468        loop {
10469            let batch: Vec<&(String, Value)> =
10470                writes.by_ref().take(FIELD_WRITE_SLOTS.len()).collect();
10471            let batch_clears: Vec<&&str> = cleared.by_ref().take(FIELD_CLEAR_SLOTS.len()).collect();
10472            if batch.is_empty() && batch_clears.is_empty() {
10473                return Ok(());
10474            }
10475            let mut variables = serde_json::Map::new();
10476            for (index, slot) in FIELD_WRITE_SLOTS.iter().enumerate() {
10477                let input = match batch.get(index) {
10478                    Some((field, value)) => {
10479                        json!({"projectId":board,"itemId":item,"fieldId":field,"value":value})
10480                    }
10481                    None => json!({"projectId":board,"itemId":item,"fieldId":filler,
10482                                   "value":{"text":""}}),
10483                };
10484                variables.insert(slot.variable.to_owned(), input);
10485                variables.insert(slot.include.to_owned(), json!(index < batch.len()));
10486            }
10487            for (index, slot) in FIELD_CLEAR_SLOTS.iter().enumerate() {
10488                let field = batch_clears.get(index).map_or(filler, |field| **field);
10489                variables.insert(
10490                    slot.variable.to_owned(),
10491                    json!({"projectId":board,"itemId":item,"fieldId":field}),
10492                );
10493                variables.insert(slot.include.to_owned(), json!(index < batch_clears.len()));
10494            }
10495            let data = self
10496                .graphql(graphql::UPDATE_FIELDS, Value::Object(variables))
10497                .await?;
10498            let sent = FIELD_WRITE_SLOTS[..batch.len()]
10499                .iter()
10500                .chain(&FIELD_CLEAR_SLOTS[..batch_clears.len()]);
10501            for slot in sent {
10502                let alias = slot.alias;
10503                let returned = data
10504                    .get(alias)
10505                    .and_then(|value| value.get("projectV2Item"))
10506                    .ok_or_else(|| SourceError::Malformed {
10507                        message: format!("GitHub field update {alias} returned no project item"),
10508                    })?;
10509                if required_str(returned, "id")? != item {
10510                    return Err(SourceError::Malformed {
10511                        message: format!(
10512                            "GitHub field update {alias} returned the wrong project item"
10513                        ),
10514                    });
10515                }
10516            }
10517        }
10518    }
10519
10520    async fn native_dependency_ids(&self, id: &NativeId) -> Result<Vec<String>, SourceError> {
10521        let mut after: Option<String> = None;
10522        let mut ids = Vec::new();
10523        loop {
10524            let data = self
10525                .graphql(
10526                    graphql::ISSUE_DEPENDENCIES,
10527                    json!({"id":id.0,"first":MAX_PAGE_SIZE,"after":after}),
10528                )
10529                .await?;
10530            let connection =
10531                data.pointer("/node/blockedBy")
10532                    .ok_or_else(|| SourceError::Malformed {
10533                        message: "GitHub dependency response has no blockedBy connection".into(),
10534                    })?;
10535            ids.extend(
10536                connection
10537                    .get("nodes")
10538                    .and_then(Value::as_array)
10539                    .ok_or_else(|| SourceError::Malformed {
10540                        message: "GitHub dependency response nodes is not an array".into(),
10541                    })?
10542                    .iter()
10543                    .map(|value| required_str(value, "id").map(str::to_owned))
10544                    .collect::<Result<Vec<_>, _>>()?,
10545            );
10546            let next = next_cursor(connection)?;
10547            if let Some(next) = &next {
10548                validate_cursor_progress(after.as_deref(), &next.0)?;
10549            }
10550            after = next.map(|cursor| cursor.0);
10551            if after.is_none() {
10552                return Ok(ids);
10553            }
10554        }
10555    }
10556
10557    async fn dependencies(
10558        &self,
10559        id: &NativeId,
10560        near_kind: ItemKind,
10561        direction: Direction,
10562        page: &PageRequest,
10563    ) -> Result<Page<DependencyEdge>, SourceError> {
10564        validate_page(page)?;
10565        let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
10566        let cursor = page.cursor.as_ref().map(|c| c.0.as_str());
10567        let recorded = recorded_offset(cursor, direction)?;
10568        // What this issue is blocked by, when a read of it by its own id in this command
10569        // already carried the whole connection — a copy reads the item it writes before it
10570        // reads its edges — and the page asked for is the whole of it, or the recorded tail
10571        // after it. Answered from that read, in the shape the dependency read answers in;
10572        // anything else is asked of GitHub.
10573        let carried = match direction {
10574            Direction::DependsOn => self
10575                .resolved_cache()?
10576                .get(id)
10577                .filter(|item| item.content_kind == ContentKind::Issue)
10578                .and_then(|item| Some((item.blocked_by.clone()?, item.raw_body.clone()))),
10579            Direction::DependedOnBy => None,
10580        }
10581        .filter(|(nodes, _)| recorded.is_some() || (cursor.is_none() && nodes.len() <= limit));
10582        // Asked for even in the recorded phase, whose page reads nothing from the
10583        // connection: `__typename` is what says whether this item has a native
10584        // relationship at all, and that is what decides which far ends the reserved key is
10585        // allowed to hold.
10586        let data = match carried {
10587            Some((nodes, body)) => json!({"node":{"__typename":"Issue","body":body,
10588                "blockedBy":{"nodes":nodes,"pageInfo":{"hasNextPage":false,"endCursor":null}}}}),
10589            None => {
10590                let after = if recorded.is_some() { None } else { cursor };
10591                let first = page.limit.min(MAX_PAGE_SIZE);
10592                match direction {
10593                    Direction::DependsOn => {
10594                        self.graphql(
10595                            graphql::ISSUE_DEPENDS_ON,
10596                            json!({"id":id.0,"first":first,"after":after,"owner":self.owner,
10597                                   "number":self.project_number,
10598                                   "boardItems":BOARD_ITEMS_PAGE_SIZE}),
10599                        )
10600                        .await?
10601                    }
10602                    Direction::DependedOnBy => {
10603                        self.graphql(
10604                            graphql::ISSUE_DEPENDED_ON_BY,
10605                            json!({"id":id.0,"first":first,"after":after}),
10606                        )
10607                        .await?
10608                    }
10609                }
10610            }
10611        };
10612        let draft_slot = draft_slot(&data, id, self.project_number)?;
10613        let node =
10614            data.get("node")
10615                .filter(|v| !v.is_null())
10616                .ok_or_else(|| SourceError::Refused {
10617                    message: format!(
10618                        "GitHub item {} was not found or does not support dependencies",
10619                        id.0
10620                    ),
10621                })?;
10622        let connection_name = match direction {
10623            Direction::DependsOn => "blockedBy",
10624            Direction::DependedOnBy => "blocking",
10625        };
10626        // A draft has neither `blockedBy` nor `blocking`, so nothing it depends on can be
10627        // named natively and the reserved key may hold any far end. An issue's connections
10628        // hold issues, and this source reads them at the near item's own level.
10629        let natively_names = (required_str(node, "__typename")? == "Issue").then_some(near_kind);
10630        if let Some(offset) = recorded {
10631            return Ok(recorded_page(
10632                self.recorded_edges(
10633                    id,
10634                    near_kind,
10635                    direction,
10636                    natively_names,
10637                    node,
10638                    draft_slot.as_ref(),
10639                )
10640                .await?,
10641                offset,
10642                limit,
10643            ));
10644        }
10645        if natively_names.is_none() {
10646            return Ok(recorded_page(
10647                self.recorded_edges(
10648                    id,
10649                    near_kind,
10650                    direction,
10651                    natively_names,
10652                    node,
10653                    draft_slot.as_ref(),
10654                )
10655                .await?,
10656                0,
10657                limit,
10658            ));
10659        }
10660        let connection = node
10661            .get(connection_name)
10662            .ok_or_else(|| SourceError::Malformed {
10663                message: "GitHub dependency response is missing its connection".into(),
10664            })?;
10665        let nodes = connection
10666            .get("nodes")
10667            .and_then(Value::as_array)
10668            .ok_or_else(|| SourceError::Malformed {
10669                message: "GitHub dependency response nodes is not an array".into(),
10670            })?;
10671        // `from` depends on `to`, always. GitHub spells the same relationship from either
10672        // end — `blockedBy` lists what this item waits on, `blocking` lists what waits on
10673        // it — so the near item is `from` in one direction and `to` in the other.
10674        let items = nodes
10675            .iter()
10676            .map(|value| {
10677                let related = NativeId(required_str(value, "id")?.into());
10678                let related_kind = related_kind(value, self.sub_issues)?;
10679                let (from, to) = match direction {
10680                    Direction::DependsOn => (
10681                        DependencyEndpoint::from_native(id.clone(), near_kind),
10682                        DependencyEndpoint::from_native(related, related_kind),
10683                    ),
10684                    Direction::DependedOnBy => (
10685                        DependencyEndpoint::from_native(related, related_kind),
10686                        DependencyEndpoint::from_native(id.clone(), near_kind),
10687                    ),
10688                };
10689                Ok(DependencyEdge {
10690                    from,
10691                    to,
10692                    kind: DependencyKind::Blocks,
10693                })
10694            })
10695            .collect::<Result<Vec<_>, SourceError>>()?;
10696        let mut next = next_cursor(connection)?;
10697        if let Some(next) = &next {
10698            validate_cursor_progress(cursor, &next.0)?;
10699        }
10700        // The recorded far ends ride on the last page of `blockedBy`, whose answer carried the
10701        // body they are recorded in, as far as the page has room — so they cost no request of
10702        // their own — and only what does not fit is resumed by a cursor.
10703        let mut items = items;
10704        if next.is_none() {
10705            let recorded = self
10706                .recorded_edges(
10707                    id,
10708                    near_kind,
10709                    direction,
10710                    natively_names,
10711                    node,
10712                    draft_slot.as_ref(),
10713                )
10714                .await?;
10715            let room = limit.saturating_sub(items.len());
10716            let total = recorded.len();
10717            items.extend(recorded.into_iter().take(room));
10718            if total > room {
10719                next = Some(Cursor(format!("{RECORDED_CURSOR}{room}")));
10720            }
10721        }
10722        Ok(Page { items, next })
10723    }
10724
10725    /// The edges this item records under [`DependencyEdge::RECORDED_KEY`], which is where
10726    /// a far end in another source has to live: no GitHub issue relationship can name one.
10727    ///
10728    /// Only forwards. The reverse of a recorded edge is derived from the far end, and this
10729    /// source never writes one down.
10730    ///
10731    /// The metadata lives in the item's own body slot, and `node` is the dependency read's
10732    /// own answer, which carries an issue's body — so an issue's recorded edges cost no
10733    /// request beyond the read already made, and reading the board for them would be a
10734    /// walk of every item for one field of one. A draft has no body in that answer, because
10735    /// a draft is not an issue, so a draft's are read off its own read by id — never off a
10736    /// listing of the board, which can be behind on the very item asked about.
10737    async fn recorded_edges(
10738        &self,
10739        id: &NativeId,
10740        near_kind: ItemKind,
10741        direction: Direction,
10742        natively_names: Option<ItemKind>,
10743        node: &Value,
10744        draft_slot: Option<&Option<BTreeMap<String, Value>>>,
10745    ) -> Result<Vec<DependencyEdge>, SourceError> {
10746        if direction != Direction::DependsOn {
10747            return Ok(Vec::new());
10748        }
10749        let slot = match (node.get("body"), draft_slot) {
10750            (Some(body), _) if natively_names.is_some() => {
10751                metadata_body(body.as_str().map(str::to_owned))?.1
10752            }
10753            // A draft the dependency read itself answered: this board's, or none of its.
10754            (_, Some(Some(slot))) => slot.clone(),
10755            (_, Some(None)) => return Ok(Vec::new()),
10756            _ => {
10757                let Some(item) = self.bound_item(id).await? else {
10758                    return Ok(Vec::new());
10759                };
10760                item.slot
10761            }
10762        };
10763        DependencyEdge::recorded(&slot, id, near_kind, &self.name, natively_names)
10764            .map_err(|message| SourceError::Malformed { message })
10765    }
10766
10767    /// Why `creation_owners` refuses a create filed in `target`, or `None` when it allows it —
10768    /// every create when the list is empty.
10769    fn owner_refusal(&self, target: &RepositoryTarget) -> Option<String> {
10770        if self.creation_owners.is_empty()
10771            || self
10772                .creation_owners
10773                .iter()
10774                .any(|owner| owner.eq_ignore_ascii_case(&target.owner))
10775        {
10776            return None;
10777        }
10778        Some(format!(
10779            "source {} would create the issue in repository {}, owned by {}, and its \
10780             creation_owners allows only repositories of {}",
10781            self.name,
10782            target.slug(),
10783            target.owner,
10784            self.creation_owners.join(", ")
10785        ))
10786    }
10787
10788    fn configured_repository(&self) -> Result<&RepositoryTarget, SourceError> {
10789        self.repository
10790            .as_ref()
10791            .ok_or_else(|| SourceError::Refused {
10792                message: format!(
10793                    "source {} has no repository configured, and a GitHub Projects board has no \
10794                 repository of its own to create an issue in; set repository: owner/name on \
10795                 this source",
10796                    self.name
10797                ),
10798            })
10799    }
10800
10801    /// The repository one new issue is created in, under the rule [`RepositoryTarget`]
10802    /// states.
10803    ///
10804    /// The fallback is demanded first, whichever arm answers: a write without a configured
10805    /// repository is refused naming the field exactly as it was before the rule existed,
10806    /// so a source that could not write before cannot write now, rather than writing for
10807    /// the one item whose own field happens to decide it.
10808    ///
10809    /// Everything this refuses is refused before `createIssue`, so a refusal leaves no
10810    /// issue behind: an entry that is not a repository on [`RepositoryTarget::HOST`], an
10811    /// entry owned by someone other than the owner of the parent issue's repository —
10812    /// GitHub accepts a sub-issue from another repository of the same owner and from no
10813    /// other, so `addSubIssue` would refuse it after the issue existed — a parent the
10814    /// board does not hold, and a parent that is a draft, which GitHub gives no sub-issues,
10815    /// both of which `addSubIssue` would likewise refuse too late. Whether the entry exists
10816    /// and is visible to the token is checked where its node id is resolved, still before
10817    /// `createIssue`. The parent is read by its own id through [`Self::item_by_id`] — never
10818    /// looked up in a listing of the board, which can be minutes behind an issue its own
10819    /// `projectItems` already places on it — and that read answers first from this process's
10820    /// own record, so a project created moments ago in this command answers though GitHub
10821    /// has not caught up.
10822    async fn creation_target(
10823        &self,
10824        incoming: &Incoming<'_>,
10825    ) -> Result<RepositoryTarget, SourceError> {
10826        let what = format!(
10827            "{} {:?}",
10828            incoming.written.kind().describes(),
10829            incoming.title
10830        );
10831        let target = self
10832            .creation_rule(incoming.repositories, incoming.parent, &what)
10833            .await?;
10834        // The engine asks `creation_refusal` before anything of a copy is written; this holds
10835        // every other create to the same restriction, before `createIssue`.
10836        match self.owner_refusal(&target) {
10837            Some(message) => Err(SourceError::Refused { message }),
10838            None => Ok(target),
10839        }
10840    }
10841
10842    /// [`Self::creation_target`]'s rule over what it reads of the item — its `repositories`
10843    /// and the project issue it is filed under — with `what` naming the item in a refusal: the
10844    /// one place the rule is, so the create, [`TaskSource::creation_repository`] and the
10845    /// write-time read of who can read the issue ([`TaskSource::visibility`]) cannot answer
10846    /// differently.
10847    ///
10848    /// On a source declared private, an item's one named repository is read for its
10849    /// visibility first — once per engine hold, see the `visibility` module — and one that
10850    /// does not read private decides nothing: the issue is created in the parent's
10851    /// repository, else the configured one. A read that cannot be answered refuses.
10852    async fn creation_rule(
10853        &self,
10854        repositories: &[Repository],
10855        parent: Option<&NativeId>,
10856        what: &str,
10857    ) -> Result<RepositoryTarget, SourceError> {
10858        let parent = match parent {
10859            Some(parent) => Some(self.bound_item(parent).await?.ok_or_else(|| {
10860                SourceError::Refused {
10861                    message: format!(
10862                        "GitHub project issue {} was not found on the board of source {}, so {} \
10863                         cannot be filed under it",
10864                        parent.0, self.name, what
10865                    ),
10866                }
10867            })?),
10868            None => None,
10869        };
10870        let parents_repository = parent
10871            .as_ref()
10872            .map(|parent| {
10873                // A draft is on the board and so is found, but it has no repository to
10874                // place a task in and GitHub gives it no sub-issues, so `addSubIssue`
10875                // would refuse the task only once `createIssue` had made it.
10876                if parent.content_kind == ContentKind::DraftIssue {
10877                    return Err(SourceError::Refused {
10878                        message: format!(
10879                            "GitHub project item {} on the board of source {} is a draft, \
10880                             which cannot have sub-issues, so {} cannot be filed under it",
10881                            parent.id.0, self.name, what
10882                        ),
10883                    });
10884                }
10885                // An issue's repository is where a sub-issue is placed and whose owner it
10886                // is compared against, so a parent whose repository this source cannot
10887                // spell as `owner/name` — GitHub's login grammar is wider than this
10888                // source's floor — is one nothing can be filed under.
10889                parent
10890                    .own_repository
10891                    .as_ref()
10892                    .and_then(|origin| RepositoryTarget::from_origin(origin).ok())
10893                    .ok_or_else(|| SourceError::Malformed {
10894                        message: format!(
10895                            "GitHub project issue {} on the board of source {} is in {}, which \
10896                             is not a {}/owner/name repository this source can place {} in",
10897                            parent.id.0,
10898                            self.name,
10899                            parent
10900                                .own_repository
10901                                .as_ref()
10902                                .map_or("no repository", Repository::as_str),
10903                            RepositoryTarget::HOST,
10904                            what
10905                        ),
10906                    })
10907            })
10908            .transpose()?;
10909        self.creation_rule_in_repository(repositories, parents_repository, what)
10910            .await
10911    }
10912
10913    async fn creation_rule_in_repository(
10914        &self,
10915        repositories: &[Repository],
10916        parents_repository: Option<RepositoryTarget>,
10917        what: &str,
10918    ) -> Result<RepositoryTarget, SourceError> {
10919        let fallback = self.configured_repository()?;
10920        match repositories {
10921            [named] => {
10922                let target =
10923                    RepositoryTarget::from_origin(named).map_err(|_| SourceError::Refused {
10924                        message: format!(
10925                            "{} names repository {}, which is not a {}/owner/name repository \
10926                             source {} can create an issue in; name one that is, or name none",
10927                            what,
10928                            named.as_str(),
10929                            RepositoryTarget::HOST,
10930                            self.name
10931                        ),
10932                    })?;
10933                // On a source declared private, an issue whose one named repository does not
10934                // read private is created where an item naming none is: the item still names
10935                // that repository in its metadata slot, and its issue stays private.
10936                if self.is_declared_private()
10937                    && self.repository_visibility(&target).await?
10938                        != onetaskgraph_plugin_api::Visibility::Private
10939                {
10940                    return Ok(parents_repository.unwrap_or_else(|| fallback.clone()));
10941                }
10942                if let Some(parents) = &parents_repository
10943                    && parents.owner != target.owner
10944                {
10945                    return Err(SourceError::Refused {
10946                        message: format!(
10947                            "{} names repository {}, owned by {}, but its project's issue is in \
10948                             {}, owned by {}, and GitHub files a sub-issue only in a repository \
10949                             of the same owner as its parent issue; name a repository of {}, or \
10950                             name none",
10951                            what,
10952                            target.slug(),
10953                            target.owner,
10954                            parents.slug(),
10955                            parents.owner,
10956                            parents.owner
10957                        ),
10958                    });
10959                }
10960                Ok(target)
10961            }
10962            _ => Ok(parents_repository.unwrap_or_else(|| fallback.clone())),
10963        }
10964    }
10965
10966    /// The node id of the repository `incoming` is being created in, or the refusal naming
10967    /// the item and the repository the token cannot see.
10968    ///
10969    /// Resolved once per command per repository; see [`Self::repository_cache`].
10970    async fn repository_id(
10971        &self,
10972        repository: &RepositoryTarget,
10973        incoming: &Incoming<'_>,
10974    ) -> Result<String, SourceError> {
10975        if let Some(id) = self.repository_cache()?.get(repository).cloned() {
10976            return Ok(id);
10977        }
10978        let data = self
10979            .graphql(
10980                graphql::REPOSITORY,
10981                json!({"owner":repository.owner,"name":repository.name}),
10982            )
10983            .await?;
10984        self.repository_read(&data, repository, incoming)
10985    }
10986
10987    /// The repository's node id out of an answer carrying the `repository` root, held for
10988    /// the rest of this command, or the refusal naming the item that cannot be created in it.
10989    fn repository_read(
10990        &self,
10991        data: &Value,
10992        repository: &RepositoryTarget,
10993        incoming: &Incoming<'_>,
10994    ) -> Result<String, SourceError> {
10995        let node = data
10996            .get("repository")
10997            .filter(|value| !value.is_null())
10998            .ok_or_else(|| SourceError::Refused {
10999                message: format!(
11000                    "GitHub repository {} was not found or is not visible to the token, so {} \
11001                     {:?} cannot be created in it",
11002                    repository.slug(),
11003                    incoming.written.kind().describes(),
11004                    incoming.title
11005                ),
11006            })?;
11007        let id = required_str(node, "id")?.to_owned();
11008        self.repository_cache()?
11009            .insert(repository.clone(), id.clone());
11010        Ok(id)
11011    }
11012
11013    fn repository_cache(
11014        &self,
11015    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<RepositoryTarget, String>>, SourceError> {
11016        self.repository_cache
11017            .lock()
11018            .map_err(|_| SourceError::Unavailable {
11019                message: "this source's record of the destination repository was left \
11020                          inconsistent by an earlier failure; next: run the command again"
11021                    .into(),
11022            })
11023    }
11024
11025    /// Create or update one board item, whichever kind it is.
11026    async fn write_item(
11027        &self,
11028        incoming: &Incoming<'_>,
11029        target: Option<&NativeId>,
11030        depends_on: &[DependencyEdge],
11031    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
11032        let prepared = self.prepare_write(incoming, target, depends_on).await?;
11033        let landed = match &prepared.destination {
11034            // Its content is written last, by `complete_write`, once everything else has landed.
11035            WriteDestination::Existing(item) => Landed {
11036                content_id: item.id.clone(),
11037                item_id: Some(item.item_id.clone()),
11038                url: item.url.clone(),
11039                number: item.number,
11040            },
11041            WriteDestination::New(target) => {
11042                if self.deferring()? {
11043                    self.create_filed_issue(
11044                        prepared.board.id.as_str(),
11045                        target,
11046                        incoming,
11047                        &prepared.body,
11048                    )
11049                    .await?
11050                } else {
11051                    self.create_and_file_issue(
11052                        prepared.board.id.as_str(),
11053                        target,
11054                        incoming,
11055                        &prepared.body,
11056                    )
11057                    .await?
11058                }
11059            }
11060        };
11061        self.complete_write(incoming, prepared, landed).await
11062    }
11063
11064    /// Everything one write of `incoming` reads and decides before it sends anything: what is
11065    /// there now, where a new item is created, the board's fields, and every value refused while
11066    /// nothing has been written — the item's body included.
11067    async fn prepare_write(
11068        &self,
11069        incoming: &Incoming<'_>,
11070        target: Option<&NativeId>,
11071        depends_on: &[DependencyEdge],
11072    ) -> Result<Prepared, SourceError> {
11073        // Refused before anything is read or written: a task or a project titled the way
11074        // this board spells a document would land as an issue this same source reads back
11075        // as a document, so the field this destination cannot carry is named rather than
11076        // written and silently reclassified.
11077        if let Written::Work(kind, _) = incoming.written
11078            && incoming.title.starts_with(DESIGN_TITLE_PREFIX)
11079        {
11080            return Err(SourceError::Refused {
11081                message: format!(
11082                    "the title of this {} begins {DESIGN_TITLE_PREFIX:?}, which is how source {} \
11083                     spells a document, so it would read back as one rather than as a {}; \
11084                     retitle it, or copy it as a document",
11085                    kind.marker(),
11086                    self.name,
11087                    kind.marker()
11088                ),
11089            });
11090        }
11091        // The destination is read by its own id, and whether this board holds it is decided
11092        // by that read — its own `projectItems` — rather than by whether a listing of the
11093        // board happens to include it yet. See the module documentation.
11094        // An existing issue is never moved; a new one is created where the rule says — and
11095        // knowing where is what lets the board's fields and that repository's id be read
11096        // together, before anything below needs either.
11097        let destination = match target {
11098            Some(target) => {
11099                WriteDestination::Existing(Box::new(self.bound_item(target).await?.ok_or_else(
11100                    || SourceError::Refused {
11101                        message: format!("GitHub destination item {} was not found", target.0),
11102                    },
11103                )?))
11104            }
11105            None => {
11106                let target = self.creation_target(incoming).await?;
11107                self.creation_context(&target, incoming).await?;
11108                WriteDestination::New(target)
11109            }
11110        };
11111        let existing = destination.existing();
11112        let board = self
11113            .fields_for(
11114                existing,
11115                incoming.metadata.contains_key(ORIGIN_KEY),
11116                incoming.written.status().is_some(),
11117                incoming
11118                    .priority
11119                    .is_some_and(|priority| priority != Priority::None),
11120            )
11121            .await?;
11122        let status_target = incoming
11123            .written
11124            .work_status()
11125            .map(|(kind, status)| self.resolved_target(kind, status.category))
11126            .transpose()?;
11127        let column = match (incoming.written.work_status(), status_target.as_ref()) {
11128            (Some((kind, status)), Some(target)) => {
11129                self.column_for(&board.fields, kind, status.category, target)?
11130            }
11131            _ => None,
11132        };
11133        // Resolved before anything is created, for the reason the column above is: a
11134        // priority this board has no option for is refused while nothing has been written.
11135        let priority_write = match incoming.priority {
11136            Some(priority) => self.priority_write(&board.fields, existing, priority)?,
11137            None => None,
11138        };
11139        // And for the reason the priority is: a value no projected field can hold, or a board
11140        // that cannot hold the field, is refused while nothing has been written.
11141        let (projections, projected) = self.projection_writes(
11142            &board.fields,
11143            existing.map(|item| &item.projected),
11144            incoming.metadata,
11145            None,
11146        )?;
11147        let content_kind = existing.map_or(ContentKind::Issue, |item| item.content_kind);
11148        if content_kind == ContentKind::DraftIssue {
11149            if let (Some(StatusTarget::Terminal(_, _)), Some(status)) =
11150                (status_target.as_ref(), incoming.written.status())
11151            {
11152                return Err(self.closes_a_draft(status.category));
11153            }
11154            if incoming.parent.is_some() {
11155                return Err(SourceError::Refused {
11156                    message: "GitHub draft items cannot be a project's sub-issue".into(),
11157                });
11158            }
11159        }
11160        // The people it is to be assigned to are looked up — unless this process already has —
11161        // and a login GitHub does not know refused, while nothing has been written.
11162        if let Some(people) = incoming.assignees
11163            && existing.is_none_or(|item| {
11164                item.assignees
11165                    .as_deref()
11166                    .is_none_or(|held| !assignees::same_people(held, people))
11167            })
11168        {
11169            if content_kind == ContentKind::DraftIssue {
11170                return Err(self.assigns_a_draft());
11171            }
11172            self.resolve_people(people).await?;
11173            self.people_ids(
11174                people,
11175                &existing.map_or_else(
11176                    || format!("the new {}", incoming.title),
11177                    Resolved::written_name,
11178                ),
11179            )?;
11180        }
11181        match existing {
11182            Some(item) if content_kind == ContentKind::Issue => {
11183                if item.labels != incoming.labels {
11184                    return Err(SourceError::Refused {
11185                        message: "GitHub issue labels differ from the labels being written".into(),
11186                    });
11187                }
11188            }
11189            _ => {
11190                if !incoming.labels.is_empty() {
11191                    return Err(SourceError::Refused {
11192                        message: "GitHub items created by this destination carry no labels".into(),
11193                    });
11194                }
11195            }
11196        }
11197
11198        // The repository the issue really lives in is what the slot below is written against,
11199        // so a single entry that is where the issue is created travels as no key at all, and
11200        // the read side derives it back from the issue.
11201        let own_repository = match &destination {
11202            WriteDestination::Existing(item) => item.own_repository.clone(),
11203            WriteDestination::New(target) => Some(
11204                Repository::try_from(target.origin())
11205                    .map_err(|message| SourceError::Config { message })?,
11206            ),
11207        };
11208        let (native, fallback) = self
11209            .partition_edges(
11210                incoming.written.kind(),
11211                content_kind,
11212                existing.and_then(|item| item.blocked_by.as_deref()),
11213                depends_on,
11214            )
11215            .await?;
11216        let mut slot = slot_metadata(incoming, own_repository.as_ref(), &fallback);
11217        let content = match incoming.assets {
11218            Some(assets) => {
11219                let uploads = self.upload_assets(own_repository.as_ref(), assets).await?;
11220                let rewritten = onetaskgraph_plugin_api::serve_asset_references(
11221                    incoming.content.unwrap_or_default(),
11222                    &mut slot,
11223                    &uploads,
11224                );
11225                incoming.content.map(|_| rewritten)
11226            }
11227            None => incoming.content.map(str::to_owned),
11228        };
11229        // A write over an existing item keeps its `## Links` section, re-rendered from the
11230        // links it holds.
11231        let content = content.map(|content| {
11232            onetaskgraph_plugin_api::relinked(
11233                &content,
11234                existing.and_then(|item| item.body.as_deref()),
11235                incoming.metadata,
11236            )
11237        });
11238        let marked = content.as_deref().map(|content| self.marked(content));
11239        let body = compose_body(marked.as_deref(), &slot)?;
11240        // Read before anything is created, for the reason the field below is: a value
11241        // this destination cannot store has to refuse, and refusing after `createIssue`
11242        // would leave an issue behind that nothing asked for. The engine writes a
11243        // qualified id here; a caller handing this key anything else is told so rather
11244        // than having it silently stored as no origin at all.
11245        // llmlint: ignore[boundary_inputs_validated, changed_behavior_has_e2e] The qualified id's syntax is the engine's and not this plugin's to police: `GlobalId` is deliberately absent from the contract crate because a plugin never sees a qualified id (AGENTS.md), no plugin crate may depend on the engine to parse one, and `docs/metadata.md` says the contents of this key are what no plugin constructs or interprets. What this boundary owns is whether the value is a string its text field can hold, and that is what it checks.
11246        let origin = match incoming.metadata.get(ORIGIN_KEY) {
11247            None => "",
11248            Some(Value::String(origin)) => origin.as_str(),
11249            Some(other) => {
11250                return Err(SourceError::Refused {
11251                    message: format!(
11252                        "{ORIGIN_KEY} holds a qualified id spelled as a string, and this item's \
11253                         is {other}"
11254                    ),
11255                });
11256            }
11257        };
11258        // Resolved before anything is created: a board that cannot carry the copy origin
11259        // has to refuse the write, and refusing it after `createIssue` would leave an
11260        // issue behind that nothing asked for.
11261        let origin_field = match Board::field(&board.fields, ORIGIN_FIELD)? {
11262            Some(field) => {
11263                if required_str(field, "__typename")? != "ProjectV2Field" {
11264                    return Err(SourceError::Refused {
11265                        message: format!(
11266                            "GitHub board source-owned {ORIGIN_FIELD} field is not a text field"
11267                        ),
11268                    });
11269                }
11270                Some(required_str(field, "id")?.to_owned())
11271            }
11272            None if incoming.metadata.contains_key(ORIGIN_KEY) => {
11273                return Err(SourceError::Refused {
11274                    message: format!(
11275                        "GitHub board has no source-owned {ORIGIN_FIELD} text field, and the \
11276                         item carries {ORIGIN_KEY}; add a text field named {ORIGIN_FIELD} to \
11277                         the board"
11278                    ),
11279                });
11280            }
11281            None => None,
11282        };
11283
11284        Ok(Prepared {
11285            origin: origin.to_owned(),
11286            destination,
11287            board,
11288            status_target,
11289            column,
11290            priority_write,
11291            projections,
11292            projected,
11293            content_kind,
11294            own_repository,
11295            native,
11296            slot,
11297            content,
11298            body,
11299            origin_field,
11300        })
11301    }
11302
11303    /// Everything one write does once the item it writes exists: its board fields, its
11304    /// relationships and — for an item that was already there — its content last, then what this
11305    /// process remembers of it.
11306    ///
11307    /// While this source is holding writes back — see [`TaskSource::begin_deferred_writes`] — an
11308    /// item this command created has its fields, its closing and its edges held for
11309    /// [`TaskSource::finish_writes`] rather than sent here.
11310    async fn complete_write(
11311        &self,
11312        incoming: &Incoming<'_>,
11313        prepared: Prepared,
11314        landed: Landed,
11315    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
11316        let Prepared {
11317            destination,
11318            board,
11319            status_target,
11320            column,
11321            priority_write,
11322            projections,
11323            projected,
11324            content_kind,
11325            own_repository,
11326            native,
11327            slot,
11328            content,
11329            body,
11330            origin,
11331            origin_field,
11332        } = prepared;
11333        let existing = destination.existing();
11334        let origin = origin.as_str();
11335        let Landed {
11336            content_id,
11337            item_id,
11338            url,
11339            number,
11340        } = landed;
11341
11342        // Only what differs from the item as this write read it is sent: a priority the item
11343        // already holds is not, so an unchanged re-copy writes no field and a person's edit of
11344        // it since that read is left alone.
11345        let priority_write = priority_write.filter(|_| {
11346            !existing.is_some_and(|item| {
11347                incoming.priority.map(HeldPriority::Read) == Some(item.priority.clone())
11348            })
11349        });
11350        let written_option = column.as_ref().map(|(_, _, name)| name.clone());
11351        let column = column
11352            .filter(|(_, _, name)| existing.is_none_or(|item| item.option.as_ref() != Some(name)))
11353            .map(|(field, option, _)| (field, option));
11354        // Creating an item here is several calls — `createIssue`, which files it on the
11355        // board, then its board fields, the parent and the dependencies — and GitHub can fail
11356        // at any of them. Everything this source can refuse *before* the first of those is
11357        // already checked above, so what is left is GitHub itself failing part way. When it
11358        // does over an item this call created, the issue is taken back: a write that
11359        // refused must not leave an item behind that nobody asked for, and one that does
11360        // makes the retry create a second.
11361        // Whether the board-field write carrying a moved origin was answered as landing whole.
11362        // When it was refused, GitHub does not say which of its fields ran before the one that
11363        // failed, so the origin may or may not have moved.
11364        let mut origin_landed = false;
11365        // An item this command created while writes are held back has every part that can land
11366        // later held for `finish_writes` — its own create filed it on the board and under its
11367        // project already — and so does a later write of it in the same command.
11368        let holding = (existing.is_none() && self.deferring()?) || self.holds_back(&content_id)?;
11369        let landed = if holding {
11370            self.hold_back(
11371                &board.id,
11372                &content_id,
11373                existing,
11374                origin_field.as_deref(),
11375                origin,
11376                column,
11377                status_target.as_ref(),
11378                priority_write.as_ref(),
11379                &projections,
11380                &native,
11381            )
11382        } else if let Some(item_id) = item_id.as_deref() {
11383            self.finish_write(
11384                board.id.as_str(),
11385                incoming,
11386                &content_id,
11387                item_id,
11388                content_kind,
11389                existing,
11390                origin_field.as_deref(),
11391                origin,
11392                column,
11393                status_target.as_ref(),
11394                priority_write.as_ref(),
11395                &projections,
11396                &native,
11397                &mut origin_landed,
11398            )
11399            .await
11400        } else {
11401            // An issue a create filed on the board itself has no board item this process
11402            // knows until `finish_writes` reads it, so nothing but a held-back write may land
11403            // on it before then.
11404            Err(SourceError::Malformed {
11405                message: format!(
11406                    "issue {} was written before the board item GitHub filed it as was read",
11407                    content_id.0
11408                ),
11409            })
11410        };
11411        // An existing item's title, body and state go last, in one `updateIssue`, once its board
11412        // fields and its relationships have landed: a refusal of any of those then leaves its
11413        // body — and the metadata slot inside it — exactly as it stood.
11414        let landed = match (landed, existing) {
11415            (Ok(()), Some(item)) => {
11416                self.update_existing(item, incoming, &body, status_target.as_ref())
11417                    .await
11418            }
11419            (landed, _) => landed,
11420        };
11421        if let Err(error) = landed {
11422            match existing {
11423                // Best effort, and the write's own failure is what the caller is told: a
11424                // refusal naming the tidy-up would hide why the write failed at all.
11425                None => {
11426                    let _ = self.delete_issue(&content_id).await;
11427                }
11428                // The origin field is the one piece of an existing item's metadata written
11429                // before its body, so a write refused after it puts it back as it was. When
11430                // that is refused too, the write's own failure is still what the caller is
11431                // told — with what it left behind added, because the item's metadata is then
11432                // not as it stood and a caller retrying has to know which key moved.
11433                Some(item) => {
11434                    let before = item.origin.as_deref().unwrap_or("");
11435                    if let Some(field) = origin_field.as_deref()
11436                        && before != origin
11437                        && let Err(restore) = self
11438                            .set_item_field(
11439                                board.id.as_str(),
11440                                &item.item_id,
11441                                field,
11442                                json!({"text": before}),
11443                            )
11444                            .await
11445                    {
11446                        let left = if origin_landed {
11447                            format!(
11448                                "its {ORIGIN_KEY} was moved to {origin:?} before that and could \
11449                                 not be put back to {before:?} ({restore}), so item {} still \
11450                                 holds {origin:?} there",
11451                                item.id.0
11452                            )
11453                        } else {
11454                            format!(
11455                                "the refused write carried its {ORIGIN_KEY} from {before:?} to \
11456                                 {origin:?}, GitHub does not say whether that part of it ran, \
11457                                 and putting it back to {before:?} was refused ({restore}), so \
11458                                 item {} holds {origin:?} or {before:?} there",
11459                                item.id.0
11460                            )
11461                        };
11462                        return Err(noting(
11463                            error,
11464                            &format!(
11465                                "; {left}; next: set {ORIGIN_KEY} on it back to {before:?}, or \
11466                                 run the write again"
11467                            ),
11468                        ));
11469                    }
11470                }
11471            }
11472            return Err(error);
11473        }
11474
11475        let written_status = match (incoming.written.work_status(), status_target.as_ref()) {
11476            (Some((kind, _)), Some(StatusTarget::Terminal(_, reason))) => {
11477                self.statuses
11478                    .status(kind, written_option.as_deref(), true, Some(reason.reason()))
11479            }
11480            (Some((kind, _)), Some(StatusTarget::Column(_))) => {
11481                self.statuses
11482                    .status(kind, written_option.as_deref(), false, None)
11483            }
11484            (Some((_, status)), _) => status.clone(),
11485            (None, _) => Status {
11486                category: StatusCategory::Unknown,
11487                name: "Open".to_owned(),
11488            },
11489        };
11490
11491        // So the rest of this command reads what it just did rather than what the board
11492        // said before it. See `remember_written` for which half takes it.
11493        let remembered = Resolved {
11494            // Empty for an issue whose board item is not read yet: `finish_writes` reads it
11495            // and `learn_item` puts it here.
11496            // llmlint: ignore[invalid_states_unrepresentable] `Resolved` is serialised into the cache's stored write context, so its field type is a stored shape this change may not move; the empty id lives only until `finish_writes` reads the board item in this same command, and nothing addresses it before then — `complete_write` refuses any write naming no board item.
11497            item_id: item_id.unwrap_or_default(),
11498            id: content_id.clone(),
11499            content_kind,
11500            kind: incoming.written.kind(),
11501            title: incoming.title.to_owned(),
11502            // The visible half of the body this write composed, split back off it the
11503            // way a read splits it — so what this record reports is what a read of the
11504            // same issue reports, rather than the person's text with the metadata slot
11505            // still on the end of it.
11506            body: self.visible(body.clone())?.0,
11507            raw_body: body.clone(),
11508            // A document has no status of its own; what it reads back as is whatever
11509            // the issue's own state says, which is what a re-read reports.
11510            status: written_status,
11511            option: written_option.or_else(|| existing.and_then(|item| item.option.clone())),
11512            priority: match incoming.priority {
11513                Some(priority) => HeldPriority::Read(priority),
11514                None => existing.map_or(HeldPriority::Read(Priority::None), |item| {
11515                    item.priority.clone()
11516                }),
11517            },
11518            // What `state_input` asked for: closed for a terminal target, open for any other
11519            // status, and the issue's own state left as it was by a document write.
11520            closed: content_kind == ContentKind::Issue
11521                && match status_target.as_ref() {
11522                    Some(StatusTarget::Terminal(_, _)) => true,
11523                    Some(_) => false,
11524                    None => existing.is_some_and(|item| item.closed),
11525                },
11526            reason: match status_target.as_ref() {
11527                Some(StatusTarget::Terminal(_, reason)) if content_kind == ContentKind::Issue => {
11528                    Some(reason.reason().to_owned())
11529                }
11530                Some(_) => None,
11531                None => existing.and_then(|item| item.reason.clone()),
11532            },
11533            delivers: incoming.delivers.to_vec(),
11534            delivered_by: incoming.delivered_by.to_vec(),
11535            labels: incoming.labels.to_vec(),
11536            parent: incoming.parent.cloned(),
11537            issue_parent: None,
11538            origin: (!origin.is_empty()).then(|| origin.to_owned()),
11539            projected,
11540            number,
11541            // In the update path this is the item's own url, read off `existing` where the
11542            // record above was bound, so one expression serves both halves.
11543            url,
11544            created_at: existing.and_then(|item| item.created_at),
11545            updated_at: existing.and_then(|item| item.updated_at),
11546            // What this write moved is GitHub's to say, so a record of it gives no token until
11547            // it is read again.
11548            item_updated_at: None,
11549            comment_count: None,
11550            relationship_events: None,
11551            served_at: None,
11552            facets: None,
11553            own_repository,
11554            repositories: incoming.repositories.to_vec(),
11555            classification: incoming.classification,
11556            slot,
11557            board_id: Some(board.id.as_str().to_owned()),
11558            fields: board
11559                .fields
11560                .get("nodes")
11561                .and_then(Value::as_array)
11562                .cloned()
11563                .unwrap_or_default(),
11564            board_fields: Some(board.fields.clone()),
11565            // What this write left the relationship holding is known by id alone, and a
11566            // later read of its edges needs each far end's kind, so it reads them again.
11567            blocked_by: None,
11568            // The people it named, which its own answer was held to; none named keeps the
11569            // item's, and creates a task of an opted-in source unassigned.
11570            assignees: match incoming.assignees {
11571                Some(people) => Some(people.to_vec()),
11572                None => match existing {
11573                    Some(item) => item.assignees.clone(),
11574                    None => (self.assignees
11575                        && matches!(incoming.written, Written::Work(ItemKind::Task, _)))
11576                    .then(Vec::new),
11577                },
11578            },
11579        };
11580        self.remember_written(remembered, existing.is_none())?;
11581        Ok(onetaskgraph_plugin_api::AssetsWritten {
11582            id: content_id,
11583            content,
11584        })
11585    }
11586
11587    /// Everything a write does after the item exists: its board fields, its parent, and
11588    /// its dependencies.
11589    ///
11590    /// Split out of `write_item` so there is one place a failure past the point of no
11591    /// return is caught, rather than a tidy-up repeated at each `?` above.
11592    // llmlint: ignore[suppressions_justified] This is the tail of `write_item` lifted out
11593    // so there is one place a failure past the point of no return is caught, and its
11594    // arguments are exactly the values that tail already had in scope. Bundling them into a
11595    // struct would describe no concept — it would be "the arguments of this function" — and
11596    // would put the whole of `write_item`'s locals behind one more indirection.
11597    #[allow(clippy::too_many_arguments)]
11598    async fn finish_write(
11599        &self,
11600        board_id: &str,
11601        incoming: &Incoming<'_>,
11602        content_id: &NativeId,
11603        item_id: &str,
11604        content_kind: ContentKind,
11605        existing: Option<&Resolved>,
11606        origin_field: Option<&str>,
11607        origin: &str,
11608        column: Option<(String, String)>,
11609        status_target: Option<&StatusTarget>,
11610        priority: Option<&PriorityWrite>,
11611        projections: &[ProjectionWrite],
11612        native: &[String],
11613        origin_landed: &mut bool,
11614    ) -> Result<(), SourceError> {
11615        let (fields, clears) = field_writes(
11616            existing,
11617            origin_field,
11618            origin,
11619            column,
11620            priority,
11621            projections,
11622        );
11623        self.set_item_fields(board_id, item_id, &fields, &clears)
11624            .await?;
11625        *origin_landed = true;
11626
11627        // An existing issue closes in the `updateIssue` its write ends with; one created just
11628        // now closes here, once its option is selected.
11629        if existing.is_none()
11630            && content_kind == ContentKind::Issue
11631            && matches!(status_target, Some(StatusTarget::Terminal(_, _)))
11632        {
11633            self.update_content(
11634                ContentKind::Issue,
11635                content_id,
11636                json!({"stateInput":state_input(status_target)}),
11637            )
11638            .await?;
11639        }
11640
11641        if content_kind == ContentKind::Issue {
11642            self.reparent(
11643                existing.and_then(|item| item.parent.clone()),
11644                content_id,
11645                incoming.parent,
11646            )
11647            .await?;
11648            // A document takes part in no dependency graph, so writing one neither reads
11649            // nor changes the issue's own `blockedBy` relationships. Reconciling them
11650            // against the empty list a document write carries would *delete* whatever
11651            // relationships a person had made on that issue, which is a write nobody
11652            // asked for.
11653            if incoming.written.kind() != BoardKind::Document {
11654                let issue = match existing {
11655                    Some(item) => Issue::Existing(item.blocked_by.as_deref()),
11656                    None => Issue::Created,
11657                };
11658                self.reconcile_blocked_by(content_id, native, issue).await?;
11659            }
11660        }
11661        Ok(())
11662    }
11663
11664    /// Whether this source is holding writes back — see [`TaskSource::begin_deferred_writes`].
11665    fn deferring(&self) -> Result<bool, SourceError> {
11666        Ok(self.deferred()?.is_some())
11667    }
11668
11669    /// Whether `content` is an item this command created whose parts are held back.
11670    fn holds_back(&self, content: &NativeId) -> Result<bool, SourceError> {
11671        Ok(self
11672            .deferred()?
11673            .as_ref()
11674            .is_some_and(|deferred| deferred.holds(content)))
11675    }
11676
11677    fn deferred(&self) -> Result<std::sync::MutexGuard<'_, Option<Deferred>>, SourceError> {
11678        self.deferred.lock().map_err(|_| SourceError::Unavailable {
11679            message: "this source's record of the writes it is holding back was left \
11680                      inconsistent by an earlier failure; next: run the command again"
11681                .into(),
11682        })
11683    }
11684
11685    /// Creates one issue filed on the board and under its project by the `createIssue` itself —
11686    /// `projectV2Ids` naming the board and `parentIssueId` the project — which is what a copy
11687    /// creates with: one request where adding it to the board and filing it under its project
11688    /// were two more. GitHub adds the board item after answering, so its id is not known here;
11689    /// [`TaskSource::finish_writes`] reads it.
11690    async fn create_filed_issue(
11691        &self,
11692        board_id: &str,
11693        repository: &RepositoryTarget,
11694        incoming: &Incoming<'_>,
11695        body: &Option<String>,
11696    ) -> Result<Landed, SourceError> {
11697        let repository_id = self.repository_id(repository, incoming).await?;
11698        let mut input = filed_input(&repository_id, board_id, incoming, body);
11699        self.assigning(&mut input, incoming)?;
11700        let data = match self
11701            .graphql(graphql::CREATE_ISSUE, json!({"input": &input}))
11702            .await
11703        {
11704            Ok(data) => data,
11705            Err(error) => return Err(self.refusing_people(&input, error)),
11706        };
11707        let created = data
11708            .pointer("/createIssue/issue")
11709            .filter(|value| !value.is_null())
11710            .ok_or_else(|| SourceError::Malformed {
11711                message: "GitHub issue creation returned no issue".into(),
11712            })?;
11713        let landed = self.created_landed(created).await?;
11714        // An issue GitHub created assigned otherwise than asked is refused and taken back; a
11715        // delete GitHub refuses too is answered beside the refusal, naming the issue left.
11716        if let Err(error) = self.assigned_as_asked(&input, Some(created)) {
11717            return Err(self.taken_back(&landed.content_id, created, error).await);
11718        }
11719        Ok(landed)
11720    }
11721
11722    /// Keep the address `createIssue` answered for the issue `content`, for
11723    /// [`TaskSource::written_location`].
11724    fn note_written(&self, content: &NativeId, url: Option<&str>) {
11725        if let Some(url) = url {
11726            self.written
11727                .lock()
11728                .unwrap_or_else(std::sync::PoisonError::into_inner)
11729                .insert(content.clone(), url.to_owned());
11730        }
11731    }
11732
11733    /// What one `createIssue` answered, as the item it created — or, when its number cannot be
11734    /// read, the refusal, after taking the issue back.
11735    async fn created_landed(&self, created: &Value) -> Result<Landed, SourceError> {
11736        let content_id = NativeId(required_nonblank_str(created, "id")?.to_owned());
11737        let url = optional_str(created, "url")?.map(str::to_owned);
11738        let number = match created_issue_number(created) {
11739            Ok(number) => number,
11740            Err(error) => {
11741                let _ = self.delete_issue(&content_id).await;
11742                return Err(error);
11743            }
11744        };
11745        self.note_written(&content_id, url.as_deref());
11746        Ok(Landed {
11747            content_id,
11748            item_id: None,
11749            url,
11750            number,
11751        })
11752    }
11753
11754    /// Hold back everything a write of the created item `content` would send after creating it,
11755    /// for [`TaskSource::finish_writes`]: the same field values, closing and edges
11756    /// `finish_write` sends, the parent excepted, which its create already named. A later write
11757    /// of the same item replaces what it changes.
11758    // llmlint: ignore[suppressions_justified] The arguments are `finish_write`'s, which this holds back instead of sending, and they are exactly the values `complete_write` has in scope; bundling them would describe no concept.
11759    #[allow(clippy::too_many_arguments)]
11760    fn hold_back(
11761        &self,
11762        board_id: &BoardId,
11763        content: &NativeId,
11764        existing: Option<&Resolved>,
11765        origin_field: Option<&str>,
11766        origin: &str,
11767        column: Option<(String, String)>,
11768        status_target: Option<&StatusTarget>,
11769        priority: Option<&PriorityWrite>,
11770        projections: &[ProjectionWrite],
11771        native: &[String],
11772    ) -> Result<(), SourceError> {
11773        let status = column.map(|(field, option)| {
11774            let name = self
11775                .fields_cache()
11776                .ok()
11777                .and_then(|fields| {
11778                    fields.as_ref().and_then(|board| {
11779                        option_name(&board.fields, &field, &option).map(str::to_owned)
11780                    })
11781                })
11782                .unwrap_or_default();
11783            (field, option, name)
11784        });
11785        let (fields, clears) =
11786            field_writes(existing, origin_field, origin, None, priority, projections);
11787        let close = match status_target {
11788            Some(StatusTarget::Terminal(_, reason)) => Some(*reason),
11789            _ => None,
11790        };
11791        let mut deferred = self.deferred()?;
11792        let deferred = deferred.get_or_insert_with(Deferred::default);
11793        if let Deferred::Nothing = deferred {
11794            *deferred = Deferred::Held {
11795                board: board_id.clone(),
11796                created: Vec::new(),
11797            };
11798        }
11799        let Deferred::Held { created, .. } = deferred else {
11800            unreachable!("held back on the line above");
11801        };
11802        let held = match created.iter().position(|held| held.content == *content) {
11803            Some(at) => &mut created[at],
11804            None => {
11805                created.push(HeldBack {
11806                    content: content.clone(),
11807                    fields: Vec::new(),
11808                    status: None,
11809                    clears: Vec::new(),
11810                    close: None,
11811                    edges: Vec::new(),
11812                });
11813                created.last_mut().expect("just held")
11814            }
11815        };
11816        for (field, value) in fields {
11817            held.fields.retain(|(held, _)| *held != field);
11818            held.clears.retain(|held| *held != field);
11819            held.fields.push((field, value));
11820        }
11821        for field in clears {
11822            held.fields.retain(|(held, _)| held != field);
11823            if !held.clears.iter().any(|held| held == field) {
11824                held.clears.push(field.to_owned());
11825            }
11826        }
11827        if status.is_some() {
11828            held.status = status;
11829        }
11830        if close.is_some() {
11831            held.close = close;
11832        }
11833        // Nothing of an item created in this command has been sent but its create, so the edges
11834        // it is to have are exactly the ones its latest write names.
11835        held.edges = native.iter().map(|far| NativeId(far.clone())).collect();
11836        Ok(())
11837    }
11838
11839    /// Create every task of `writes`, together, filed on the board and under each one's
11840    /// project: [`graphql::CREATE_ISSUES`], [`MUTATION_BATCH`] to a request.
11841    ///
11842    /// Each is prepared as [`Self::write_item`] prepares one — every refusal a write owes made
11843    /// before the first request — then created, then completed with its parts held back. A
11844    /// request refused part way leaves the issues it did create, which are taken back, with the
11845    /// rest of this call's, before the refusal is answered.
11846    async fn create_together(
11847        &self,
11848        writes: &[ItemWrite<Task>],
11849    ) -> Result<Vec<NativeId>, SourceError> {
11850        let incomings: Vec<Incoming<'_>> = writes
11851            .iter()
11852            .map(|write| self.task_incoming(write, None))
11853            .collect::<Result<_, _>>()?;
11854        // Every person these creates assign, looked up together rather than one write at a time.
11855        let people: Vec<String> = writes
11856            .iter()
11857            .filter_map(|write| write.item.assignees.clone())
11858            .flatten()
11859            .collect();
11860        self.resolve_people(&people).await?;
11861        let mut prepared = Vec::with_capacity(writes.len());
11862        for (incoming, write) in incomings.iter().zip(writes) {
11863            if write.target.is_some() {
11864                return Err(SourceError::Malformed {
11865                    message: "a write naming its target was handed to a batch of creates".into(),
11866                });
11867            }
11868            prepared.push(
11869                self.prepare_write(incoming, None, &write.depends_on)
11870                    .await?,
11871            );
11872        }
11873        let mut inputs = Vec::with_capacity(prepared.len());
11874        for (incoming, prepared) in incomings.iter().zip(&prepared) {
11875            let WriteDestination::New(target) = &prepared.destination else {
11876                return Err(SourceError::Malformed {
11877                    message: "an update was decided for a write handed to a batch of creates"
11878                        .into(),
11879                });
11880            };
11881            let repository_id = self.repository_id(target, incoming).await?;
11882            let mut input = filed_input(
11883                &repository_id,
11884                prepared.board.id.as_str(),
11885                incoming,
11886                &prepared.body,
11887            );
11888            self.assigning(&mut input, incoming)?;
11889            inputs.push(input);
11890        }
11891        let mut landed: Vec<Landed> = Vec::with_capacity(inputs.len());
11892        let refused = 'create: {
11893            for chunk in inputs.chunks(MUTATION_BATCH) {
11894                let mut variables = serde_json::Map::new();
11895                for slot in 0..MUTATION_BATCH {
11896                    variables.insert(
11897                        format!("create{slot}"),
11898                        chunk.get(slot).cloned().unwrap_or_else(|| chunk[0].clone()),
11899                    );
11900                    variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
11901                }
11902                let data = match self
11903                    .graphql(graphql::CREATE_ISSUES, Value::Object(variables))
11904                    .await
11905                {
11906                    Ok(data) => data,
11907                    Err(error) => break 'create Some(error),
11908                };
11909                let mut refusal = data.get(ANSWER_ERRORS).map(|errors| {
11910                    let said: Vec<&str> = errors
11911                        .as_array()
11912                        .into_iter()
11913                        .flatten()
11914                        .filter_map(|error| error.get("message").and_then(Value::as_str))
11915                        .collect();
11916                    SourceError::Refused {
11917                        message: if said.is_empty() {
11918                            "GitHub returned GraphQL errors".to_owned()
11919                        } else {
11920                            said.join("; ")
11921                        },
11922                    }
11923                });
11924                for (slot, input) in chunk.iter().enumerate() {
11925                    match data
11926                        .pointer(&format!("/create{slot}/issue"))
11927                        .filter(|value| !value.is_null())
11928                    {
11929                        Some(created) => match self.created_landed(created).await {
11930                            Ok(landed_one) => {
11931                                landed.push(landed_one);
11932                                // Taken back with the rest, as any refusal here is.
11933                                if let Err(error) = self.assigned_as_asked(input, Some(created)) {
11934                                    refusal.get_or_insert(error);
11935                                }
11936                            }
11937                            Err(error) => {
11938                                refusal.get_or_insert(error);
11939                            }
11940                        },
11941                        // An alias GitHub refused answers nothing, and the refusal says why.
11942                        None => {
11943                            refusal.get_or_insert(SourceError::Malformed {
11944                                message: "GitHub issue creation returned no issue".into(),
11945                            });
11946                        }
11947                    }
11948                }
11949                if let Some(error) = refusal {
11950                    break 'create Some(error);
11951                }
11952            }
11953            None
11954        };
11955        if let Some(error) = refused {
11956            // None of these ids reaches the caller, so an issue GitHub will not take back is
11957            // named here or by nobody.
11958            let ids: Vec<&NativeId> = landed.iter().map(|created| &created.content_id).collect();
11959            let left = self.delete_issues(&ids).await;
11960            let left: Vec<&str> = left.iter().map(|id| id.0.as_str()).collect();
11961            return Err(left_behind(error, &left));
11962        }
11963        let created: Vec<NativeId> = landed
11964            .iter()
11965            .map(|landed| landed.content_id.clone())
11966            .collect();
11967        let mut ids = Vec::with_capacity(landed.len());
11968        for ((incoming, prepared), landed) in incomings.iter().zip(prepared).zip(landed) {
11969            match self.complete_write(incoming, prepared, landed).await {
11970                Ok(written) => ids.push(written.id),
11971                // llmlint: ignore[changed_behavior_has_e2e] While writes are held back, which is the only time a batch is created, completing a created item only holds its parts back, and that fails on nothing but a poisoned lock, which no journey can cause; the issues are taken back regardless, because the caller is never handed their ids.
11972                Err(error) => {
11973                    let ids: Vec<&NativeId> = created.iter().collect();
11974                    let left = self.delete_issues(&ids).await;
11975                    let left: Vec<&str> = left.iter().map(|id| id.0.as_str()).collect();
11976                    return Err(left_behind(error, &left));
11977                }
11978            }
11979        }
11980        Ok(ids)
11981    }
11982
11983    /// Hold back the update of the existing issue `issue` — `members`, what its own
11984    /// [`graphql::UPDATE_ISSUE`] would send beside its id — while writes are being held back — so the updates a copy makes one after
11985    /// another go to GitHub as one request. Whatever this source held of the issue is dropped
11986    /// as the mutation itself would drop it. Answers whether it was held: never while a write
11987    /// the store's cache expects runs, which records each mutation's own answer, and never for
11988    /// an issue an update is already held for, which that one is sent ahead of.
11989    fn hold_update(&self, issue: &NativeId, members: &Value) -> Result<bool, SourceError> {
11990        if self.expected.journaling() || self.deferred()?.is_none() {
11991            return Ok(false);
11992        }
11993        let mut held = self
11994            .held_updates
11995            .lock()
11996            .map_err(|_| SourceError::Unavailable {
11997                message: "issue updates held back were left inconsistent; run the command again"
11998                    .into(),
11999            })?;
12000        if held.iter().any(|earlier| earlier.issue == *issue) {
12001            return Ok(false);
12002        }
12003        let named = |value: &str| issue.0 == value;
12004        self.resolved_cache()?
12005            .retain(|id, item| !named(&id.0) && !named(&item.item_id));
12006        self.read_ahead()?.retain(|id, item| {
12007            !named(&id.0) && !item.as_ref().is_some_and(|item| named(&item.item_id))
12008        });
12009        self.carried()?
12010            .retain(|id, item| !named(&id.0) && !named(&item.item_id));
12011        held.push(HeldUpdate::new(issue, members));
12012        Ok(true)
12013    }
12014
12015    /// Send every update [`Self::hold_update`] held back: one alone as [`graphql::UPDATE_ISSUE`]
12016    /// sends it, several as aliased `updateIssue`s of [`graphql::UPDATE_ISSUES`],
12017    /// [`MUTATION_BATCH`] to a request. Each counts one write, as it would alone.
12018    async fn send_held_updates(&self) -> Result<(), SourceError> {
12019        let held = std::mem::take(&mut *self.held_updates.lock().map_err(|_| {
12020            SourceError::Unavailable {
12021                message: "issue updates held back were left inconsistent; run the command again"
12022                    .into(),
12023            }
12024        })?);
12025        if let [one] = held.as_slice() {
12026            return self
12027                .send_update(
12028                    graphql::UPDATE_ISSUE,
12029                    "/updateIssue/issue",
12030                    &one.issue,
12031                    one.input.clone(),
12032                )
12033                .await;
12034        }
12035        for chunk in held.chunks(MUTATION_BATCH) {
12036            let mut variables = serde_json::Map::new();
12037            for slot in 0..MUTATION_BATCH {
12038                variables.insert(
12039                    format!("update{slot}"),
12040                    chunk.get(slot).unwrap_or(&chunk[0]).input.clone(),
12041                );
12042                variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12043            }
12044            let data = match self
12045                .graphql(graphql::UPDATE_ISSUES, Value::Object(variables))
12046                .await
12047            {
12048                Ok(data) => data,
12049                Err(error) => {
12050                    for held in chunk {
12051                        self.forget_people(&held.input);
12052                    }
12053                    return Err(error);
12054                }
12055            };
12056            let inputs: Vec<&Value> = chunk.iter().map(|held| &held.input).collect();
12057            check_aliased_answers(
12058                graphql::UPDATE_ISSUES,
12059                &data,
12060                "update",
12061                &inputs,
12062                &[("issue", "id")],
12063            )?;
12064            for (slot, held) in chunk.iter().enumerate() {
12065                self.assigned_as_asked(&held.input, data.pointer(&format!("/update{slot}/issue")))?;
12066            }
12067        }
12068        Ok(())
12069    }
12070
12071    /// Send everything held back since [`TaskSource::begin_deferred_writes`]: one read of the
12072    /// created items' board items, then their field values and edges together in requests of
12073    /// [`WRITE_BATCH`], then their closes in requests of [`MUTATION_BATCH`]. Anything refused
12074    /// takes back every issue held, [`DELETE_BATCH`] to a request, and answers the refusal.
12075    async fn send_held_back(&self) -> Result<(), SourceError> {
12076        let Some(Deferred::Held { board, created }) = self.deferred()?.take() else {
12077            return Ok(());
12078        };
12079        if created.is_empty() {
12080            return Ok(());
12081        }
12082        let sent = self.send_deferred(board.as_str(), &created).await;
12083        if let Err(error) = sent {
12084            // Best effort, and the failure is what the caller is told, as a write of one item
12085            // that fails part way takes back what it created: the copy that held these back
12086            // journalled every one, so one this cannot take back its undo tries again, and says
12087            // so when it cannot either.
12088            let ids: Vec<&NativeId> = created.iter().map(|held| &held.content).collect();
12089            let _ = self.delete_issues(&ids).await;
12090            return Err(error);
12091        }
12092        Ok(())
12093    }
12094
12095    /// The requests [`Self::send_held_back`] makes.
12096    async fn send_deferred(&self, board: &str, created: &[HeldBack]) -> Result<(), SourceError> {
12097        let items = self.created_board_items(board, created).await?;
12098        let mut fields: Vec<Value> = Vec::new();
12099        let mut closes: Vec<Value> = Vec::new();
12100        let mut edges: Vec<Value> = Vec::new();
12101        for held in created {
12102            let (item, status) = &items[&held.content];
12103            let mut values = held.fields.clone();
12104            // A status the board already shows — set by a workflow a person turned on to file
12105            // new items at it — is not written again.
12106            if let Some((field, option, name)) = &held.status
12107                && status.as_deref() != Some(name.as_str())
12108            {
12109                values.insert(0, (field.clone(), json!({"singleSelectOptionId": option})));
12110            }
12111            for (field, value) in values {
12112                fields.push(json!({"projectId":board,"itemId":item,"fieldId":field,"value":value}));
12113            }
12114            if let Some(reason) = held.close {
12115                closes.push(json!({"id": held.content.0, "stateInput": closed_input(reason)}));
12116            }
12117            for far in &held.edges {
12118                edges.push(json!({"issueId": held.content.0, "blockingIssueId": far.0}));
12119            }
12120            if !held.clears.is_empty() {
12121                let clears: Vec<&str> = held.clears.iter().map(String::as_str).collect();
12122                self.set_item_fields(board, item, &[], &clears).await?;
12123            }
12124        }
12125        // Each alias answers with what it wrote, which is what its input named: the board item a
12126        // field value is set on, the issue closed, the issue blocked and the one blocking it.
12127        let field_answer: &[(&str, &str)] = &[("projectV2Item", "itemId")];
12128        let close_answer: &[(&str, &str)] = &[("issue", "id")];
12129        let block_answer: &[(&str, &str)] =
12130            &[("issue", "issueId"), ("blockingIssue", "blockingIssueId")];
12131        // Every field value, then every edge, as one ordered list sent `WRITE_BATCH` aliases to a
12132        // request: a request holding both kinds is the one document carrying both, so a plan's
12133        // values and edges cost one request where they fit in one.
12134        let writes: Vec<HeldWrite<'_>> = fields
12135            .iter()
12136            .map(HeldWrite::Field)
12137            .chain(edges.iter().map(HeldWrite::Edge))
12138            .collect();
12139        for chunk in writes.chunks(WRITE_BATCH) {
12140            let values: Vec<&Value> = chunk
12141                .iter()
12142                .filter_map(|write| match write {
12143                    HeldWrite::Field(input) => Some(*input),
12144                    HeldWrite::Edge(_) => None,
12145                })
12146                .collect();
12147            let blocks: Vec<&Value> = chunk
12148                .iter()
12149                .filter_map(|write| match write {
12150                    HeldWrite::Edge(input) => Some(*input),
12151                    HeldWrite::Field(_) => None,
12152                })
12153                .collect();
12154            let (document, sends) = match (values.is_empty(), blocks.is_empty()) {
12155                (false, false) => (graphql::WRITE_FIELDS_AND_EDGES, ["sendField", "sendBlock"]),
12156                (false, true) => (graphql::WRITE_FIELD_VALUES, ["send", "send"]),
12157                _ => (graphql::ADD_BLOCKED_BYS, ["send", "send"]),
12158            };
12159            let mut variables = serde_json::Map::new();
12160            let kinds = [
12161                ("field", &values, sends[0], field_answer),
12162                ("block", &blocks, sends[1], block_answer),
12163            ];
12164            for (prefix, inputs, send, _) in &kinds {
12165                if inputs.is_empty() {
12166                    continue;
12167                }
12168                for slot in 0..WRITE_BATCH {
12169                    variables.insert(
12170                        format!("{prefix}{slot}"),
12171                        (*inputs.get(slot).unwrap_or(&inputs[0])).clone(),
12172                    );
12173                    variables.insert(format!("{send}{slot}"), json!(slot < inputs.len()));
12174                }
12175            }
12176            let data = self.graphql(document, Value::Object(variables)).await?;
12177            for (prefix, inputs, _, answers) in kinds {
12178                check_aliased_answers(document, &data, prefix, inputs, answers)?;
12179            }
12180        }
12181        for chunk in closes.chunks(MUTATION_BATCH) {
12182            let mut variables = serde_json::Map::new();
12183            for slot in 0..MUTATION_BATCH {
12184                variables.insert(
12185                    format!("close{slot}"),
12186                    chunk.get(slot).cloned().unwrap_or_else(|| chunk[0].clone()),
12187                );
12188                variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12189            }
12190            let data = self
12191                .graphql(graphql::CLOSE_ISSUES, Value::Object(variables))
12192                .await?;
12193            let inputs: Vec<&Value> = chunk.iter().collect();
12194            check_aliased_answers(graphql::CLOSE_ISSUES, &data, "close", &inputs, close_answer)?;
12195        }
12196        for held in created {
12197            self.learn_item(&held.content, &items[&held.content].0)?;
12198        }
12199        Ok(())
12200    }
12201
12202    /// The board item each of `created` is on this board, with its `Status` as the board set it:
12203    /// [`graphql::CREATED_BOARD_ITEMS`], read again — after a wait of a second, then two, four,
12204    /// eight and sixteen — for only those GitHub has not filed yet.
12205    ///
12206    /// **Membership is never assumed.** `createIssue`'s `projectV2Ids` files an issue some time
12207    /// after GitHub answered the create — the feasibility spike saw 0.45 to 1.84 seconds, and no
12208    /// create answer carrying the item — so only a read says it is there. One still absent once
12209    /// those reads are spent is filed with [`graphql::ADD_TO_BOARD`], one write each; GitHub
12210    /// filing it meanwhile refuses that "Content already exists in this project", which says it
12211    /// is placed, and one more read finds the item rather than a second one being made.
12212    async fn created_board_items(
12213        &self,
12214        board: &str,
12215        created: &[HeldBack],
12216    ) -> Result<BTreeMap<NativeId, (String, Option<String>)>, SourceError> {
12217        let mut found: BTreeMap<NativeId, (String, Option<String>)> = BTreeMap::new();
12218        let unfiled = |found: &BTreeMap<NativeId, (String, Option<String>)>| -> Vec<NativeId> {
12219            created
12220                .iter()
12221                .map(|held| held.content.clone())
12222                .filter(|id| !found.contains_key(id))
12223                .collect()
12224        };
12225        let mut wait = Duration::from_secs(1);
12226        for attempt in 0..6 {
12227            let absent = unfiled(&found);
12228            if absent.is_empty() {
12229                return Ok(found);
12230            }
12231            if attempt > 0 {
12232                self.clock
12233                    .sleep_because(wait, pacing::cause::BOARD_FILING)
12234                    .await;
12235                wait = wait.saturating_mul(2);
12236            }
12237            self.read_created_items(board, &absent, &mut found).await?;
12238        }
12239        let mut placed_meanwhile = Vec::new();
12240        for id in unfiled(&found) {
12241            match self
12242                .graphql(
12243                    graphql::ADD_TO_BOARD,
12244                    json!({"input":{"projectId":board,"contentId":id.0}}),
12245                )
12246                .await
12247            {
12248                Ok(added) => {
12249                    let item = added
12250                        .pointer("/addProjectV2ItemById/item")
12251                        .filter(|value| !value.is_null())
12252                        .ok_or_else(|| SourceError::Malformed {
12253                            message: "GitHub board addition returned no project item".into(),
12254                        })?;
12255                    found.insert(id, (required_nonblank_str(item, "id")?.to_owned(), None));
12256                }
12257                Err(error) if already_on_the_board(&error) => placed_meanwhile.push(id),
12258                Err(error) => return Err(error),
12259            }
12260        }
12261        if !placed_meanwhile.is_empty() {
12262            self.read_created_items(board, &placed_meanwhile, &mut found)
12263                .await?;
12264        }
12265        let absent = unfiled(&found);
12266        if absent.is_empty() {
12267            return Ok(found);
12268        }
12269        let absent: Vec<&str> = absent.iter().map(|id| id.0.as_str()).collect();
12270        Err(SourceError::Unavailable {
12271            message: format!(
12272                "GitHub created {} filed on board {board} and, after 31 seconds and adding {} \
12273                 to it, still answers {} on no item of it: {}; next: run the copy again once \
12274                 GitHub has caught up",
12275                if absent.len() == 1 {
12276                    "an issue"
12277                } else {
12278                    "issues"
12279                },
12280                if absent.len() == 1 { "it" } else { "them" },
12281                if absent.len() == 1 { "it" } else { "them" },
12282                absent.join(", ")
12283            ),
12284        })
12285    }
12286
12287    /// One [`graphql::CREATED_BOARD_ITEMS`] read of each of `ids`, [`COPY_DETAIL_BATCH`] to a
12288    /// request, adding to `found` the board item of every one GitHub has filed on `board`.
12289    async fn read_created_items(
12290        &self,
12291        board: &str,
12292        ids: &[NativeId],
12293        found: &mut BTreeMap<NativeId, (String, Option<String>)>,
12294    ) -> Result<(), SourceError> {
12295        for chunk in ids.chunks(COPY_DETAIL_BATCH) {
12296            let mut variables = serde_json::Map::new();
12297            for slot in 0..COPY_DETAIL_BATCH {
12298                variables.insert(
12299                    format!("id{slot}"),
12300                    json!(chunk.get(slot).unwrap_or(&chunk[0]).0),
12301                );
12302                variables.insert(format!("read{slot}"), json!(slot < chunk.len()));
12303            }
12304            variables.insert("boardItems".into(), json!(BOARD_ITEMS_PAGE_SIZE));
12305            variables.insert("statusName".into(), json!(STATUS_FIELD));
12306            let data = self
12307                .graphql(graphql::CREATED_BOARD_ITEMS, Value::Object(variables))
12308                .await?;
12309            for (slot, id) in chunk.iter().enumerate() {
12310                // An answer for another issue than the one asked about says nothing of
12311                // where that one is filed, and its board item is not this one's.
12312                let node = data.get(format!("i{slot}")).filter(|node| !node.is_null());
12313                let named = node.map(|node| node.get("id").and_then(Value::as_str));
12314                if let Some(named) = named
12315                    && named != Some(id.0.as_str())
12316                {
12317                    return Err(SourceError::Malformed {
12318                        message: format!(
12319                            "GitHub answered the board items of {} when asked for those of {}",
12320                            named.unwrap_or("an issue it did not name"),
12321                            id.0
12322                        ),
12323                    });
12324                }
12325                // An issue GitHub does not answer yet is not filed yet; one it answers is
12326                // read whole, its connection, each board item's board and its status, and
12327                // any of them unreadable is refused rather than read as not filed.
12328                let Some(node) = node else { continue };
12329                let malformed = |what: &str| SourceError::Malformed {
12330                    message: format!("GitHub answered the board items of {} with {what}", id.0),
12331                };
12332                let nodes = node
12333                    .pointer("/projectItems/nodes")
12334                    .and_then(Value::as_array)
12335                    .ok_or_else(|| malformed("no list of board items"))?;
12336                let mut item = None;
12337                for node in nodes {
12338                    let on = node
12339                        .pointer("/project/id")
12340                        .and_then(Value::as_str)
12341                        .ok_or_else(|| malformed("a board item naming no board"))?;
12342                    if on == board {
12343                        item = Some(node);
12344                    }
12345                }
12346                if let Some(item) = item {
12347                    let status = match item.get("status") {
12348                        None | Some(Value::Null) => None,
12349                        Some(status) => Some(
12350                            status
12351                                .get("name")
12352                                .and_then(Value::as_str)
12353                                .ok_or_else(|| malformed("a status that names no option"))?
12354                                .to_owned(),
12355                        ),
12356                    };
12357                    found.insert(
12358                        id.clone(),
12359                        (required_nonblank_str(item, "id")?.to_owned(), status),
12360                    );
12361                }
12362            }
12363        }
12364        Ok(())
12365    }
12366
12367    /// The board item id of `content`, which this process created and remembered without one,
12368    /// in every half of its own view.
12369    fn learn_item(&self, content: &NativeId, item: &str) -> Result<(), SourceError> {
12370        if let Some(held) = self.resolved_cache()?.get_mut(content) {
12371            held.item_id = item.to_owned();
12372        }
12373        if let Some(held) = self.created()?.iter_mut().find(|held| held.id == *content) {
12374            held.item_id = item.to_owned();
12375        }
12376        Ok(())
12377    }
12378
12379    /// Ask together which items each of `origins` names, and what creating an item reads; see
12380    /// [`TaskSource::read_ahead_origins_for_copy`]. An origin whose answer runs past its first
12381    /// page is left to its own lookup.
12382    async fn origins_ahead(&self, origins: &[String]) -> Result<(), SourceError> {
12383        if self.repository.is_none() {
12384            return Ok(());
12385        }
12386        let unasked: Vec<&String> = {
12387            let held = self.narrowed_cache()?;
12388            let mut unasked: Vec<&String> = Vec::new();
12389            for origin in origins {
12390                if !held.contains_key(&Narrowing::Origin(origin.clone()).key())
12391                    && !unasked.contains(&origin)
12392                {
12393                    unasked.push(origin);
12394                }
12395            }
12396            unasked
12397        };
12398        if unasked.is_empty() {
12399            return Ok(());
12400        }
12401        // One batch is held back for the read ahead that follows, which may carry a project's
12402        // members beside it in the same request.
12403        if unasked.len() <= ORIGIN_BATCH {
12404            let mut pending =
12405                self.pending_origins
12406                    .lock()
12407                    .map_err(|_| SourceError::Unavailable {
12408                        message:
12409                            "origins held for a read ahead were left inconsistent; run the command \
12410                          again"
12411                                .into(),
12412                    })?;
12413            for origin in unasked {
12414                if !pending.contains(origin) {
12415                    pending.push(origin.clone());
12416                }
12417            }
12418            return Ok(());
12419        }
12420        let unasked: Vec<String> = unasked.into_iter().cloned().collect();
12421        self.send_origin_lookups(&unasked, None).await
12422    }
12423
12424    /// Hold, for [`TaskSource::member_classifications`] of `project`, each member's
12425    /// classification and repositories as the members page `data` carries them — when that page
12426    /// is every member, each one names `project` as its parent, and every record it holds is
12427    /// readable. Any other page holds nothing, so the members are read as they always were.
12428    fn hold_member_classes(&self, project: &NativeId, data: &Value) -> Result<(), SourceError> {
12429        let Some(page) = data
12430            .pointer("/members/subIssues")
12431            .filter(|page| !page.is_null())
12432        else {
12433            return Ok(());
12434        };
12435        if page
12436            .pointer("/pageInfo/hasNextPage")
12437            .and_then(Value::as_bool)
12438            != Some(false)
12439        {
12440            return Ok(());
12441        }
12442        let Some(nodes) = page.get("nodes").and_then(Value::as_array) else {
12443            return Ok(());
12444        };
12445        let mut members = Vec::with_capacity(nodes.len());
12446        for node in nodes {
12447            if node.pointer("/parent/id").and_then(Value::as_str) != Some(project.0.as_str()) {
12448                return Ok(());
12449            }
12450            let Some(body) = node.get("body").and_then(Value::as_str) else {
12451                return Ok(());
12452            };
12453            // Every node here is filed under `project`, which `BoardKind::of` reads as one of its
12454            // tasks whatever its marker says, so each is a member the full read would classify.
12455            let Ok((_, slot)) = metadata_body(Some(body.to_owned())) else {
12456                return Ok(());
12457            };
12458            let Ok(classification) = Classification::from_metadata(&slot) else {
12459                return Ok(());
12460            };
12461            let repositories = if slot.contains_key(Repository::METADATA_KEY) {
12462                let Ok(repositories) = Repository::from_metadata(&slot) else {
12463                    return Ok(());
12464                };
12465                repositories
12466            } else {
12467                let Some(origin) = node
12468                    .pointer("/repository/nameWithOwner")
12469                    .and_then(Value::as_str)
12470                else {
12471                    return Ok(());
12472                };
12473                let Ok(own) = Repository::try_from(format!("{}/{origin}", RepositoryTarget::HOST))
12474                else {
12475                    return Ok(());
12476                };
12477                vec![own]
12478            };
12479            members.push((classification, repositories));
12480        }
12481        self.member_classes
12482            .lock()
12483            .map_err(|_| SourceError::Unavailable {
12484                message: "a project's members held for its classification were left \
12485                          inconsistent; run the command again"
12486                    .into(),
12487            })?
12488            .insert(project.clone(), members);
12489        Ok(())
12490    }
12491
12492    /// Send every origin held back for the read ahead, beside the members of `members` when it
12493    /// names a project — or nothing, when none is held.
12494    async fn send_pending_origins(&self, members: Option<&NativeId>) -> Result<(), SourceError> {
12495        let pending = std::mem::take(&mut *self.pending_origins.lock().map_err(|_| {
12496            SourceError::Unavailable {
12497                message: "origins held for a read ahead were left inconsistent; run the command \
12498                          again"
12499                    .into(),
12500            }
12501        })?);
12502        if pending.is_empty() {
12503            return Ok(());
12504        }
12505        self.send_origin_lookups(&pending, members).await
12506    }
12507
12508    /// [`graphql::ORIGIN_LOOKUPS`] of `unasked`, [`ORIGIN_BATCH`] to a request — the first one
12509    /// [`graphql::ORIGIN_LOOKUPS_WITH_MEMBERS`], carrying the members of `members`, when it names
12510    /// a project — holding each origin's answer and, from a members page that is the whole of
12511    /// them, each member's classification.
12512    async fn send_origin_lookups(
12513        &self,
12514        unasked: &[String],
12515        members: Option<&NativeId>,
12516    ) -> Result<(), SourceError> {
12517        let Some(repository) = self.repository.clone() else {
12518            return Ok(());
12519        };
12520        let mut members = members;
12521        for chunk in unasked.chunks(ORIGIN_BATCH) {
12522            let mut variables = json!({"owner":self.owner,"number":self.project_number,
12523                "type":"ISSUE","lookupFirst":ORIGIN_LOOKUPS_PAGE_SIZE,"nestedFirst":NESTED_PAGE_SIZE,
12524                "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true,
12525                "repositoryOwner":repository.owner,"repositoryName":repository.name});
12526            for slot in 0..ORIGIN_BATCH {
12527                let origin = chunk.get(slot).unwrap_or(&chunk[0]);
12528                variables[format!("filter{slot}")] =
12529                    json!(format!("{ORIGIN_FIELD}:{}", quoted(origin)));
12530                variables[format!("search{slot}")] = json!(
12531                    self.board_search(Some(&format!("in:body {}", quoted(&as_stored(origin)))))
12532                );
12533                variables[format!("ask{slot}")] = json!(slot < chunk.len());
12534            }
12535            let project = members.take();
12536            let document = match project {
12537                Some(project) => {
12538                    variables["project"] = json!(project.0);
12539                    variables["memberFirst"] = json!(MEMBER_PAGE_SIZE);
12540                    graphql::ORIGIN_LOOKUPS_WITH_MEMBERS
12541                }
12542                None => graphql::ORIGIN_LOOKUPS,
12543            };
12544            let data = self.graphql(document, variables).await?;
12545            self.fields_read(&data)?;
12546            if let Some(project) = project {
12547                self.hold_member_classes(project, &data)?;
12548            }
12549            if let Some(node) = data.get("repository").filter(|value| !value.is_null()) {
12550                let id = required_nonblank_str(node, "id")?.to_owned();
12551                self.repository_cache()?.insert(repository.clone(), id);
12552                if let Some(numeric) = node
12553                    .get("databaseId")
12554                    .and_then(Value::as_u64)
12555                    .and_then(std::num::NonZeroU64::new)
12556                {
12557                    self.numeric_repositories
12558                        .lock()
12559                        .await
12560                        .insert(repository.clone(), numeric);
12561                }
12562            }
12563            for (slot, origin) in chunk.iter().enumerate() {
12564                let items = data
12565                    .pointer(&format!("/o{slot}/projectV2/items"))
12566                    .filter(|value| !value.is_null())
12567                    .ok_or_else(|| SourceError::Refused {
12568                        message: format!(
12569                            "GitHub project {}/{} was not found or is not visible to the token",
12570                            self.owner, self.project_number
12571                        ),
12572                    })?;
12573                let searched =
12574                    data.get(format!("s{slot}"))
12575                        .ok_or_else(|| SourceError::Malformed {
12576                            message: "GitHub search response has no search connection".into(),
12577                        })?;
12578                if resumed(items, None)?.has_more() || resumed(searched, None)?.has_more() {
12579                    continue;
12580                }
12581                let mut found: Vec<Resolved> = Vec::new();
12582                for item in optional_nodes(Some(items), "project items")?
12583                    .into_iter()
12584                    .flatten()
12585                {
12586                    if let Some(resolved) = self.resolve(item)?
12587                        && resolved.content_kind == ContentKind::Issue
12588                        && !found.iter().any(|held| held.id == resolved.id)
12589                    {
12590                        found.push(resolved);
12591                    }
12592                }
12593                for node in optional_nodes(Some(searched), "search")?
12594                    .into_iter()
12595                    .flatten()
12596                {
12597                    if let Some(resolved) = self.resolve_issue(node).await?
12598                        && !found.iter().any(|held| held.id == resolved.id)
12599                    {
12600                        found.push(resolved);
12601                    }
12602                }
12603                self.narrowed_cache()?
12604                    .insert(Narrowing::Origin((*origin).clone()).key(), found);
12605            }
12606        }
12607        Ok(())
12608    }
12609
12610    /// Delete every issue of `ids`, [`DELETE_BATCH`] to a request with
12611    /// [`graphql::DELETE_ISSUES`], and answer those still there: each a request's answer does not
12612    /// confirm, every one of a request refused whole included.
12613    async fn delete_issues(&self, ids: &[&NativeId]) -> Vec<NativeId> {
12614        let mut left = Vec::new();
12615        for chunk in ids.chunks(DELETE_BATCH) {
12616            let mut variables = serde_json::Map::new();
12617            for slot in 0..DELETE_BATCH {
12618                let id = chunk.get(slot).unwrap_or(&chunk[0]);
12619                variables.insert(format!("delete{slot}"), json!({"issueId": id.0}));
12620                variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12621            }
12622            let data = self
12623                .graphql(graphql::DELETE_ISSUES, Value::Object(variables))
12624                .await
12625                .unwrap_or(Value::Null);
12626            for (slot, id) in chunk.iter().enumerate() {
12627                // Confirmed only by the repository the deleted issue was in, named by a
12628                // non-blank id: anything else says nothing of whether the issue is gone.
12629                let confirmed = data
12630                    .pointer(&format!("/delete{slot}/repository/id"))
12631                    .and_then(Value::as_str)
12632                    .is_some_and(|id| !id.trim().is_empty());
12633                if !confirmed {
12634                    left.push((*id).clone());
12635                }
12636            }
12637        }
12638        left
12639    }
12640
12641    /// Delete one issue, which takes its board item with it.
12642    async fn delete_issue(&self, id: &NativeId) -> Result<(), SourceError> {
12643        let data = self
12644            .graphql(graphql::DELETE_ISSUE, json!({"input":{"issueId":id.0}}))
12645            .await?;
12646        data.pointer("/deleteIssue/repository")
12647            .filter(|value| !value.is_null())
12648            .ok_or_else(|| SourceError::Malformed {
12649                message: "GitHub issue deletion returned no repository".into(),
12650            })?;
12651        self.forget(id)?;
12652        Ok(())
12653    }
12654
12655    /// Remove one item this copy created, so a copy that could not finish leaves the board
12656    /// as it found it.
12657    ///
12658    /// Deleting the issue takes its board item with it, so there is no second mutation to
12659    /// keep in step. An id the board does not hold is not an error: the item is already
12660    /// gone, which is the state this asks for. Which that is, is decided by reading the item
12661    /// by its own id — a listing of the board can still be missing an item it holds, and
12662    /// reading that as *already gone* would leave behind the very item this was asked to
12663    /// take back.
12664    async fn delete_item(&self, id: &NativeId) -> Result<(), SourceError> {
12665        let Some(item) = self.bound_item(id).await? else {
12666            return Ok(());
12667        };
12668        if item.content_kind == ContentKind::DraftIssue {
12669            return Err(SourceError::Refused {
12670                message: format!(
12671                    "GitHub item {} is a draft, and this source removes an item by deleting \
12672                     its issue; next: remove it from the board by hand",
12673                    id.0
12674                ),
12675            });
12676        }
12677        let data = self
12678            .graphql(graphql::DELETE_ISSUE, json!({"input":{"issueId":id.0}}))
12679            .await?;
12680        data.pointer("/deleteIssue/repository")
12681            .filter(|value| !value.is_null())
12682            .ok_or_else(|| SourceError::Malformed {
12683                message: "GitHub issue deletion returned no repository".into(),
12684            })?;
12685        self.forget(id)?;
12686        Ok(())
12687    }
12688
12689    /// The issue a comment call on `task` is about, or `None` when this board holds no such
12690    /// task.
12691    ///
12692    /// Resolved exactly as [`TaskSource::get_task`] resolves it, so the comment verbs and a
12693    /// read of the task cannot disagree about which ids name one: a project or a document of
12694    /// this board is not a task here either.
12695    ///
12696    /// A **draft** is a task with nowhere to keep a comment, because GitHub keeps comments on
12697    /// issues and a draft is not one. It is refused rather than answered with an empty page,
12698    /// which would read as a task nobody has commented on yet.
12699    async fn commented_issue(&self, task: &NativeId) -> Result<Option<NativeId>, SourceError> {
12700        let cached = self.resolved_cache()?.get(task).cloned();
12701        let Some(item) = (match cached {
12702            Some(item) => Some(item),
12703            None => self.item_by_id(task).await?,
12704        })
12705        .filter(|item| item.kind == BoardKind::Work(ItemKind::Task)) else {
12706            return Ok(None);
12707        };
12708        if item.content_kind == ContentKind::DraftIssue {
12709            return Err(self.draft_has_no_comments(task));
12710        }
12711        Ok(Some(item.id))
12712    }
12713
12714    /// The refusal a comment call on a board draft is answered with: GitHub keeps comments on
12715    /// issues, and a draft is not one.
12716    fn draft_has_no_comments(&self, task: &NativeId) -> SourceError {
12717        SourceError::Refused {
12718            message: format!(
12719                "task {} of source {} is a draft item on the board, and GitHub keeps \
12720                 comments on issues alone, so a draft has none to read or write; next: \
12721                 convert the draft to an issue on the board, then comment on the issue it \
12722                 becomes",
12723                task.0, self.name
12724            ),
12725        }
12726    }
12727
12728    /// One task and a page of its comments, read with [`graphql::ISSUE_DETAIL`] in one
12729    /// request — or `None` when this board holds no task by that id.
12730    ///
12731    /// What `task show` and a comment listing read. A draft is a task with no comments, so it
12732    /// is answered with the draft and the refusal, at the price of the draft's own read.
12733    async fn issue_detail(
12734        &self,
12735        id: &NativeId,
12736        page: &PageRequest,
12737    ) -> Result<Option<TaskDetailRead>, SourceError> {
12738        let after = page.cursor.as_ref().map(|cursor| cursor.0.as_str());
12739        let asked = self
12740            .graphql(
12741                graphql::ISSUE_DETAIL,
12742                json!({"id":id.0,"first":page.limit.min(MAX_PAGE_SIZE),"after":after,
12743                       "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
12744                       "duplicates":true}),
12745            )
12746            .await;
12747        let data = match asked {
12748            Ok(data) => data,
12749            Err(error) if unresolvable_node(&error) => return Ok(None),
12750            Err(error) => return Err(error),
12751        };
12752        // `node` is null for an id that names nothing, and absent only from an answer this
12753        // source cannot read — never the same thing.
12754        let node = data.get("node").ok_or_else(|| SourceError::Malformed {
12755            message: format!("GitHub answered the read of {} with no node", id.0),
12756        })?;
12757        self.detail_of(id, node, true, after).await
12758    }
12759
12760    /// Several tasks, each with the first page of its comments when `comments` is set, read
12761    /// [`DETAIL_BATCH`] at a time with [`graphql::ISSUE_DETAILS`] — one answer per id, in
12762    /// order.
12763    ///
12764    /// A batch GitHub refuses because one of its ids resolves to no node at all is read again
12765    /// one item at a time, so that id is answered as missing and the others as themselves; any
12766    /// other refusal is every id of that batch's answer.
12767    async fn issue_details(
12768        &self,
12769        ids: &[NativeId],
12770        comments: Option<&PageRequest>,
12771    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
12772        let mut read = Vec::with_capacity(ids.len());
12773        for batch in ids.chunks(DETAIL_BATCH) {
12774            match self
12775                .graphql(graphql::ISSUE_DETAILS, detail_batch(batch, comments))
12776                .await
12777            {
12778                Ok(data) => {
12779                    for (slot, id) in batch.iter().enumerate() {
12780                        // Every alias asked for is answered, null for an id naming nothing;
12781                        // one missing is an answer this source cannot read.
12782                        let read_one = match data.get(format!("i{slot}")) {
12783                            Some(node) => self.detail_of(id, node, comments.is_some(), None).await,
12784                            None => Err(SourceError::Malformed {
12785                                message: format!(
12786                                    "GitHub answered a batch read with no item for {}",
12787                                    id.0
12788                                ),
12789                            }),
12790                        };
12791                        read.push(read_one);
12792                    }
12793                }
12794                Err(error) if unresolvable_node(&error) => {
12795                    for id in batch {
12796                        read.push(match comments {
12797                            Some(page) => self.issue_detail(id, page).await,
12798                            None => self.task_read(id).await,
12799                        });
12800                    }
12801                }
12802                Err(error) => read.extend(batch.iter().map(|_| Err(error.clone()))),
12803            }
12804        }
12805        read
12806    }
12807
12808    /// One task and nothing of its comments, as [`TaskSource::get_task`] reads it.
12809    async fn task_read(&self, id: &NativeId) -> Result<Option<TaskDetailRead>, SourceError> {
12810        Ok(self.get_task(id).await?.map(|task| TaskDetailRead {
12811            task,
12812            comments: None,
12813        }))
12814    }
12815
12816    /// What one node a detail read reached says: the task this board holds by `id`, with the
12817    /// page of comments the node carries when `commented` — or `None` for a node that is no
12818    /// task of this board.
12819    ///
12820    /// Resolved as [`Self::item_by_id`] resolves an item: a draft is read again as a draft,
12821    /// and an item this process created answers from this process's own record, which a node
12822    /// read taken moments after the write can still be behind.
12823    async fn detail_of(
12824        &self,
12825        id: &NativeId,
12826        node: &Value,
12827        commented: bool,
12828        after: Option<&str>,
12829    ) -> Result<Option<TaskDetailRead>, SourceError> {
12830        if node.is_null() {
12831            return Ok(None);
12832        }
12833        let draft = optional_str(node, "__typename")? == Some("DraftIssue");
12834        // An issue answered under one id is that id's, or the answer is not one this source
12835        // can report: reporting another issue's task and comments under the qualified id asked
12836        // for would be the one wrong answer here. A draft's own read checks the same.
12837        if !draft
12838            && optional_str(node, "__typename")? == Some("Issue")
12839            && required_str(node, "id")? != id.0
12840        {
12841            return Err(SourceError::Malformed {
12842                message: format!(
12843                    "GitHub answered the read of {} with issue {}",
12844                    id.0,
12845                    required_str(node, "id")?
12846                ),
12847            });
12848        }
12849        let item = if draft {
12850            self.draft_by_id(id).await?
12851        } else {
12852            self.resolve_issue(node).await?
12853        };
12854        // A read that carried the whole of what the issue is blocked by — a copy's — is kept
12855        // for this command, so the dependency read the copy makes next is answered from it.
12856        if let Some(read) = item.as_ref().filter(|item| item.blocked_by.is_some()) {
12857            self.resolved_cache()?.insert(read.id.clone(), read.clone());
12858        }
12859        let Some(item) = item.filter(|item| item.kind == BoardKind::Work(ItemKind::Task)) else {
12860            return Ok(None);
12861        };
12862        let own = self.created()?.iter().find(|own| own.id == *id).cloned();
12863        let task = own.unwrap_or(item).task()?;
12864        let comments = match (commented, draft) {
12865            (false, _) => None,
12866            (true, true) => Some(Err(self.draft_has_no_comments(id))),
12867            (true, false) => Some(comment_page(node, &id.0, after).map(Some)),
12868        };
12869        if commented && !draft && after.is_none() {
12870            self.expected.learn_comments(id, node);
12871        }
12872        Ok(Some(TaskDetailRead { task, comments }))
12873    }
12874
12875    /// Whether the comment `comment` is one of `issue`'s own.
12876    ///
12877    /// Read before an edit or a removal is sent, because GitHub's comment mutations take the
12878    /// comment's id and nothing else: a comment id given against the wrong task would
12879    /// otherwise change a comment on some other issue entirely. An id that names nothing, or
12880    /// names something that is not an issue comment, is a comment this task does not have —
12881    /// which is what GitHub refusing to resolve it means too.
12882    async fn comment_is_on(
12883        &self,
12884        issue: &NativeId,
12885        comment: &NativeId,
12886    ) -> Result<bool, SourceError> {
12887        Ok(self.comment_on(issue, comment).await?.is_some())
12888    }
12889
12890    /// The body the comment `comment` holds, exactly as GitHub holds it, when it is one of
12891    /// `issue`'s own — the read [`Self::comment_is_on`] makes, answering with what it selected.
12892    async fn comment_on(
12893        &self,
12894        issue: &NativeId,
12895        comment: &NativeId,
12896    ) -> Result<Option<String>, SourceError> {
12897        // A write the store's cache expects knows which comments its issue held, and their
12898        // bodies, at the version it expects: what this read would answer.
12899        if let Some(primed) = self.expected.primed_comment(issue, comment) {
12900            return Ok(primed);
12901        }
12902        let asked = self
12903            .graphql(graphql::COMMENT_ISSUE, json!({"id":comment.0}))
12904            .await;
12905        let data = match asked {
12906            Ok(data) => data,
12907            Err(error) if unresolvable_node(&error) => return Ok(None),
12908            Err(error) => return Err(error),
12909        };
12910        let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
12911            return Ok(None);
12912        };
12913        if optional_str(node, "__typename")? != Some("IssueComment") {
12914            return Ok(None);
12915        }
12916        let on = node.get("issue").ok_or_else(|| SourceError::Malformed {
12917            message: format!("GitHub issue comment {} names no issue", comment.0),
12918        })?;
12919        if required_str(on, "id")? != issue.0 {
12920            return Ok(None);
12921        }
12922        Ok(Some(required_str(node, "body")?.to_owned()))
12923    }
12924
12925    /// Which far ends this item's own `blockedBy` relationship holds, and which it cannot.
12926    async fn partition_edges(
12927        &self,
12928        near_kind: BoardKind,
12929        near_content: ContentKind,
12930        carried: Option<&[Value]>,
12931        depends_on: &[DependencyEdge],
12932    ) -> Result<(Vec<String>, Vec<DependencyEdge>), SourceError> {
12933        let mut native = Vec::new();
12934        let mut fallback = Vec::new();
12935        let far_ends: Vec<(&DependencyEdge, &str, bool, Option<&Value>)> = depends_on
12936            .iter()
12937            .map(|edge| {
12938                // An opaque far end names another tracker, so it is never this board's own.
12939                let same_source = edge.to.designator().is_none()
12940                    && edge
12941                        .to
12942                        .source()
12943                        .is_none_or(|source| source == self.name.as_str());
12944                // A qualified id's source segment runs to its *first* colon — `GlobalId` and
12945                // `DependencyEndpoint::source` both read it that way — and a native id may hold
12946                // colons of its own, so the far end is everything after that one separator.
12947                // Splitting at the last would truncate `work:urn:task:7` to `7`.
12948                let far_id = if edge.to.is_qualified() {
12949                    edge.to
12950                        .id()
12951                        .split_once(':')
12952                        .map_or(edge.to.id(), |(_, native)| native)
12953                } else {
12954                    edge.to.id()
12955                };
12956                // One that already blocks the near issue was answered by that issue's own
12957                // read, which carried each of its blockers' kinds — an issue every one — so it
12958                // is not read again.
12959                let blocking = carried.and_then(|nodes| {
12960                    nodes
12961                        .iter()
12962                        .find(|node| node.get("id").and_then(Value::as_str) == Some(far_id))
12963                });
12964                (edge, far_id, same_source, blocking)
12965            })
12966            .collect();
12967        // Every other same-source far end is read by its own id, exactly as the item it is a
12968        // far end of is: whether this board holds it is that read's answer, never a listing's.
12969        // They are read together, [`DETAIL_BATCH`] to a request, rather than one each.
12970        let mut unread: Vec<NativeId> = Vec::new();
12971        for (_, far_id, same_source, blocking) in &far_ends {
12972            let id = NativeId((*far_id).to_owned());
12973            if *same_source && blocking.is_none() && !unread.contains(&id) {
12974                unread.push(id);
12975            }
12976        }
12977        let read: BTreeMap<NativeId, Option<Resolved>> = unread
12978            .iter()
12979            .cloned()
12980            .zip(self.items_by_ids(&unread).await?)
12981            .collect();
12982        for (edge, far_id, same_source, blocking) in far_ends {
12983            let far = match (same_source, blocking) {
12984                (false, _) => None,
12985                (true, Some(node)) => Some(FarEnd {
12986                    kind: if required_str(node, "title")?.starts_with(DESIGN_TITLE_PREFIX) {
12987                        BoardKind::Document
12988                    } else {
12989                        BoardKind::Work(related_kind(node, self.sub_issues)?)
12990                    },
12991                    content_kind: ContentKind::Issue,
12992                }),
12993                (true, None) => {
12994                    let read = read
12995                        .get(&NativeId(far_id.to_owned()))
12996                        .cloned()
12997                        .flatten()
12998                        .ok_or_else(|| SourceError::Refused {
12999                            message: format!("GitHub dependency item {far_id} was not found"),
13000                        })?;
13001                    Some(FarEnd {
13002                        kind: read.kind,
13003                        content_kind: read.content_kind,
13004                    })
13005                }
13006            };
13007            let far = far.as_ref();
13008            // The caller says which kind the far end is, and this board holds the far end
13009            // itself, so a disagreement is settled here rather than stored: recorded, the
13010            // wrong kind would read back as a cross-level edge that never existed; written
13011            // natively, it would name a relationship of a different level than the caller
13012            // asked for.
13013            //
13014            // A far end this board holds as a *document* fails the same comparison and is
13015            // refused by the same sentence: `ItemKind` has no document variant because
13016            // nothing may point at one, so no caller can name it correctly and the refusal
13017            // is the only honest answer.
13018            if let Some(disagreeing) = far.filter(|far| far.kind != BoardKind::Work(edge.to.kind)) {
13019                return Err(SourceError::Refused {
13020                    message: format!(
13021                        "GitHub dependency item {far_id} is a {} of this board, and this item \
13022                         names it as a {}; record the kind it is",
13023                        disagreeing.kind.describes(),
13024                        edge.to.kind.marker()
13025                    ),
13026                });
13027            }
13028            // A draft has neither `blockedBy` nor `blocking`, so no edge of one is native
13029            // however the far end is spelled — and one classified native here would be
13030            // written nowhere at all, because a draft's native reconciliation never runs.
13031            let native_here = near_content == ContentKind::Issue
13032                && far.is_some_and(|far| {
13033                    far.content_kind == ContentKind::Issue
13034                        && BoardKind::Work(edge.to.kind) == near_kind
13035                });
13036            if native_here {
13037                native.push(far_id.to_owned());
13038            } else {
13039                fallback.push(edge.clone());
13040            }
13041        }
13042        Ok((native, fallback))
13043    }
13044
13045    async fn update_existing(
13046        &self,
13047        item: &Resolved,
13048        incoming: &Incoming<'_>,
13049        body: &Option<String>,
13050        status_target: Option<&StatusTarget>,
13051    ) -> Result<(), SourceError> {
13052        let title = incoming.written_title();
13053        // A terminal status closes the issue here, in the same mutation as its body: its board
13054        // option was selected before this, so a close never lands on an item whose board cannot
13055        // show it.
13056        let mut fields = match item.content_kind {
13057            ContentKind::DraftIssue => json!({"title":title,"body":body}),
13058            ContentKind::Issue => json!({"title":title,"body":body,
13059                                         "stateInput":state_input(status_target)}),
13060        };
13061        // The people it is to be assigned to, replacing whoever it holds — sent only when they
13062        // are not exactly those, and looked up before anything of this write was sent.
13063        if let Some(people) = incoming.assignees
13064            && item
13065                .assignees
13066                .as_deref()
13067                .is_none_or(|held| !assignees::same_people(held, people))
13068        {
13069            if item.content_kind == ContentKind::DraftIssue {
13070                return Err(self.assigns_a_draft());
13071            }
13072            fields["assigneeIds"] = json!(self.people_ids(people, &item.written_name())?);
13073        }
13074        // Only the members whose value differs from the item as this write read it are sent,
13075        // and nothing at all when none does — whether or not the store's cache expects a
13076        // version of it. A member left out is one GitHub leaves as it is, so a person's edit
13077        // of it since that read is kept rather than overwritten with what it already held,
13078        // and a re-copy of an unchanged item costs no mutation.
13079        if let Some(members) = fields.as_object_mut() {
13080            if members.get("title").and_then(Value::as_str) == Some(item.title.as_str()) {
13081                members.remove("title");
13082            }
13083            let body_unchanged = match (members.get("body"), item.raw_body.as_deref()) {
13084                (Some(Value::String(sent)), Some(held)) => sent == held,
13085                (Some(Value::Null), held) => held.is_none_or(str::is_empty),
13086                _ => false,
13087            };
13088            if body_unchanged {
13089                members.remove("body");
13090            }
13091            // An issue already in the state the target asks for keeps it: an open one stays
13092            // open, and a closed one whose closure reads as the target's category keeps its
13093            // reason — a duplicate's says more than this write would.
13094            let unchanged_state = match status_target {
13095                Some(StatusTarget::Terminal(_, reason)) => {
13096                    item.closed
13097                        && closed_category(item.reason.as_deref())
13098                            == closed_category(Some(reason.reason()))
13099                }
13100                Some(StatusTarget::Column(_) | StatusTarget::Disabled(_)) => !item.closed,
13101                None => true,
13102            };
13103            if unchanged_state {
13104                members.remove("stateInput");
13105            }
13106            if members.is_empty() {
13107                return Ok(());
13108            }
13109        }
13110        self.update_content(item.content_kind, &item.id, fields)
13111            .await
13112    }
13113
13114    /// Update one board item's content with exactly `fields` beside its id, through the
13115    /// mutation its kind takes: `updateIssue` for an issue, `updateProjectV2DraftIssue` for
13116    /// a draft.
13117    ///
13118    /// Every input field either mutation leaves out is a field GitHub leaves as it is, which
13119    /// is what lets a narrow write carry the one thing it changes and nothing else.
13120    async fn update_content(
13121        &self,
13122        kind: ContentKind,
13123        id: &NativeId,
13124        fields: Value,
13125    ) -> Result<(), SourceError> {
13126        let (operation, id_key, pointer) = match kind {
13127            ContentKind::DraftIssue => (
13128                graphql::UPDATE_DRAFT,
13129                "draftIssueId",
13130                "/updateProjectV2DraftIssue/draftIssue",
13131            ),
13132            ContentKind::Issue => (graphql::UPDATE_ISSUE, "id", "/updateIssue/issue"),
13133        };
13134        if kind == ContentKind::Issue && self.hold_issue(&fields)? {
13135            return Ok(());
13136        }
13137        if kind == ContentKind::Issue && self.hold_update(id, &fields)? {
13138            return Ok(());
13139        }
13140        let mut input = fields;
13141        input[id_key] = json!(id.0);
13142        self.send_update(operation, pointer, id, input).await
13143    }
13144
13145    /// Send one item's update, `input`, as `operation`, and hold GitHub's answer at `pointer`
13146    /// to naming that item, `id`.
13147    async fn send_update(
13148        &self,
13149        operation: &str,
13150        pointer: &str,
13151        id: &NativeId,
13152        input: Value,
13153    ) -> Result<(), SourceError> {
13154        let data = match self.graphql(operation, json!({"input":&input})).await {
13155            Ok(data) => data,
13156            Err(error) => return Err(self.refusing_people(&input, error)),
13157        };
13158        let returned = data
13159            .pointer(pointer)
13160            .ok_or_else(|| SourceError::Malformed {
13161                message: "GitHub item update returned no item".into(),
13162            })?;
13163        if required_str(returned, "id")? != id.0 {
13164            return Err(SourceError::Malformed {
13165                message: "GitHub item update returned the wrong item".into(),
13166            });
13167        }
13168        self.assigned_as_asked(&input, Some(returned))
13169    }
13170
13171    /// Creates one issue, files it on the board, and reports what a read of it would say:
13172    /// its content id, its board item id, and the web address GitHub gave it.
13173    ///
13174    /// Two calls rather than one: `createIssue` answers with an issue that is on no board,
13175    /// and `addProjectV2ItemById` is what puts it there. Filing it at creation through
13176    /// `CreateIssueInput.projectV2Ids` was tried and is not done: GitHub answered with no
13177    /// board item, and the `addProjectV2ItemById` that then had to follow was refused
13178    /// "Content already exists in this project". A terminal status is not written here:
13179    /// `finish_write` selects its option first and closes the issue after, so a close never
13180    /// lands on an item whose board cannot show it.
13181    ///
13182    /// The address and the number come back here because this is the only place either is
13183    /// known before GitHub's own board read catches up — an item this run created answers
13184    /// the reads that follow it out of the record below, and one remembered without them
13185    /// would report no location and no key for the rest of the run.
13186    async fn create_and_file_issue(
13187        &self,
13188        board_id: &str,
13189        repository: &RepositoryTarget,
13190        incoming: &Incoming<'_>,
13191        body: &Option<String>,
13192    ) -> Result<Landed, SourceError> {
13193        let repository_id = self.repository_id(repository, incoming).await?;
13194        let mut input = json!({
13195            "repositoryId":repository_id,"title":incoming.written_title(),"body":body
13196        });
13197        self.assigning(&mut input, incoming)?;
13198        let data = match self
13199            .graphql(graphql::CREATE_ISSUE, json!({"input": &input}))
13200            .await
13201        {
13202            Ok(data) => data,
13203            Err(error) => return Err(self.refusing_people(&input, error)),
13204        };
13205        let created = data
13206            .pointer("/createIssue/issue")
13207            .filter(|value| !value.is_null())
13208            .ok_or_else(|| SourceError::Malformed {
13209                message: "GitHub issue creation returned no issue".into(),
13210            })?;
13211        let content_id = NativeId(required_str(created, "id")?.to_owned());
13212        // Assigned otherwise than asked, the issue is refused and taken back as the filed
13213        // create's is, a refused delete answered beside the refusal.
13214        if let Err(error) = self.assigned_as_asked(&input, Some(created)) {
13215            return Err(self.taken_back(&content_id, created, error).await);
13216        }
13217        // Optional although GitHub's schema makes it non-null: the issue exists by now, so
13218        // a response without it is not worth failing a landed write over — the item simply
13219        // reports no location until the board read catches up, which is what it did before.
13220        let url = optional_str(created, "url")?.map(str::to_owned);
13221        // The issue exists from here on, so an unreadable number and a refused board
13222        // filing below each try, best effort, to take it back: an issue in the repository
13223        // that is on no board is an item nobody asked for and nothing here would find again.
13224        //
13225        // Its number is optional on the same terms its address is — a landed write is not
13226        // worth failing over a member that came back missing, and such an item reports no
13227        // handle until a board read catches up. A number that is *present* and is not an
13228        // unsigned integer is still a response this source cannot read.
13229        let number = match created_issue_number(created) {
13230            Ok(number) => number,
13231            Err(error) => {
13232                let _ = self.delete_issue(&content_id).await;
13233                return Err(error);
13234            }
13235        };
13236        let added = match self
13237            .graphql(
13238                graphql::ADD_TO_BOARD,
13239                json!({"input":{"projectId":board_id,"contentId":content_id.0}}),
13240            )
13241            .await
13242        {
13243            Ok(added) => added,
13244            Err(error) => {
13245                let _ = self.delete_issue(&content_id).await;
13246                return Err(error);
13247            }
13248        };
13249        let item = added
13250            .pointer("/addProjectV2ItemById/item")
13251            .filter(|value| !value.is_null())
13252            .ok_or_else(|| SourceError::Malformed {
13253                message: "GitHub board addition returned no project item".into(),
13254            })?;
13255        self.note_written(&content_id, url.as_deref());
13256        Ok(Landed {
13257            content_id,
13258            item_id: Some(required_str(item, "id")?.to_owned()),
13259            url,
13260            number,
13261        })
13262    }
13263
13264    /// Move one issue under the project it now belongs to, or out of the one it left.
13265    async fn reparent(
13266        &self,
13267        held: Option<NativeId>,
13268        child: &NativeId,
13269        wanted: Option<&NativeId>,
13270    ) -> Result<(), SourceError> {
13271        if held.as_ref() == wanted {
13272            return Ok(());
13273        }
13274        if let Some(held) = &held {
13275            self.sub_issue(graphql::REMOVE_SUB_ISSUE, held, child, "removeSubIssue")
13276                .await?;
13277        }
13278        if let Some(wanted) = wanted {
13279            self.sub_issue(graphql::ADD_SUB_ISSUE, wanted, child, "addSubIssue")
13280                .await?;
13281        }
13282        Ok(())
13283    }
13284
13285    async fn sub_issue(
13286        &self,
13287        operation: &str,
13288        parent: &NativeId,
13289        child: &NativeId,
13290        root: &str,
13291    ) -> Result<(), SourceError> {
13292        let data = self
13293            .graphql(
13294                operation,
13295                json!({"input":{"issueId":parent.0,"subIssueId":child.0}}),
13296            )
13297            .await?;
13298        let issue =
13299            data.pointer(&format!("/{root}/issue"))
13300                .ok_or_else(|| SourceError::Malformed {
13301                    message: "GitHub sub-issue update returned no issue".into(),
13302                })?;
13303        let sub =
13304            data.pointer(&format!("/{root}/subIssue"))
13305                .ok_or_else(|| SourceError::Malformed {
13306                    message: "GitHub sub-issue update returned no sub-issue".into(),
13307                })?;
13308        if required_str(issue, "id")? != parent.0 || required_str(sub, "id")? != child.0 {
13309            return Err(SourceError::Malformed {
13310                message: "GitHub sub-issue update returned the wrong issues".into(),
13311            });
13312        }
13313        Ok(())
13314    }
13315
13316    /// Bring one issue's `blockedBy` to exactly `native`, sending only the difference, and say
13317    /// whether there was one.
13318    ///
13319    /// An issue [`Issue::Created`] by this very write is blocked by nothing yet, so its
13320    /// relationships are not read: there is nothing a read of them could find.
13321    async fn reconcile_blocked_by(
13322        &self,
13323        content_id: &NativeId,
13324        native: &[String],
13325        issue: Issue<'_>,
13326    ) -> Result<bool, SourceError> {
13327        let current = match issue {
13328            Issue::Created => Vec::new(),
13329            Issue::Existing(Some(held)) => held
13330                .iter()
13331                .map(|far| required_str(far, "id").map(str::to_owned))
13332                .collect::<Result<Vec<_>, _>>()?,
13333            Issue::Existing(None) => self.native_dependency_ids(content_id).await?,
13334        };
13335        let mut changed = false;
13336        for (operation, far_id) in current
13337            .iter()
13338            .filter(|id| !native.contains(id))
13339            .map(|id| (graphql::REMOVE_BLOCKED_BY, id))
13340            .chain(
13341                native
13342                    .iter()
13343                    .filter(|id| !current.contains(id))
13344                    .map(|id| (graphql::ADD_BLOCKED_BY, id)),
13345            )
13346        {
13347            let data = self
13348                .graphql(
13349                    operation,
13350                    json!({"input":{"issueId":content_id.0,"blockingIssueId":far_id}}),
13351                )
13352                .await?;
13353            let root = if operation == graphql::ADD_BLOCKED_BY {
13354                "addBlockedBy"
13355            } else {
13356                "removeBlockedBy"
13357            };
13358            let issue =
13359                data.pointer(&format!("/{root}/issue"))
13360                    .ok_or_else(|| SourceError::Malformed {
13361                        message: "GitHub dependency update returned no issue".into(),
13362                    })?;
13363            let blocker = data
13364                .pointer(&format!("/{root}/blockingIssue"))
13365                .ok_or_else(|| SourceError::Malformed {
13366                    message: "GitHub dependency update returned no blocking issue".into(),
13367                })?;
13368            if required_str(issue, "id")? != content_id.0 || required_str(blocker, "id")? != far_id
13369            {
13370                return Err(SourceError::Malformed {
13371                    message: "GitHub dependency update returned the wrong issues".into(),
13372                });
13373            }
13374            changed = true;
13375        }
13376        Ok(changed)
13377    }
13378}
13379
13380/// The board field values one write sends, in the order GitHub runs them, and the fields it
13381/// clears after them: the origin field when it moves, the `Status` option `column` names, the
13382/// priority, then each projected field.
13383fn field_writes<'a>(
13384    existing: Option<&Resolved>,
13385    origin_field: Option<&str>,
13386    origin: &str,
13387    column: Option<(String, String)>,
13388    priority: Option<&'a PriorityWrite>,
13389    projections: &'a [ProjectionWrite],
13390) -> (Vec<(String, Value)>, Vec<&'a str>) {
13391    let mut fields = Vec::new();
13392    if let Some(field_id) = origin_field
13393        && existing.map_or(!origin.is_empty(), |item| {
13394            item.origin.as_deref().unwrap_or("") != origin
13395        })
13396    {
13397        fields.push((field_id.to_owned(), json!({"text":origin})));
13398    }
13399    if let Some((field_id, option_id)) = column {
13400        fields.push((field_id, json!({"singleSelectOptionId":option_id})));
13401    }
13402    let mut clears = Vec::new();
13403    match priority {
13404        Some(PriorityWrite::Select { field, option }) => {
13405            fields.push((field.clone(), json!({"singleSelectOptionId":option})));
13406        }
13407        Some(PriorityWrite::Clear { field }) => clears.push(field.as_str()),
13408        None => {}
13409    }
13410    for projection in projections {
13411        projection.join(&mut fields, &mut clears);
13412    }
13413    (fields, clears)
13414}
13415
13416/// Everything one write decided before sending anything: see
13417/// [`GitHubProjectsSource::prepare_write`].
13418struct Prepared {
13419    /// What the write lands on.
13420    destination: WriteDestination,
13421    board: BoardFields,
13422    status_target: Option<StatusTarget>,
13423    /// The `Status` field, the option and the option's name the status lands on.
13424    // llmlint: ignore[invalid_states_unrepresentable] Exactly what `column_for` returns, which predates this change and four callers share; this record only carries it from `prepare_write` to `complete_write`, which a retyping of that return would reach and this change does not need.
13425    column: Option<(String, String, String)>,
13426    priority_write: Option<PriorityWrite>,
13427    projections: Vec<ProjectionWrite>,
13428    projected: BTreeMap<String, String>,
13429    content_kind: ContentKind,
13430    own_repository: Option<Repository>,
13431    /// The far ends of the item's native blocked-by relationships.
13432    // llmlint: ignore[invalid_states_unrepresentable] What `partition_edges` answers and `finish_write` takes as `&[String]`, both of which predate this change; this record only carries the value between them.
13433    native: Vec<String>,
13434    slot: BTreeMap<String, Value>,
13435    content: Option<String>,
13436    body: Option<String>,
13437    /// The copy origin the item records, empty for none.
13438    // llmlint: ignore[invalid_states_unrepresentable] `finish_write` and `field_writes` take the origin as `&str`, empty for none, as they did before this change; this record only carries it to them.
13439    origin: String,
13440    origin_field: Option<String>,
13441}
13442
13443/// One write a copy held back of the kinds sent together: a board field value, or a blocked-by
13444/// edge, each its input.
13445enum HeldWrite<'a> {
13446    Field(&'a Value),
13447    Edge(&'a Value),
13448}
13449
13450/// Whether `error` is GitHub refusing to file an issue on a board because it is filed there
13451/// already — what `addProjectV2ItemById` answers once `createIssue`'s `projectV2Ids` has placed
13452/// it, rather than answering with the item it holds.
13453fn already_on_the_board(error: &SourceError) -> bool {
13454    error
13455        .to_string()
13456        .contains("Content already exists in this project")
13457}
13458
13459/// Hold every alias `inputs` sent under `prefix` in `data` to answering with what its input
13460/// named — each `(root, named)` of `answers` — and refuse one that answered nothing or another
13461/// item.
13462fn check_aliased_answers(
13463    document: &str,
13464    data: &Value,
13465    prefix: &str,
13466    inputs: &[&Value],
13467    answers: &[(&str, &str)],
13468) -> Result<(), SourceError> {
13469    for (slot, input) in inputs.iter().enumerate() {
13470        for (root, named) in answers {
13471            let answered = data
13472                .pointer(&format!("/{prefix}{slot}/{root}/id"))
13473                .and_then(Value::as_str)
13474                .ok_or_else(|| SourceError::Malformed {
13475                    message: format!(
13476                        "GitHub answered {} with nothing at {prefix}{slot}",
13477                        operation_description(document)
13478                    ),
13479                })?;
13480            let asked = input.get(named).and_then(Value::as_str).unwrap_or_default();
13481            if answered != asked {
13482                return Err(SourceError::Malformed {
13483                    message: format!(
13484                        "GitHub answered {} at {prefix}{slot} with {answered}, which is not \
13485                         {asked}, the item it was asked to write",
13486                        operation_description(document)
13487                    ),
13488                });
13489            }
13490        }
13491    }
13492    Ok(())
13493}
13494
13495/// `error`, which stopped a batch of creates, and — when GitHub refused to take any of them
13496/// back — each issue of `left` it created that is still in the repository, which its caller,
13497/// never handed their ids, could not name.
13498fn left_behind(error: SourceError, left: &[&str]) -> SourceError {
13499    if left.is_empty() {
13500        return error;
13501    }
13502    SourceError::Refused {
13503        message: format!(
13504            "{error}; GitHub then refused to take back {}, which this write created and which \
13505             are still in the repository; next: delete {} before writing again",
13506            left.join(", "),
13507            if left.len() == 1 { "it" } else { "them" }
13508        ),
13509    }
13510}
13511
13512/// What one write lands on: the item it updates, as it stood, or where it creates a new one.
13513enum WriteDestination {
13514    /// The item as it stood, for an update.
13515    Existing(Box<Resolved>),
13516    /// Where a new item is created.
13517    New(RepositoryTarget),
13518}
13519
13520impl WriteDestination {
13521    /// The item an update writes over, as it stood; `None` for a create.
13522    fn existing(&self) -> Option<&Resolved> {
13523        match self {
13524            Self::Existing(item) => Some(item),
13525            Self::New(_) => None,
13526        }
13527    }
13528}
13529
13530/// One existing issue's update held back by [`GitHubProjectsSource::hold_update`]: the issue,
13531/// and the `UpdateIssueInput` its own [`graphql::UPDATE_ISSUE`] would have sent — the members
13532/// it writes beside that issue's id, which only [`Self::new`] sets.
13533struct HeldUpdate {
13534    issue: NativeId,
13535    // llmlint: ignore[invalid_states_unrepresentable] The members are exactly what `update_content` would have sent at once, which every one of its callers builds as GraphQL variables; holding them back changes when they are sent, not what they may be, and only `new` builds one, fixing the issue's id. Typing `UpdateIssueInput` would retype every caller of `update_content`, a change of its own.
13536    input: Value,
13537}
13538
13539impl HeldUpdate {
13540    /// The update writing `members` — an `UpdateIssueInput` without its id — to `issue`.
13541    fn new(issue: &NativeId, members: &Value) -> Self {
13542        let mut input = members.clone();
13543        input["id"] = json!(issue.0);
13544        Self {
13545            issue: issue.clone(),
13546            input,
13547        }
13548    }
13549}
13550
13551/// What a copy has held back of the items it created; see
13552/// [`GitHubProjectsSource::hold_back`].
13553#[derive(Debug, Default)]
13554enum Deferred {
13555    /// Writes are being held back, and nothing has been held yet.
13556    #[default]
13557    Nothing,
13558    /// The items held back, every one of them on `board`.
13559    Held {
13560        /// The board every one of them is on.
13561        board: BoardId,
13562        /// Each created item, in the order it was created.
13563        created: Vec<HeldBack>,
13564    },
13565}
13566
13567impl Deferred {
13568    /// Whether `content` is one of the items held back.
13569    fn holds(&self, content: &NativeId) -> bool {
13570        match self {
13571            Self::Nothing => false,
13572            Self::Held { created, .. } => created.iter().any(|held| held.content == *content),
13573        }
13574    }
13575}
13576
13577/// One created item's parts that land once [`TaskSource::finish_writes`] is called.
13578#[derive(Debug)]
13579struct HeldBack {
13580    /// The issue.
13581    content: NativeId,
13582    /// Its board field values other than its `Status`, in the order they are written.
13583    fields: Vec<(String, Value)>,
13584    /// The `Status` field, and the option and its name that the item's status lands on.
13585    // llmlint: ignore[invalid_states_unrepresentable] The same triple `column_for` returns and `Prepared::column` carries, held back unchanged until it is sent.
13586    status: Option<(String, String, String)>,
13587    /// The fields it clears after those are written.
13588    clears: Vec<String>,
13589    /// The reason it is closed for, once its option is selected; `None` leaves it open.
13590    close: Option<ClosedState>,
13591    /// The issues it is blocked by.
13592    edges: Vec<NativeId>,
13593}
13594
13595/// The member [`answer_with_errors`] carries a response's GraphQL errors under, beside its data:
13596/// no GitHub type has a field of this name.
13597const ANSWER_ERRORS: &str = "onetaskgraphErrors";
13598
13599/// A response's `data` with its GraphQL errors beside it under [`ANSWER_ERRORS`], when it has
13600/// both — or `None`, for an answer [`GitHubProjectsSource::answer`] reads as it always has.
13601///
13602/// What [`graphql::CREATE_ISSUES`] is answered with: GitHub runs a document's mutation fields in
13603/// order and answers each one that ran, so a refusal of one alias leaves the issues the others
13604/// created named in the data beside it — the ids a copy needs to take them back.
13605fn answer_with_errors(body: &str) -> Option<Value> {
13606    let parsed: Value = serde_json::from_str(body).ok()?;
13607    let errors = parsed
13608        .get("errors")?
13609        .as_array()
13610        .filter(|errors| !errors.is_empty())?;
13611    let mut data = parsed.get("data").filter(|data| data.is_object())?.clone();
13612    data[ANSWER_ERRORS] = Value::Array(errors.clone());
13613    Some(data)
13614}
13615
13616/// The `createIssue` input that files the new issue on `board` and, when `incoming` names one,
13617/// under its project — see [`GitHubProjectsSource::create_filed_issue`].
13618fn filed_input(
13619    repository: &str,
13620    board: &str,
13621    incoming: &Incoming<'_>,
13622    body: &Option<String>,
13623) -> Value {
13624    let mut input = json!({"repositoryId":repository,"title":incoming.written_title(),
13625                           "body":body,"projectV2Ids":[board]});
13626    if let Some(parent) = incoming.parent {
13627        input["parentIssueId"] = json!(parent.0);
13628    }
13629    input
13630}
13631
13632/// The name of option `option` of field `field` among a board's `fields`.
13633fn option_name<'a>(fields: &'a Value, field: &str, option: &str) -> Option<&'a str> {
13634    fields
13635        .get("nodes")?
13636        .as_array()?
13637        .iter()
13638        .find(|node| node.get("id").and_then(Value::as_str) == Some(field))?
13639        .get("options")?
13640        .as_array()?
13641        .iter()
13642        .find(|candidate| candidate.get("id").and_then(Value::as_str) == Some(option))?
13643        .get("name")?
13644        .as_str()
13645}
13646
13647/// What a write needs to know of one far end it names: which kind of item it is, and whether
13648/// it is an issue a native relationship can name.
13649struct FarEnd {
13650    kind: BoardKind,
13651    content_kind: ContentKind,
13652}
13653
13654/// Whether the issue one write reconciles was created by that write or was already there.
13655#[derive(Clone, Copy, PartialEq, Eq)]
13656enum Issue<'a> {
13657    /// Created by this write, so it holds no relationships yet.
13658    Created,
13659    /// On the board before this write, holding whatever relationships it holds — the far
13660    /// ends of its whole `blockedBy`, when the read that reached it carried them.
13661    Existing(Option<&'a [Value]>),
13662}
13663
13664/// What resolving one node id reached; see [`GitHubProjectsSource::reach`].
13665enum Reached {
13666    /// An issue this board holds, resolved into everything this source reports about it.
13667    Held(Box<Resolved>),
13668    /// Nothing this board holds: no such node, or a node on some other board.
13669    Nothing,
13670    /// A board draft, which [`graphql::ISSUE`] reaches and reads nothing of, so it is read
13671    /// again by [`GitHubProjectsSource::draft_by_id`].
13672    Draft,
13673}
13674
13675/// What GitHub says when a string is not a node id it can resolve.
13676///
13677/// Matched because it is the ordinary answer to a project selector naming a project by its
13678/// *name*, and reporting that as a failure would make naming one impossible. It is read
13679/// off the refusal GitHub sent, never guessed from the shape of the string: this source
13680/// does not define the syntax of a GitHub node id and would be wrong about it.
13681const UNRESOLVABLE_NODE: &str = "could not resolve to a node";
13682
13683/// `error` with `note` added to the end of what it says, its kind and every other member
13684/// unchanged — so a caller still branches on the failure that happened, and reads beside it
13685/// what that failure left behind.
13686fn noting(error: SourceError, note: &str) -> SourceError {
13687    match error {
13688        SourceError::Config { message } => SourceError::Config {
13689            message: message + note,
13690        },
13691        SourceError::Auth { message } => SourceError::Auth {
13692            message: message + note,
13693        },
13694        SourceError::Refused { message } => SourceError::Refused {
13695            message: message + note,
13696        },
13697        SourceError::RateLimited {
13698            retry_after_seconds,
13699            message,
13700        } => SourceError::RateLimited {
13701            retry_after_seconds,
13702            message: Some(message.unwrap_or_default() + note),
13703        },
13704        SourceError::Unavailable { message } => SourceError::Unavailable {
13705            message: message + note,
13706        },
13707        SourceError::Malformed { message } => SourceError::Malformed {
13708            message: message + note,
13709        },
13710    }
13711}
13712
13713/// The variables of one [`graphql::ISSUE_COPY_DETAILS`] request, as [`detail_batch`] binds its
13714/// own: a slot `batch` has no id for is bound to its last id, read again at no added price.
13715fn copy_detail_batch(batch: &[NativeId], comments: &PageRequest, children: bool) -> Value {
13716    let mut variables = serde_json::Map::new();
13717    for slot in 0..COPY_DETAIL_BATCH {
13718        let id = batch.get(slot).or(batch.last()).map(|id| id.0.clone());
13719        variables.insert(format!("id{slot}"), json!(id));
13720    }
13721    variables.insert("project".to_owned(), json!(batch.first().map(|id| &id.0)));
13722    variables.insert("children".to_owned(), json!(children));
13723    variables.insert("first".to_owned(), json!(comments.limit.min(MAX_PAGE_SIZE)));
13724    variables.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
13725    variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
13726    variables.insert("duplicates".to_owned(), json!(true));
13727    Value::Object(variables)
13728}
13729
13730/// The variables of one [`graphql::ISSUE_DETAILS`] request over `batch` — at most
13731/// [`DETAIL_BATCH`] ids — each item with the first page of its comments when `comments` asks
13732/// for them.
13733///
13734/// The document is fixed-size, so a slot `batch` has no id for is bound to its last id, which
13735/// is read again at no added price.
13736fn detail_batch(batch: &[NativeId], comments: Option<&PageRequest>) -> Value {
13737    let mut variables = serde_json::Map::new();
13738    for slot in 0..DETAIL_BATCH {
13739        let id = batch.get(slot).or(batch.last()).map(|id| id.0.clone());
13740        variables.insert(format!("id{slot}"), json!(id));
13741    }
13742    variables.insert(
13743        "first".to_owned(),
13744        json!(comments.map_or(MAX_PAGE_SIZE, |page| page.limit.min(MAX_PAGE_SIZE))),
13745    );
13746    variables.insert("comments".to_owned(), json!(comments.is_some()));
13747    variables.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
13748    variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
13749    variables.insert("duplicates".to_owned(), json!(true));
13750    Value::Object(variables)
13751}
13752
13753/// Whether this refusal is GitHub saying the id names no node at all.
13754fn unresolvable_node(error: &SourceError) -> bool {
13755    matches!(error, SourceError::Refused { message }
13756        if message.to_ascii_lowercase().contains(UNRESOLVABLE_NODE))
13757}
13758
13759/// One project name, as a search qualifier which filters on it at the server.
13760///
13761/// Quoted so the whole title is one phrase rather than a bag of words, with the two
13762/// characters GitHub's own quoting grammar gives a meaning inside a quoted phrase escaped
13763/// the way it documents. A title matched here is still compared for equality afterwards:
13764/// the qualifier narrows what the server sends, and this source decides what it names.
13765fn title_qualifier(name: &str) -> String {
13766    format!("in:title {}", quoted(name))
13767}
13768
13769/// `value` as one quoted phrase of a GitHub search or a board filter, with the two
13770/// characters GitHub's quoting grammar gives a meaning inside a quoted phrase escaped the way
13771/// it documents — so a value holding a qualifier's spelling is searched for rather than
13772/// obeyed.
13773fn quoted(value: &str) -> String {
13774    let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
13775    format!("\"{escaped}\"")
13776}
13777
13778/// The search qualifier for the issues updated at or after `since`.
13779///
13780/// Written to the second, rounded down, which can only widen what the search returns.
13781fn updated_qualifier(since: DateTime<Utc>) -> String {
13782    format!("updated:>={}", since.format("%Y-%m-%dT%H:%M:%S+00:00"))
13783}
13784
13785/// The search terms that narrow a board-scoped issue search to a task query's text and
13786/// metadata predicates, or `None` when it carries neither.
13787///
13788/// The text is one quoted phrase, searched `in:title`, `in:body` or both as its fields say,
13789/// and each metadata value is one more quoted phrase, which GitHub finds in the body because
13790/// its index covers the metadata comment the value is stored in. GitHub ANDs the phrases and
13791/// matches each in any field the `in:` qualifier names, so a query naming a title search and
13792/// a metadata value searches both fields for both — wider than asked, never narrower, and
13793/// every candidate is confirmed in process afterwards.
13794///
13795/// **This narrows a text search, and that is this source's declared semantics.** GitHub
13796/// matches whole tokens where a substring rule would match inside a word, so an item holding
13797/// the text only inside a longer word is not returned. A text of nothing but whitespace
13798/// matches every item, so it narrows nothing and is not sent.
13799fn narrowing_qualifiers(query: &TaskQuery) -> Option<String> {
13800    let text = query
13801        .text
13802        .as_ref()
13803        .filter(|text| !text.terms.trim().is_empty());
13804    if text.is_none() && query.metadata.is_empty() {
13805        return None;
13806    }
13807    let (title, body) = match text.map(|text| text.fields) {
13808        None => (false, true),
13809        Some(TextFields::Title) => (true, !query.metadata.is_empty()),
13810        Some(TextFields::Content) => (false, true),
13811        Some(TextFields::TitleOrContent) => (true, true),
13812    };
13813    let fields = match (title, body) {
13814        (true, true) => "in:title,body",
13815        (true, false) => "in:title",
13816        _ => "in:body",
13817    };
13818    let phrases = text
13819        .map(|text| text.terms.clone())
13820        .into_iter()
13821        .chain(
13822            query
13823                .metadata
13824                .iter()
13825                .map(|wanted| as_stored(wanted.value())),
13826        )
13827        .map(|phrase| quoted(&phrase))
13828        .collect::<Vec<_>>();
13829    Some(format!("{fields} {}", phrases.join(" ")))
13830}
13831
13832/// Whether every status category `query` keeps reads only off an open issue or a draft: a
13833/// closed issue reads `done`, `cancelled` or — closed for a reason that implies no category —
13834/// `unknown`, so a status filter naming none of those three can ask every issue search it sends
13835/// for open issues alone; each candidate's category is still confirmed from its own item.
13836fn open_only(query: &TaskQuery) -> bool {
13837    !query.statuses.is_empty()
13838        && query.statuses.iter().all(|category| {
13839            !matches!(
13840                category,
13841                StatusCategory::Done | StatusCategory::Cancelled | StatusCategory::Unknown
13842            )
13843        })
13844}
13845
13846/// Whether every status category `query` keeps is one only an open item reads as — `draft`,
13847/// `backlog`, `todo`, `queued`, `in-progress` and `unknown` — so a listing of it can read the
13848/// board's open items alone.
13849///
13850/// `unknown` is among them here though [`open_only`] leaves it out: a closed issue reads
13851/// `unknown` only for a closure reason GitHub never records on a closed issue (see
13852/// [`closed_category`]), so an open-only read of the board loses nothing a whole one keeps,
13853/// while an issue search, which [`open_only`] narrows, keeps its own rule.
13854fn open_items_only(query: &TaskQuery) -> bool {
13855    !query.statuses.is_empty()
13856        && query
13857            .statuses
13858            .iter()
13859            .all(|category| !matches!(category, StatusCategory::Done | StatusCategory::Cancelled))
13860}
13861
13862/// What a task query is narrowed by beside a board-scoped issue search's scope — its comment
13863/// activity and its text and metadata, with `is:open` when [`open_only`] — or `None` for a query
13864/// carrying none of those, which no narrowed search answers.
13865///
13866/// A narrowed search never answers a draft, which is no issue, so narrowing it to open issues
13867/// too leaves out nothing such a search could have answered.
13868fn search_qualifiers(query: &TaskQuery) -> Option<String> {
13869    let mut qualifiers: Vec<String> = [
13870        query.commented_since.map(updated_qualifier),
13871        narrowing_qualifiers(query),
13872    ]
13873    .into_iter()
13874    .flatten()
13875    .collect();
13876    if qualifiers.is_empty() {
13877        return None;
13878    }
13879    if open_only(query) {
13880        qualifiers.push(OPEN_QUALIFIER.to_owned());
13881    }
13882    Some(qualifiers.join(" "))
13883}
13884
13885/// The search terms that narrow a board-scoped issue search to a project or document query's
13886/// text, or `None` when it has none or a blank one: the phrase, in the fields, a task query
13887/// carrying that text alone is sent as by [`narrowing_qualifiers`].
13888fn text_qualifiers(text: Option<&TextQuery>) -> Option<String> {
13889    narrowing_qualifiers(&TaskQuery {
13890        text: text.cloned(),
13891        ..TaskQuery::default()
13892    })
13893}
13894
13895/// Refuses a project or document query's text GitHub's issue search cannot find, before
13896/// anything is asked of GitHub, on exactly the terms [`refuse_unsearchable`] refuses a task
13897/// query's.
13898fn refuse_unsearchable_text(text: Option<&TextQuery>) -> Result<(), SourceError> {
13899    refuse_unsearchable(&TaskQuery {
13900        text: text.cloned(),
13901        ..TaskQuery::default()
13902    })
13903}
13904
13905/// Refuses a task query naming a text or a metadata value GitHub's issue search cannot find,
13906/// before anything is asked of GitHub.
13907///
13908/// GitHub's index holds words, so a phrase with no letter or digit names none to find, and no
13909/// bounded query answers it: sent, GitHub's answer to it is nothing this source may rely on;
13910/// left out, the search is every issue of the board. So this source says it cannot answer
13911/// rather than reading the board or answering nothing. A blank text is not refused: it narrows
13912/// nothing GitHub could search for, and keeps the board read it always had.
13913fn refuse_unsearchable(query: &TaskQuery) -> Result<(), SourceError> {
13914    const WHY: &str = "GitHub's issue search indexes words, so it cannot answer a value with no \
13915                       letter or digit with a bounded query";
13916    if let Some(text) = &query.text
13917        && !text.terms.trim().is_empty()
13918        && !has_words(&text.terms)
13919    {
13920        return Err(SourceError::Refused {
13921            message: format!(
13922                "cannot search for the text {:?}: {WHY}; search for a text holding a letter or a digit",
13923                text.terms
13924            ),
13925        });
13926    }
13927    if let Some(wanted) = query
13928        .metadata
13929        .iter()
13930        .find(|wanted| !has_words(wanted.value()))
13931    {
13932        return Err(SourceError::Refused {
13933            message: format!(
13934                "cannot filter by the metadata value {:?} at {:?}: {WHY}; filter by a value holding a letter or a digit",
13935                wanted.value(),
13936                std::iter::once(wanted.key())
13937                    .chain(wanted.path().iter().map(String::as_str))
13938                    .collect::<Vec<_>>()
13939                    .join("/"),
13940            ),
13941        });
13942    }
13943    Ok(())
13944}
13945
13946/// Whether GitHub's index could hold a word of `phrase`: whether it has a letter or a digit.
13947fn has_words(phrase: &str) -> bool {
13948    phrase.chars().any(char::is_alphanumeric)
13949}
13950
13951/// `value` spelled the way the metadata slot stores it: as the inside of its JSON string.
13952///
13953/// What GitHub indexes is the slot's JSON text, so a value holding a character JSON escapes —
13954/// a newline, a tab, a quote — is found by the escape the body holds and not by the character,
13955/// which GitHub's word match would read as different words.
13956fn as_stored(value: &str) -> String {
13957    let encoded = Value::String(value.to_owned()).to_string();
13958    encoded[1..encoded.len() - 1].to_owned()
13959}
13960
13961/// The one narrower question a task query carrying a text, metadata or origin predicate is
13962/// sent as.
13963enum Narrowing {
13964    /// Every carrier of this origin: [`graphql::ORIGIN_LOOKUP`].
13965    Origin(String),
13966    /// The board-scoped issue search narrowed by these qualifiers.
13967    Search(String),
13968}
13969
13970impl Narrowing {
13971    /// What this question is remembered under for the length of one command.
13972    fn key(&self) -> String {
13973        match self {
13974            Self::Origin(origin) => format!("origin {origin}"),
13975            Self::Search(also) => format!("search {also}"),
13976        }
13977    }
13978}
13979
13980/// Where one connection of [`graphql::ORIGIN_LOOKUP`] resumes.
13981enum Resumed {
13982    /// It reported another page, which starts after this cursor.
13983    More(String),
13984    /// It has ended. Sending this cursor again — the page's own end when it had one, and
13985    /// otherwise the cursor it was reached from — answers an empty page, so the one document
13986    /// can go on walking the other connection.
13987    Ended(Option<String>),
13988}
13989
13990impl Resumed {
13991    /// Whether the connection has another page.
13992    const fn has_more(&self) -> bool {
13993        matches!(self, Self::More(_))
13994    }
13995
13996    /// The cursor to send this connection next.
13997    fn cursor(self) -> Option<String> {
13998        match self {
13999            Self::More(next) => Some(next),
14000            Self::Ended(last) => last,
14001        }
14002    }
14003}
14004
14005/// Where `connection`, reached from `after`, resumes — refused when it reports another page
14006/// with no cursor to it, or from a cursor that does not advance.
14007fn resumed(connection: &Value, after: Option<&str>) -> Result<Resumed, SourceError> {
14008    let info = connection
14009        .get("pageInfo")
14010        .ok_or_else(|| SourceError::Malformed {
14011            message: "GitHub connection has no pageInfo".into(),
14012        })?;
14013    let end = optional_str(info, "endCursor")?;
14014    if required_bool(info, "hasNextPage")? {
14015        let next = end.ok_or_else(|| SourceError::Malformed {
14016            message: "GitHub connection reports another page and no endCursor".into(),
14017        })?;
14018        validate_cursor_progress(after, next)?;
14019        return Ok(Resumed::More(next.to_owned()));
14020    }
14021    Ok(Resumed::Ended(
14022        end.map(str::to_owned).or_else(|| after.map(str::to_owned)),
14023    ))
14024}
14025
14026/// The board, and every item on it this source reports.
14027#[derive(Clone)]
14028struct Board {
14029    id: String,
14030    fields: Value,
14031    items: Vec<Resolved>,
14032}
14033
14034/// What a write needs of the board and nothing more: its node id and its field
14035/// definitions, in the shape a read of the board's own `fields` gives them.
14036///
14037/// Deliberately no items. A write decides which item it writes, which parent it files
14038/// under and which far ends it names by reading each of them by its own id; this is the
14039/// half of the board those reads cannot carry, and holding no item is what keeps it from
14040/// ever being asked whether an item is there.
14041#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
14042struct BoardFields {
14043    id: BoardId,
14044    fields: Value,
14045}
14046
14047/// A board's node id: what a field write and `addProjectV2ItemById` address.
14048///
14049/// Never blank, because a blank one addresses no board — so an id GitHub answers blank is
14050/// refused where it is read, and one an item names blank is read as not named at all.
14051#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
14052#[serde(try_from = "String")]
14053struct BoardId(String);
14054
14055impl TryFrom<String> for BoardId {
14056    type Error = String;
14057
14058    /// The same refusal [`BoardId::parse`] makes, for an id read back from a kept context.
14059    fn try_from(id: String) -> Result<Self, Self::Error> {
14060        Self::parse(&id).map_err(|error| error.to_string())
14061    }
14062}
14063
14064/// Where one write left its item, for the record the rest of the command reads it out of.
14065///
14066/// A named record rather than a tuple because the update arm and the create arm each fill
14067/// all four, and two `Option`s of different meaning side by side in a tuple are two
14068/// positions a reader has to count.
14069struct Landed {
14070    /// The issue's own node id, which is the [`NativeId`] this source reports.
14071    content_id: NativeId,
14072    /// The board item's id, which is what a field write addresses — `None` for an issue its
14073    /// create filed on the board itself, whose board item GitHub adds after answering and
14074    /// [`TaskSource::finish_writes`] reads.
14075    // llmlint: ignore[invalid_states_unrepresentable] This field and the one below are `Resolved::item_id` and `Resolved::url` carried out of one call: the update arm assigns them from an existing `Resolved` and the whole record is assigned straight back into one. A newtype introduced here alone would be wrapped at both of those boundaries and unwrapped at every use, and would make this private record disagree with the type the same values have on the struct they come from and return to. Where the board item id gets a newtype is on `Resolved`, which is the contract's own shape and not this change's to move.
14076    item_id: Option<String>,
14077    /// The web address GitHub gave the issue, when it gave one.
14078    // llmlint: ignore[invalid_states_unrepresentable] The answer `Resolved::url` and the contract's `Task::url` already record: a web address this source never parses, resolves or compares — it reads GitHub's string and hands it back, and `Location::Url` is where the contract gives it a shape. Validating it here would have this plugin decide what GitHub may call an address.
14079    url: Option<String>,
14080    /// The issue's number on its repository, when GitHub reported one.
14081    number: Option<u64>,
14082}
14083
14084impl BoardId {
14085    fn parse(id: &str) -> Result<Self, SourceError> {
14086        if id.trim().is_empty() {
14087            return Err(SourceError::Malformed {
14088                message: "GitHub named a board with a blank node id".into(),
14089            });
14090        }
14091        Ok(Self(id.to_owned()))
14092    }
14093
14094    fn as_str(&self) -> &str {
14095        &self.0
14096    }
14097}
14098
14099impl Board {
14100    fn field<'a>(fields: &'a Value, name: &str) -> Result<Option<&'a Value>, SourceError> {
14101        complete_connection(fields, "project fields", NESTED_PAGE_SIZE)?;
14102        let nodes = fields
14103            .get("nodes")
14104            .and_then(Value::as_array)
14105            .ok_or_else(|| SourceError::Malformed {
14106                message: "GitHub project fields.nodes is not an array".into(),
14107            })?;
14108        Ok(nodes
14109            .iter()
14110            .find(|field| field.get("name").and_then(Value::as_str) == Some(name)))
14111    }
14112}
14113
14114/// One board item, resolved into everything this source reports about it.
14115///
14116/// Serializable because it is what [`TaskSource::write_context`] hands the store's cache and
14117/// [`TaskSource::prime_write`] takes back — see [`expected`].
14118#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
14119struct Resolved {
14120    item_id: String,
14121    id: NativeId,
14122    content_kind: ContentKind,
14123    kind: BoardKind,
14124    title: String,
14125    body: Option<String>,
14126    /// The body exactly as GitHub holds it, metadata slot and all, which is what a write
14127    /// that changes the slot alone has to keep byte for byte outside it.
14128    raw_body: Option<String>,
14129    status: Status,
14130    /// The name of the board `Status` option this item sits in, as the board spells it.
14131    option: Option<String>,
14132    /// What its `Priority` field says, read through this instance's mapping.
14133    priority: HeldPriority,
14134    /// Whether this item's issue is closed. A draft has no such state and is never closed.
14135    closed: bool,
14136    /// GitHub's reason for a closed issue's closure, as it spells it — `None` for an open
14137    /// issue, a draft, and an issue closed before GitHub recorded reasons.
14138    #[serde(default)]
14139    reason: Option<String>,
14140    /// The tasks this one delivers, read out of its slot. Empty for anything not a task.
14141    delivers: Vec<TaskRef>,
14142    /// Every task that delivers this one, read out of its slot. Empty for anything not a
14143    /// task.
14144    delivered_by: Vec<TaskRef>,
14145    labels: Vec<Label>,
14146    parent: Option<NativeId>,
14147    /// The issue's GitHub parent on a source reading sub-issues as children (`sub_issues:
14148    /// parent`), where [`Self::parent`] — the project it is filed under — is always `None`.
14149    #[serde(default)]
14150    issue_parent: Option<NativeId>,
14151    // llmlint: ignore[invalid_states_unrepresentable] The write side's reason, read back: this is the engine's qualified id, taken out of a board text field and handed on untouched. A newtype here would have this plugin define the syntax of an id `docs/metadata.md` says no plugin ever constructs or interprets.
14152    origin: Option<String>,
14153    /// What each board text field this instance projects metadata onto holds for this item,
14154    /// by field name — only the fields holding a value, an empty text included. What a write compares the
14155    /// item's metadata against, so a field already holding its value is not written again;
14156    /// never read back as metadata, which the slot alone reports.
14157    projected: BTreeMap<String, String>,
14158    /// The issue's own number on its repository, as GitHub reports it.
14159    ///
14160    /// `None` in exactly two cases: a draft, which has no number at all — `DraftIssue`
14161    /// declares none, and a draft is not filed in a repository to be numbered by one — and
14162    /// an issue this run created whose creating mutation answered without one, which is a
14163    /// response GitHub's own schema says cannot happen and which a landed write is not
14164    /// worth failing over. An `Issue` read off the board always has one.
14165    number: Option<u64>,
14166    url: Option<String>,
14167    created_at: Option<DateTime<Utc>>,
14168    updated_at: Option<DateTime<Utc>>,
14169    /// When the board item itself last changed — what a board field write moves — when the
14170    /// read that reached it said.
14171    item_updated_at: Option<DateTime<Utc>>,
14172    /// How many comments the issue holds, when the read that reached it said.
14173    comment_count: Option<u64>,
14174    /// How many relationship events the issue's timeline holds — every dependency, as
14175    /// `blockedBy` or `blocking`, and every project membership, as its parent, added or
14176    /// removed — when the read that reached it said.
14177    relationship_events: Option<u64>,
14178    /// The server's clock on the response that read it — its `Date` header — when the
14179    /// response carried one.
14180    served_at: Option<DateTime<Utc>>,
14181    /// The digest of its [`change_token::Facets`] — its own kind, its board field values and
14182    /// its labels — when the read that reached it carried all three whole.
14183    #[serde(default)]
14184    facets: Option<change_token::FacetsDigest>,
14185    own_repository: Option<Repository>,
14186    repositories: Vec<Repository>,
14187    classification: Classification,
14188    slot: BTreeMap<String, Value>,
14189    /// The node id of the board this item sits on, when the read that reached it said.
14190    board_id: Option<String>,
14191    /// The definition of every board field this item holds a value of, in the shape a read
14192    /// of the board's own `fields` gives one.
14193    ///
14194    /// Only the fields this item has a value in: a field it holds nothing of is not here,
14195    /// which says nothing about whether the board has it.
14196    fields: Vec<Value>,
14197    /// Every field the board this item sits on defines, as its own read of the board's
14198    /// `fields` gives them — when the read that reached the item carried them, which a read
14199    /// of it by its own id does. What a write of it needs of the board, then, needs no read
14200    /// of the board.
14201    board_fields: Option<Value>,
14202    /// The far ends of this issue's whole `blockedBy` connection, each as a dependency read
14203    /// selects one — when the read that reached it carried the connection to its end, which a
14204    /// read of it by its own id does for any issue blocked by no more than a page. What a
14205    /// write reconciles that relationship against, and what a read of its forward edges in
14206    /// the same command answers with.
14207    blocked_by: Option<Vec<Value>>,
14208    /// Every person the item is assigned to, by login in the order GitHub answered them — read
14209    /// only by a source opted in to assignees, and `None` for any other, and for a record no
14210    /// read or write of this process showed them on.
14211    #[serde(default)]
14212    assignees: Option<Vec<String>>,
14213}
14214
14215impl Resolved {
14216    /// The board this item's own read names it on, when that read named one this source can
14217    /// address.
14218    fn named_board(&self) -> Option<BoardId> {
14219        self.board_id
14220            .as_deref()
14221            .and_then(|id| BoardId::parse(id).ok())
14222    }
14223
14224    /// The board's id and every field it defines, when the read that reached this item
14225    /// carried both — which a read of it by its own id does.
14226    fn carried_board(&self) -> Option<BoardFields> {
14227        Some(BoardFields {
14228            id: self.named_board()?,
14229            fields: self.board_fields.clone()?,
14230        })
14231    }
14232
14233    /// Whether this item holds a value of the board field called `name`, and so carries
14234    /// that field's definition. `false` says nothing about whether the board has the field.
14235    fn defines(&self, name: &str) -> bool {
14236        self.fields
14237            .iter()
14238            .any(|field| field.get("name").and_then(Value::as_str) == Some(name))
14239    }
14240
14241    /// The metadata a caller sees: their own keys, plus the copy origin this source keeps
14242    /// in a field of its own, and none of the five keys that are only an encoding.
14243    ///
14244    /// The two delivery keys are left out for every kind, not only for a task: they are
14245    /// the encoding of [`Task::delivers`] and [`Task::delivered_by`], and a project or a
14246    /// document carrying one holds nothing a caller's own metadata could mean by it.
14247    fn metadata(&self) -> BTreeMap<String, Value> {
14248        let mut metadata = self.slot.clone();
14249        metadata.remove(Repository::METADATA_KEY);
14250        metadata.remove(DependencyEdge::RECORDED_KEY);
14251        metadata.remove(ItemKind::METADATA_KEY);
14252        metadata.remove(TaskRef::DELIVERS_KEY);
14253        metadata.remove(TaskRef::DELIVERED_BY_KEY);
14254        metadata.remove(Classification::METADATA_KEY);
14255        // The board field is the origin, and the body's copy of it is only a mirror for the
14256        // issue search to find: an item whose field holds none has none, whatever its body
14257        // says, so no reader ever sees two answers.
14258        metadata.remove(ORIGIN_KEY);
14259        if let Some(origin) = &self.origin {
14260            metadata.insert(ORIGIN_KEY.to_owned(), Value::String(origin.clone()));
14261        }
14262        metadata
14263    }
14264
14265    /// Where this item is, as a link a reader can open.
14266    ///
14267    /// A board is a hosted place and every issue on it has a web address, so that address
14268    /// is what "where is this?" means here — and [`Location::Url`] is what says which kind
14269    /// of place it is, so a reader knows to open it rather than to read a file out. It
14270    /// does not replace or derive from `url`: the field goes on reporting exactly what it
14271    /// reported before, and this says what that address *is*.
14272    ///
14273    /// An item GitHub gave no `url` for — a draft has none — reports no location at all
14274    /// rather than a third variant, which is the contract's "the source did not say". An
14275    /// issue this run created is not one of those: its address comes back from the
14276    /// creating mutation, so it is somewhere a reader can open from the moment it exists
14277    /// rather than from whenever the board read catches up.
14278    fn location(&self) -> Option<Location> {
14279        self.url.clone().map(Location::Url)
14280    }
14281
14282    /// The short handle this board's backend shows people for a task: the issue's number
14283    /// alone, as a decimal string.
14284    ///
14285    /// The number alone rather than `owner/repo#1043`, because that is the contract's
14286    /// value for this backend. A draft has no number and so no handle, which is the
14287    /// contract's *absent* rather than a handle of some other shape — and the native
14288    /// [`Task::id`] here is the issue's GraphQL node id, which this neither replaces nor
14289    /// derives from.
14290    fn key(&self) -> Option<String> {
14291        self.number.map(|number| number.to_string())
14292    }
14293
14294    /// This item's change token — see [`change_token`] — or `None` when the read that
14295    /// reached it did not carry all six of its parts, which a draft never does, did not say
14296    /// when GitHub served it, or found it changed too recently to have settled.
14297    fn version(&self) -> Option<String> {
14298        let parts = self.token_parts()?;
14299        change_token::settled(parts.issue, parts.item, self.served_at?)
14300            .then(|| change_token::spell(&parts))
14301    }
14302
14303    /// The change token this item, read just after a write of it, holds now — whether or not it
14304    /// has settled: what a written task's `version` answers (see
14305    /// [`GitHubProjectsSource::written_tokens`]), spelled from the parts a later read spells its
14306    /// token from.
14307    fn written_version(&self) -> Option<String> {
14308        self.token_parts().map(|parts| change_token::spell(&parts))
14309    }
14310
14311    /// Every part of this item's change token, or `None` when the read that reached it did not
14312    /// carry them all — a draft never does.
14313    fn token_parts(&self) -> Option<change_token::Parts> {
14314        match self.content_kind {
14315            ContentKind::Issue => Some(change_token::Parts {
14316                issue: self.updated_at?,
14317                item: self.item_updated_at?,
14318                comments: self.comment_count?,
14319                relationships: self.relationship_events?,
14320                facets: self.facets.clone()?,
14321                repository: self.own_repository.clone()?,
14322            }),
14323            ContentKind::DraftIssue => None,
14324        }
14325    }
14326
14327    /// Whether its `Priority` field holds a value at all, mapped or not.
14328    fn holds_priority(&self) -> bool {
14329        self.priority != HeldPriority::Read(Priority::None)
14330    }
14331
14332    /// The task this item is.
14333    ///
14334    /// Fails for an item whose `Priority` field holds an option the mapping does not name:
14335    /// reading that as a level would be a guess, and reading it as `none` would let the next
14336    /// copy clear a priority a person set.
14337    fn task(&self) -> Result<Task, SourceError> {
14338        let priority = match &self.priority {
14339            HeldPriority::Read(priority) => *priority,
14340            HeldPriority::Unmapped(option) => {
14341                return Err(SourceError::Malformed {
14342                    message: format!(
14343                        "task {}{} sits in the board {PRIORITY_FIELD} option {option:?}, which \
14344                         this source's priority_mapping does not name, so its priority cannot be \
14345                         read; next: name {option:?} under priority_mapping, or move the item to \
14346                         a mapped option",
14347                        self.id,
14348                        self.number
14349                            .map(|number| format!(" (#{number})"))
14350                            .unwrap_or_default()
14351                    ),
14352                });
14353            }
14354        };
14355        let metadata = self.metadata();
14356        Ok(Task {
14357            version: self.version(),
14358            id: self.id.clone(),
14359            key: self.key(),
14360            title: self.title.clone(),
14361            // The `## Links` section the engine rendered is stripped, so content round-trips.
14362            content: onetaskgraph_plugin_api::read_content(self.body.clone(), &metadata),
14363            status: self.status.clone(),
14364            priority,
14365            labels: self.labels.clone(),
14366            project: self.parent.clone(),
14367            url: self.url.clone(),
14368            location: self.location(),
14369            created_at: self.created_at,
14370            updated_at: self.updated_at,
14371            metadata,
14372            repositories: self.repositories.clone(),
14373            delivers: self.delivers.clone(),
14374            delivered_by: self.delivered_by.clone(),
14375            classification: self.classification,
14376            assignees: self.assignees.clone(),
14377        })
14378    }
14379
14380    fn project(&self) -> Project {
14381        Project {
14382            version: self.version(),
14383            id: self.id.clone(),
14384            title: self.title.clone(),
14385            content: self.body.clone(),
14386            status: self.status.clone(),
14387            labels: self.labels.clone(),
14388            url: self.url.clone(),
14389            location: self.location(),
14390            created_at: self.created_at,
14391            updated_at: self.updated_at,
14392            metadata: self.metadata(),
14393            repositories: self.repositories.clone(),
14394            classification: self.classification,
14395        }
14396    }
14397
14398    /// The same issue as a document: the project it is filed under, and no status and no
14399    /// dependencies, because a document is not work.
14400    fn document(&self) -> Document {
14401        Document {
14402            version: self.version(),
14403            id: self.id.clone(),
14404            title: self.title.clone(),
14405            content: self.body.clone(),
14406            project: self.parent.clone(),
14407            labels: self.labels.clone(),
14408            url: self.url.clone(),
14409            location: self.location(),
14410            created_at: self.created_at,
14411            updated_at: self.updated_at,
14412            metadata: self.metadata(),
14413            repositories: self.repositories.clone(),
14414            classification: self.classification,
14415        }
14416    }
14417}
14418
14419/// Where one targeted update moves an item's status, and which of its two halves move.
14420struct StatusMove {
14421    /// The board the item's `Status` field is on.
14422    board: BoardId,
14423    /// The `Status` field's id.
14424    field: String,
14425    /// The option's id.
14426    option: String,
14427    /// The option's name, as the board spells it.
14428    name: String,
14429    /// What the status asks of the issue's state.
14430    target: StatusTarget,
14431    /// The status the item reads as once it is there.
14432    landed: Status,
14433    /// Which of the status's two halves differ from what the item holds.
14434    moves: Moves,
14435}
14436
14437/// Which halves of an item's status one targeted update moves: its `Status` option, the open or
14438/// closed state of its issue, or both. A status neither half of which differs is no move at all,
14439/// and is not a value of this type.
14440#[derive(Clone, Copy, PartialEq, Eq)]
14441enum Moves {
14442    /// The option alone.
14443    Option,
14444    /// The issue's state alone: open, closed, or closed with another reason.
14445    State,
14446    /// Both.
14447    Both,
14448}
14449
14450impl Moves {
14451    /// What differs, or `None` when nothing does.
14452    const fn of(option: bool, state: bool) -> Option<Self> {
14453        match (option, state) {
14454            (true, true) => Some(Self::Both),
14455            (true, false) => Some(Self::Option),
14456            (false, true) => Some(Self::State),
14457            (false, false) => None,
14458        }
14459    }
14460
14461    /// Whether the option moves.
14462    const fn option(self) -> bool {
14463        matches!(self, Self::Option | Self::Both)
14464    }
14465
14466    /// Whether the issue's state moves.
14467    const fn state(self) -> bool {
14468        matches!(self, Self::State | Self::Both)
14469    }
14470}
14471
14472/// What one write is, and the status that comes with being it.
14473///
14474/// One value rather than a [`BoardKind`] beside an `Option<Status>`: a document has no
14475/// status and a task or a project always has one, so "a document carrying a status" and
14476/// "a task carrying none" are states a write cannot be in rather than states every use
14477/// site below has to defend against.
14478enum Written<'a> {
14479    /// A document, which is not work and so has no status at all.
14480    Document,
14481    /// A task or a project, and the status it is being written with.
14482    Work(ItemKind, &'a Status),
14483}
14484
14485impl Written<'_> {
14486    /// Which of the board's three kinds this write is.
14487    const fn kind(&self) -> BoardKind {
14488        match self {
14489            Self::Document => BoardKind::Document,
14490            Self::Work(kind, _) => BoardKind::Work(*kind),
14491        }
14492    }
14493
14494    /// The status this write carries. A document carries none, so a write of one says
14495    /// nothing about the issue's open or closed state and selects no board `Status`
14496    /// option.
14497    const fn status(&self) -> Option<&Status> {
14498        match self {
14499            Self::Document => None,
14500            Self::Work(_, status) => Some(status),
14501        }
14502    }
14503
14504    /// The status this write carries with the kind whose half of `status_mapping` it is
14505    /// written through.
14506    const fn work_status(&self) -> Option<(ItemKind, &Status)> {
14507        match self {
14508            Self::Document => None,
14509            Self::Work(kind, status) => Some((*kind, status)),
14510        }
14511    }
14512}
14513
14514/// The item being written, in the one shape all three write methods reach.
14515struct Incoming<'a> {
14516    written: Written<'a>,
14517    /// The title a person wrote. A document's goes onto the issue with
14518    /// [`DESIGN_TITLE_PREFIX`] put back, so a round trip returns the title that went in.
14519    title: &'a str,
14520    content: Option<&'a str>,
14521    assets: Option<&'a onetaskgraph_plugin_api::AssetWrite>,
14522    labels: &'a [Label],
14523    metadata: &'a BTreeMap<String, Value>,
14524    repositories: &'a [Repository],
14525    /// Recorded in the slot while private, and nowhere while public.
14526    classification: Classification,
14527    parent: Option<&'a NativeId>,
14528    /// [`Task::delivers`], already checked. Empty for a project or a document, which is
14529    /// what keeps either key out of their slot.
14530    delivers: &'a [TaskRef],
14531    /// [`Task::delivered_by`], already checked. Empty for a project or a document.
14532    delivered_by: &'a [TaskRef],
14533    /// [`Task::priority`], for a task written to an instance that holds one; `None` for a
14534    /// project, a document, and every write to an instance with no `priority_mapping` —
14535    /// which is what keeps such a write's requests exactly what they were before.
14536    priority: Option<Priority>,
14537    /// [`Task::assignees`] of a task written to a source opted in to them — the people it is
14538    /// to be assigned to, replacing whoever it holds — and `None` for everything else, which
14539    /// leaves an existing item's as they are and creates one unassigned.
14540    assignees: Option<&'a [String]>,
14541}
14542
14543/// What one write does to one projected metadata text field, by the field's id.
14544#[derive(Debug, Clone)]
14545enum ProjectionWrite {
14546    /// Write this text.
14547    Set {
14548        field: String, // llmlint: ignore[invalid_states_unrepresentable] A private opaque GraphQL field id passed straight back to GitHub, as `PriorityWrite`'s are; GitHub publishes no grammar for it.
14549        text: String,
14550    },
14551    /// Clear the field's value.
14552    Clear { field: String }, // llmlint: ignore[invalid_states_unrepresentable] As above.
14553}
14554
14555impl ProjectionWrite {
14556    /// Add this write to a field write's list of values and list of clears.
14557    fn join<'a>(&'a self, values: &mut Vec<(String, Value)>, clears: &mut Vec<&'a str>) {
14558        match self {
14559            Self::Set { field, text } => values.push((field.clone(), json!({"text": text}))),
14560            Self::Clear { field } => clears.push(field),
14561        }
14562    }
14563}
14564
14565/// What one write does to an item's `Priority` field.
14566enum PriorityWrite {
14567    /// Select this option of this field.
14568    Select {
14569        /// The `Priority` field's id.
14570        field: String,
14571        /// The mapped option's id.
14572        option: String,
14573    },
14574    /// Clear the field's value, which is what `none` is.
14575    Clear {
14576        /// The `Priority` field's id.
14577        field: String,
14578    },
14579}
14580
14581impl Incoming<'_> {
14582    /// The title this write puts on the issue.
14583    fn written_title(&self) -> String {
14584        match self.written {
14585            Written::Document => format!("{DESIGN_TITLE_PREFIX}{}", self.title),
14586            Written::Work(..) => self.title.to_owned(),
14587        }
14588    }
14589}
14590
14591#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
14592enum ContentKind {
14593    DraftIssue,
14594    Issue,
14595}
14596
14597/// What one board issue is: a document, or the work an [`ItemKind`] names.
14598///
14599/// A type of this source's own rather than an `ItemKind` with a third variant, because
14600/// `ItemKind` names what a dependency endpoint points at and nothing may point at a
14601/// document — the contract keeps a document out of that enum deliberately. Holding the
14602/// board's three answers in one value is what makes every place that asks "which is this?"
14603/// answer all three, rather than a `document: bool` beside a `kind` that means nothing for
14604/// two thirds of the board.
14605#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
14606enum BoardKind {
14607    /// An issue whose title begins [`DESIGN_TITLE_PREFIX`].
14608    Document,
14609    /// Every other issue, and every draft.
14610    Work(ItemKind),
14611}
14612
14613impl BoardKind {
14614    /// The kind of an item titled `title`, filed under a project or not, holding `sub_issues`
14615    /// sub-issues and carrying the kind marker `marked` in its slot.
14616    ///
14617    /// The design prefix is read *first*, before either of the two rules that separate a
14618    /// project from a task. A document is not work whatever sub-issues it has and whatever
14619    /// marker it carries, and reading the prefix later would make a design issue with none of
14620    /// either an empty project. Being a sub-issue wins outright over the rest, and no marker
14621    /// overrides it: an issue filed under a project is that project's task even when it has
14622    /// sub-issues of its own.
14623    fn of(title: &str, filed: bool, sub_issues: u64, marked: Option<ItemKind>) -> Self {
14624        if title.starts_with(DESIGN_TITLE_PREFIX) {
14625            Self::Document
14626        } else if filed {
14627            Self::Work(ItemKind::Task)
14628        } else if sub_issues > 0 || marked == Some(ItemKind::Project) {
14629            Self::Work(ItemKind::Project)
14630        } else {
14631            Self::Work(ItemKind::Task)
14632        }
14633    }
14634
14635    /// What the change token's facets call this kind.
14636    const fn facet(self) -> change_token::FacetKind {
14637        match self {
14638            Self::Document => change_token::FacetKind::Document,
14639            Self::Work(ItemKind::Project) => change_token::FacetKind::Project,
14640            Self::Work(ItemKind::Task) => change_token::FacetKind::Task,
14641        }
14642    }
14643
14644    /// Whose half of `status_mapping` an item of this kind reads its status through. A
14645    /// document has no status of its own, so the task half stands in for whatever the issue
14646    /// holds; nothing reports it.
14647    const fn status_kind(self) -> ItemKind {
14648        match self {
14649            Self::Document => ItemKind::Task,
14650            Self::Work(kind) => kind,
14651        }
14652    }
14653
14654    /// How a refusal names this kind to the person reading it.
14655    const fn describes(self) -> &'static str {
14656        match self {
14657            Self::Document => "document",
14658            Self::Work(kind) => kind.marker(),
14659        }
14660    }
14661}
14662
14663/// Whether `labels` satisfies `filter`, matching by name, case-insensitively.
14664///
14665/// This is the local Markdown source's `labels_match`, spelled the same way on purpose:
14666/// the shared cross-source journeys assert one answer to one question, so two sources
14667/// that disagree about what "carries the label bug" means fail them.
14668fn labels_match(labels: &[Label], filter: &LabelFilter) -> bool {
14669    let holds = |name: &String| {
14670        labels
14671            .iter()
14672            .any(|label| label.name.eq_ignore_ascii_case(name))
14673    };
14674    (filter.any_of.is_empty() || filter.any_of.iter().any(holds))
14675        && filter.all_of.iter().all(holds)
14676        && !filter.none_of.iter().any(holds)
14677}
14678
14679/// Whether `category` is one of `statuses`. An empty list is unfiltered rather than
14680/// "keeps nothing", which is what lets a `Vec<StatusCategory>` spell no filter at all.
14681fn status_matches(category: StatusCategory, statuses: &[StatusCategory]) -> bool {
14682    statuses.is_empty() || statuses.contains(&category)
14683}
14684
14685/// Whether `title`/`content` satisfies `query`, matching case-insensitively.
14686///
14687/// `content` is the item's own prose — the body with this source's trailing metadata
14688/// comment already taken off — so a search never matches an encoding the author of the
14689/// issue never wrote.
14690fn text_matches(title: &str, content: Option<&str>, query: &TextQuery) -> bool {
14691    let terms = query.terms.to_lowercase();
14692    let in_title = title.to_lowercase().contains(&terms);
14693    let in_content = content.is_some_and(|body| body.to_lowercase().contains(&terms));
14694    match query.fields {
14695        TextFields::Title => in_title,
14696        TextFields::Content => in_content,
14697        TextFields::TitleOrContent => in_title || in_content,
14698    }
14699}
14700
14701/// Whether `task` satisfies `query`, with `project` deciding the project predicate.
14702///
14703/// The project predicate is passed separately because a read narrowed to one project has
14704/// already answered it by asking *that project* for its own items — and re-applying it
14705/// there would compare the caller's selector, which may be a project's **name**, against
14706/// the id of the project that name resolved to, and keep nothing. Every other read passes
14707/// `query.project` and applies it here, which is what keeps `projects` a predicate this
14708/// source really does apply.
14709fn task_matches(task: &Task, query: &TaskQuery, project: &ProjectFilter) -> bool {
14710    labels_match(&task.labels, &query.labels)
14711        && status_matches(task.status.category, &query.statuses)
14712        && (query.priorities.is_empty() || query.priorities.contains(&task.priority))
14713        && match project {
14714            ProjectFilter::Any => true,
14715            ProjectFilter::Orphans => task.project.is_none(),
14716            ProjectFilter::Is(id) => task.project.as_ref() == Some(id),
14717        }
14718        && query
14719            .text
14720            .as_ref()
14721            .is_none_or(|text| text_matches(&task.title, task.content.as_deref(), text))
14722        // Against the parsed metadata slot, and against the origin field, which is where
14723        // `Resolved::metadata` reads each of them from.
14724        && query.metadata_matches(&task.metadata)
14725        && query.origin_matches(&task.metadata)
14726}
14727
14728fn project_matches(project: &Project, query: &ProjectQuery) -> bool {
14729    labels_match(&project.labels, &query.labels)
14730        && status_matches(project.status.category, &query.statuses)
14731        && query
14732            .text
14733            .as_ref()
14734            .is_none_or(|text| text_matches(&project.title, project.content.as_deref(), text))
14735}
14736
14737/// The same three predicates a task query carries, minus the status filter.
14738///
14739/// A document is not work, so it has no status for one to compare against and the query
14740/// type carries none. The project predicate is the same one — a design issue filed under a
14741/// project issue is in that project, and one filed under nothing is in none — so it is
14742/// spelled the same way here rather than answered differently.
14743fn document_matches(document: &Document, query: &DocumentQuery, project: &ProjectFilter) -> bool {
14744    labels_match(&document.labels, &query.labels)
14745        && match project {
14746            ProjectFilter::Any => true,
14747            ProjectFilter::Orphans => document.project.is_none(),
14748            ProjectFilter::Is(id) => document.project.as_ref() == Some(id),
14749        }
14750        && query
14751            .text
14752            .as_ref()
14753            .is_none_or(|text| text_matches(&document.title, document.content.as_deref(), text))
14754}
14755
14756/// Why a GitHub item's change token does not vouch for its forward edges.
14757///
14758/// A forward edge names its far end and that far end's kind, and the near item's token moves
14759/// with the edges it holds but says nothing of the far ends themselves: a far end turning from a
14760/// task into a project when it gains a sub-issue, retitled into a document, or deleted moves
14761/// nothing the near token reads, so an edge kept at the near version could name a far end that
14762/// is no longer what it said.
14763const FAR_ENDS_UNCOVERED: &str = "a github item's change token does not attest a far end's kind, \
14764     whether it became a document, or its deletion, so its forward edges are always read from \
14765     github";
14766
14767/// The issue-search qualifier that keeps open issues alone, which a status filter naming only
14768/// categories an open issue reads as narrows a board-scoped search with.
14769const OPEN_QUALIFIER: &str = "is:open";
14770
14771/// What the board's open items are held under among the narrowed answers of one command — a
14772/// key no [`Narrowing`], each `origin …` or `search …`, can spell.
14773const OPEN_ITEMS_KEY: &str = "items is:open";
14774
14775/// The board filter `task status reconcile` reads the board through: closed items alone.
14776const CLOSED_FILTER: &str = "is:closed";
14777
14778/// The variables of one [`graphql::ISSUES_BY_REFERENCE`] request for `batch`: each slot names
14779/// one reference, and a slot the batch has none for names its last one again.
14780fn reference_batch(batch: &[IssueRef]) -> Value {
14781    let mut variables = serde_json::Map::new();
14782    for slot in 0..REFERENCE_BATCH {
14783        let issue = batch.get(slot).or(batch.last());
14784        variables.insert(format!("owner{slot}"), json!(issue.map(|i| &i.owner)));
14785        variables.insert(format!("name{slot}"), json!(issue.map(|i| &i.name)));
14786        variables.insert(format!("number{slot}"), json!(issue.map(|i| i.number)));
14787    }
14788    variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
14789    variables.insert("statusField".to_owned(), json!(STATUS_FIELD));
14790    variables.insert("duplicates".to_owned(), json!(true));
14791    Value::Object(variables)
14792}
14793
14794/// One issue an issue read by reference answered, in the shape every other read of an issue
14795/// hands its resolver: each board membership's `Status` value, read by name, as the one field
14796/// value that membership carries.
14797///
14798/// A membership's `status` is `null` when its card sits at no option — or on a board with no
14799/// field of that name — and otherwise an option value naming its option; anything else is not
14800/// an answer to this read, and is refused rather than read as a card at no option.
14801fn held_issue(issue: &Value) -> Result<Value, SourceError> {
14802    let malformed = |what: &str| SourceError::Malformed {
14803        message: format!("GitHub answered an issue read by reference with {what}"),
14804    };
14805    let mut issue = issue.clone();
14806    let nodes = issue
14807        .pointer_mut("/projectItems/nodes")
14808        .and_then(Value::as_array_mut)
14809        .ok_or_else(|| malformed("no list of board memberships"))?;
14810    for node in nodes {
14811        let node = node
14812            .as_object_mut()
14813            .ok_or_else(|| malformed("a board membership that is not an object"))?;
14814        let status = match node.get("status") {
14815            None => return Err(malformed("a board membership with no status member")),
14816            Some(Value::Null) => None,
14817            Some(status) if status.get("name").is_some_and(Value::is_string) => {
14818                Some(status.clone())
14819            }
14820            // A single-select value of another field type answers `{}`; only an option value
14821            // carries a name.
14822            Some(status) if status.as_object().is_some_and(serde_json::Map::is_empty) => None,
14823            Some(_) => return Err(malformed("a membership status that names no option")),
14824        };
14825        node.insert(
14826            "fieldValues".to_owned(),
14827            json!({"nodes": status.into_iter().collect::<Vec<_>>(),
14828                   "pageInfo": {"hasNextPage": false}}),
14829        );
14830    }
14831    Ok(issue)
14832}
14833
14834/// The issue one slot of a read by reference answered, `None` when GitHub answered that
14835/// slot's repository or issue `null` — which [`GitHubProjectsSource::answer_unresolved`]
14836/// admitted only beside a `NOT_FOUND` naming that very slot — and a refusal when the answer
14837/// leaves the slot, or its `issue` member, out: an answer missing a member is malformed rather
14838/// than a reference nothing holds.
14839fn referenced_issue(data: &Value, slot: usize) -> Result<Option<&Value>, SourceError> {
14840    let alias = format!("r{slot}");
14841    let repository = data.get(&alias).ok_or_else(|| SourceError::Malformed {
14842        message: format!("GitHub answered a read by reference with no {alias}"),
14843    })?;
14844    if repository.is_null() {
14845        return Ok(None);
14846    }
14847    let issue = repository
14848        .get("issue")
14849        .ok_or_else(|| SourceError::Malformed {
14850            message: format!("GitHub answered {alias} of a read by reference with no issue"),
14851        })?;
14852    if issue.is_null() {
14853        return Ok(None);
14854    }
14855    // `Repository.issue` is typed `Issue`, so anything else is not an answer to this read.
14856    if optional_str(issue, "__typename")? != Some("Issue") {
14857        return Err(SourceError::Malformed {
14858            message: format!(
14859                "GitHub answered {alias} of a read by reference with an issue whose __typename \
14860                 is not Issue"
14861            ),
14862        });
14863    }
14864    Ok(Some(issue))
14865}
14866
14867/// A closure reason as a person reads it: `NOT_PLANNED` as `not planned`.
14868fn spoken_reason(reason: &str) -> String {
14869    reason.to_ascii_lowercase().replace('_', " ")
14870}
14871
14872impl GitHubProjectsSource {
14873    /// Every task and project of this board whose card contradicts its issue's closure, each
14874    /// judged against its own kind's half of `status_mapping`, read through the board's own
14875    /// `is:closed` filter, page by page — never the board's unfiltered `items`.
14876    ///
14877    /// Each item the filter answers is confirmed from its own node: an open one, one whose
14878    /// closure reads `unknown`, and one whose card is already in line are left out whatever
14879    /// the filter let through. The board's fields ride along and are held for the option
14880    /// writes that follow, so those need no read of the board.
14881    async fn contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
14882        let mut after: Option<String> = None;
14883        let mut found = Vec::new();
14884        loop {
14885            let data = self
14886                .graphql(
14887                    graphql::CLOSED_ITEMS,
14888                    json!({"owner":self.owner,"number":self.project_number,
14889                           "first":MAX_PAGE_SIZE,"after":after,"filter":CLOSED_FILTER,
14890                           "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
14891                )
14892                .await?;
14893            let board = data
14894                .pointer("/closedItems/projectV2")
14895                .filter(|value| !value.is_null())
14896                .ok_or_else(|| SourceError::Refused {
14897                    message: format!(
14898                        "GitHub project {}/{} was not found or is not visible to the token",
14899                        self.owner, self.project_number
14900                    ),
14901                })?;
14902            *self.fields_cache()? = Some(BoardFields {
14903                id: BoardId::parse(required_str(board, "id")?)?,
14904                fields: board.get("fields").cloned().unwrap_or(Value::Null),
14905            });
14906            let items = board.get("items").ok_or_else(|| SourceError::Malformed {
14907                message: "GitHub project closed items are missing".into(),
14908            })?;
14909            for item in items
14910                .get("nodes")
14911                .and_then(Value::as_array)
14912                .ok_or_else(|| SourceError::Malformed {
14913                    message: "GitHub project items.nodes is not an array".into(),
14914                })?
14915            {
14916                let Some(resolved) = self.resolve(item)? else {
14917                    continue;
14918                };
14919                let BoardKind::Work(kind) = resolved.kind else {
14920                    continue;
14921                };
14922                let Some((closed_as, name)) = self.statuses.contradicted(
14923                    kind,
14924                    resolved.option.as_deref(),
14925                    resolved.closed,
14926                    resolved.reason.as_deref(),
14927                ) else {
14928                    continue;
14929                };
14930                found.push(StatusContradiction {
14931                    closed_as,
14932                    to: name.to_owned(),
14933                    option: resolved.option.clone(),
14934                    item: match kind {
14935                        ItemKind::Task => ContradictedItem::Task(resolved.task()?),
14936                        ItemKind::Project => ContradictedItem::Project(resolved.project()),
14937                    },
14938                });
14939            }
14940            let info = items
14941                .get("pageInfo")
14942                .ok_or_else(|| SourceError::Malformed {
14943                    message: "GitHub project items have no pageInfo".into(),
14944                })?;
14945            if !required_bool(info, "hasNextPage")? {
14946                return Ok(found);
14947            }
14948            let next = required_str(info, "endCursor")?;
14949            validate_cursor_progress(after.as_deref(), next)?;
14950            after = Some(next.to_owned());
14951        }
14952    }
14953
14954    /// What this board holds for each issue in `issues`, once each in the order given, read
14955    /// [`REFERENCE_BATCH`] references at a time — and nothing else of the board.
14956    ///
14957    /// An issue GitHub cannot find for this source's credential, and one with no item on this
14958    /// board, are both absent. A closure that already says the work will not be done here —
14959    /// not planned, duplicate — is skipped: a landing does not overrule it. An item closed as
14960    /// completed whose card sits at its kind's `done` option is unchanged, and every other item
14961    /// is due a `done` write. A project item — a plan's home card, its issue holding the plan's
14962    /// tasks as sub-issues — is held under exactly these rules, judged against the project
14963    /// kind's half of `status_mapping`.
14964    async fn holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
14965        let mut distinct: Vec<IssueRef> = Vec::with_capacity(issues.len());
14966        for issue in issues {
14967            if !distinct.contains(issue) {
14968                distinct.push(issue.clone());
14969            }
14970        }
14971        let done = |kind: ItemKind| {
14972            self.statuses
14973                .target(kind, StatusCategory::Done)
14974                .option()
14975                .unwrap_or("Done")
14976                .to_owned()
14977        };
14978        // GitHub numbers an issue with a GraphQL `Int`, a signed 32-bit value, so a reference past
14979        // its range names no issue any repository can hold: it is answered absent and never sent,
14980        // where binding it would have GitHub refuse the whole batch.
14981        let readable: Vec<IssueRef> = distinct
14982            .iter()
14983            .filter(|issue| i32::try_from(issue.number).is_ok())
14984            .cloned()
14985            .collect();
14986        let mut holdings = Vec::with_capacity(readable.len());
14987        for batch in readable.chunks(REFERENCE_BATCH) {
14988            let data = self
14989                .graphql(graphql::ISSUES_BY_REFERENCE, reference_batch(batch))
14990                .await?;
14991            for (slot, issue) in batch.iter().enumerate() {
14992                let node = referenced_issue(&data, slot)?;
14993                let resolved = match node {
14994                    Some(node) => self.resolve_issue_as(&held_issue(node)?, false).await?,
14995                    None => None,
14996                };
14997                // A task and a project are both held; a document is not work, so nothing is.
14998                let Some((item, kind)) = resolved.and_then(|item| match item.kind {
14999                    BoardKind::Work(kind) => Some((item, kind)),
15000                    BoardKind::Document => None,
15001                }) else {
15002                    holdings.push(IssueHolding {
15003                        issue: issue.clone(),
15004                        completion: Completion::Absent,
15005                    });
15006                    continue;
15007                };
15008                let task = match kind {
15009                    ItemKind::Task => {
15010                        let held = item.task()?;
15011                        HeldTask {
15012                            id: held.id,
15013                            kind,
15014                            option: item.option.clone(),
15015                            classification: held.classification,
15016                            repositories: held.repositories,
15017                            delivers: held.delivers,
15018                        }
15019                    }
15020                    // A project delivers no task, so what its write keeps in step is nothing.
15021                    ItemKind::Project => {
15022                        let held = item.project();
15023                        HeldTask {
15024                            id: held.id,
15025                            kind,
15026                            option: item.option.clone(),
15027                            classification: held.classification,
15028                            repositories: held.repositories,
15029                            delivers: Vec::new(),
15030                        }
15031                    }
15032                };
15033                let done = done(kind);
15034                let completion = match (item.closed, item.reason.as_deref()) {
15035                    (true, Some(reason @ ("NOT_PLANNED" | "DUPLICATE"))) => Completion::Skipped {
15036                        task,
15037                        reason: format!("closed as {}", spoken_reason(reason)),
15038                    },
15039                    (true, None | Some("COMPLETED"))
15040                        if item
15041                            .option
15042                            .as_deref()
15043                            .is_some_and(|option| option.eq_ignore_ascii_case(&done)) =>
15044                    {
15045                        Completion::Unchanged { task }
15046                    }
15047                    _ => {
15048                        let kept = item.clone();
15049                        self.held_cache
15050                            .lock()
15051                            .map_err(|_| SourceError::Unavailable {
15052                                message: "items read by issue reference were left \
15053                                          inconsistent; run the command again"
15054                                    .into(),
15055                            })?
15056                            .insert(kept.id.clone(), kept);
15057                        Completion::Due {
15058                            task,
15059                            to: done.clone(),
15060                        }
15061                    }
15062                };
15063                holdings.push(IssueHolding {
15064                    issue: issue.clone(),
15065                    completion,
15066                });
15067            }
15068        }
15069        let mut read = holdings.into_iter();
15070        let mut answered = Vec::with_capacity(distinct.len());
15071        for issue in distinct {
15072            if i32::try_from(issue.number).is_ok() {
15073                answered.push(read.next().ok_or_else(|| SourceError::Malformed {
15074                    message: format!("no holding was read for {issue}"),
15075                })?);
15076            } else {
15077                answered.push(IssueHolding {
15078                    issue,
15079                    completion: Completion::Absent,
15080                });
15081            }
15082        }
15083        Ok(answered)
15084    }
15085}
15086
15087#[async_trait::async_trait]
15088impl TaskSource for GitHubProjectsSource {
15089    fn kind(&self) -> &'static str {
15090        KIND
15091    }
15092    /// GitHub's issue search, which narrows a read of the comments made since an instant, is
15093    /// an index behind the writes it indexes — the credentialed lane has watched it miss a newly
15094    /// commented issue for thirty seconds — so a watermark is set back by
15095    /// [`COMMENT_SEARCH_LAG`], four times that.
15096    fn comment_consistency_window(&self) -> std::time::Duration {
15097        COMMENT_SEARCH_LAG
15098    }
15099    /// The `Date` of the last answer GitHub gave this source.
15100    fn served_at(&self) -> Option<DateTime<Utc>> {
15101        *self
15102            .last_served
15103            .lock()
15104            .unwrap_or_else(std::sync::PoisonError::into_inner)
15105    }
15106    fn attach_body_markup(&self, markup: onetaskgraph_plugin_api::SharedBodyMarkup) {
15107        let _ = self.body_markup.set(markup);
15108    }
15109    fn order_versions(&self, a: &str, b: &str) -> Option<std::cmp::Ordering> {
15110        change_token::order(a, b)
15111    }
15112    /// A task's fields and comments: §4.13d of `docs/plugin-protocol.md` states, member by
15113    /// member, the change each part of the token moves for. Not its forward edges — see
15114    /// [`FAR_ENDS_UNCOVERED`].
15115    fn version_coverage(&self) -> VersionCoverage {
15116        VersionCoverage {
15117            forward_edges: Coverage::Uncovered {
15118                reason: FAR_ENDS_UNCOVERED.to_owned(),
15119            },
15120            ..VersionCoverage::whole()
15121        }
15122    }
15123    /// Every part, for a copy's skip: the relationship count moves for an edge added or removed
15124    /// and for a far end deleted, so the token sees every change to a task's edges but one — a
15125    /// far end's own kind flipping, by gaining a sub-issue or being retitled into a document,
15126    /// which `spike-coverage` measured stale 1 of 1. A skipping recopy does not carry that, and
15127    /// the next copy that reads the task does (`docs/plugin-protocol.md` §4.13d).
15128    // llmlint: ignore[names_match_behavior] The manager's ruling (c-d7838f2c) keeps 0.6.0's GitHub skip and has this plugin state that bounded claim through the coverage it reports, with the bound documented here, in §4.13d and by the copy_skip journey; a separate bounded representation would be a contract change beyond a defaulted addition, which the ruling reserves for the contract's owner, and a follow-up is drafted for a far-end-aware skip.
15129    fn copy_version_coverage(&self) -> VersionCoverage {
15130        VersionCoverage::whole()
15131    }
15132    /// A project's fields, and not its forward edges, for the same reason a task's are not.
15133    fn project_version_coverage(&self) -> ProjectVersionCoverage {
15134        ProjectVersionCoverage {
15135            fields: Coverage::Covered,
15136            forward_edges: Coverage::Uncovered {
15137                reason: FAR_ENDS_UNCOVERED.to_owned(),
15138            },
15139        }
15140    }
15141    /// A document's fields and the manifest of its image assets, which its metadata slot
15142    /// records: both are the issue's body, whose every edit moves the token's issue time.
15143    fn document_version_coverage(&self) -> DocumentVersionCoverage {
15144        DocumentVersionCoverage::whole()
15145    }
15146    fn write_context(&self, id: &NativeId) -> Option<Value> {
15147        self.context_of(id)
15148    }
15149    fn board_context(&self) -> Option<Value> {
15150        self.board_context_held()
15151    }
15152    fn prime_write(&self, id: &NativeId, context: &Value, board: Option<&Value>) -> bool {
15153        self.prime(id, context, board)
15154    }
15155    fn unprime(&self, id: &NativeId) {
15156        self.unprime_held(id);
15157    }
15158    fn placement_context(&self) -> Option<Value> {
15159        self.placement_held()
15160    }
15161    fn prime_placement(&self, context: &Value) -> bool {
15162        self.prime_placement_held(context)
15163    }
15164    fn written_context(&self, id: &NativeId) -> Option<Value> {
15165        self.written_held(id)
15166    }
15167    fn prime_written(&self, id: &NativeId, context: &Value, task: &Task) -> bool {
15168        self.prime_written_held(id, context, task)
15169    }
15170    fn begin_journal(&self) {
15171        self.expected.begin();
15172    }
15173    fn end_journal(&self) -> Option<WriteJournal> {
15174        Some(self.expected.end())
15175    }
15176    fn capabilities(&self) -> Capabilities {
15177        Capabilities {
15178            projects: Support::Native,
15179            documents: Support::Native,
15180            comments: Support::Native,
15181            assets: Support::Native,
15182            priority: if self.priorities.is_some() {
15183                Support::Native
15184            } else {
15185                Support::Unsupported
15186            },
15187            filter_by_priority: Support::Native,
15188            filter_by_comment_activity: Support::Native,
15189            filter_by_metadata: Support::Native,
15190            filter_by_origin: Support::Native,
15191            reconcile_status: Support::Native,
15192            complete_by_issue: Support::Native,
15193            orphan_tasks: Support::Native,
15194            filter_by_label: Support::Native,
15195            filter_by_status: Support::Native,
15196            search_title: Support::Native,
15197            search_content: Support::Native,
15198            task_dependencies: DependencySupport::BothDirections,
15199            project_dependencies: DependencySupport::BothDirections,
15200            max_page_size: MAX_PAGE_SIZE,
15201            assignees: if self.assignees {
15202                Support::Native
15203            } else {
15204                Support::Unsupported
15205            },
15206        }
15207    }
15208    async fn visibility(
15209        &self,
15210        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15211    ) -> Result<onetaskgraph_plugin_api::Visibility, SourceError> {
15212        self.write_visibility(target).await
15213    }
15214    async fn visibility_with_project(
15215        &self,
15216        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15217        project: &onetaskgraph_plugin_api::WriteTarget<'_>,
15218    ) -> Result<onetaskgraph_plugin_api::Visibility, SourceError> {
15219        self.write_visibility_with_project(target, project).await
15220    }
15221    fn declare_visibility(&self, declared: onetaskgraph_plugin_api::Visibility) {
15222        self.declared_private.store(
15223            declared == onetaskgraph_plugin_api::Visibility::Private,
15224            std::sync::atomic::Ordering::SeqCst,
15225        );
15226    }
15227    fn scope_visibility<'a>(
15228        &'a self,
15229        operation: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>>,
15230    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>> {
15231        self.scope_visibility_reads(operation)
15232    }
15233
15234    /// Where a create of `target` would file its issue, by [`Self::creation_rule`] — the rule
15235    /// the create applies — reading the parent project's issue only when `target` names one.
15236    async fn creation_repository(
15237        &self,
15238        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15239    ) -> Result<Option<Repository>, SourceError> {
15240        let onetaskgraph_plugin_api::WriteTarget::New {
15241            repositories,
15242            project,
15243        } = target
15244        else {
15245            return Ok(None);
15246        };
15247        let target = self
15248            .creation_rule(repositories, *project, "a new item")
15249            .await?;
15250        Repository::try_from(target.origin())
15251            .map(Some)
15252            .map_err(|message| SourceError::Malformed { message })
15253    }
15254    /// Every issue of the repository a create of `target` files in whose body carries `key` in
15255    /// its metadata slot, read off that repository's issues newest first back to `since` —
15256    /// never through search, whose index lags a fresh issue by seconds.
15257    async fn created_with_key(
15258        &self,
15259        record: onetaskgraph_plugin_api::MetadataRecord,
15260        key: &str,
15261        since: Option<DateTime<Utc>>,
15262        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15263    ) -> Result<Vec<NativeId>, SourceError> {
15264        let _ = record;
15265        let onetaskgraph_plugin_api::WriteTarget::New {
15266            repositories,
15267            project,
15268        } = target
15269        else {
15270            return Ok(Vec::new());
15271        };
15272        let repository = self
15273            .creation_rule(repositories, *project, "a new item")
15274            .await?;
15275        let wanted = Value::String(key.to_owned());
15276        let mut found = Vec::new();
15277        let mut after: Option<String> = None;
15278        let mut followed = std::collections::HashSet::new();
15279        loop {
15280            let data = self
15281                .graphql(
15282                    graphql::ISSUES_BY_CREATION,
15283                    json!({"owner": repository.owner, "name": repository.name,
15284                           "first": MAX_PAGE_SIZE, "after": after}),
15285                )
15286                .await?;
15287            let issues =
15288                data.pointer("/repository/issues")
15289                    .ok_or_else(|| SourceError::Malformed {
15290                        message: format!(
15291                            "GitHub answered no issues for repository {}",
15292                            repository.slug()
15293                        ),
15294                    })?;
15295            let malformed = |what: &str| SourceError::Malformed {
15296                message: format!(
15297                    "GitHub answered a page of repository {}'s issues {what}",
15298                    repository.slug()
15299                ),
15300            };
15301            let nodes = issues
15302                .get("nodes")
15303                .and_then(Value::as_array)
15304                .ok_or_else(|| malformed("with no list of issues"))?;
15305            let mut older = false;
15306            for node in nodes {
15307                let id = node
15308                    .get("id")
15309                    .and_then(Value::as_str)
15310                    .filter(|id| !id.is_empty())
15311                    .ok_or_else(|| malformed("holding an issue with no id"))?;
15312                let created = optional_time(node, "createdAt")?
15313                    .ok_or_else(|| malformed("holding an issue with no creation time"))?;
15314                if since.is_some_and(|since| created < since) {
15315                    older = true;
15316                    break;
15317                }
15318                let body = match node.get("body") {
15319                    Some(Value::String(body)) => Some(body.clone()),
15320                    Some(Value::Null) => None,
15321                    _ => return Err(malformed("holding an issue with no body member")),
15322                };
15323                let (_, metadata) = metadata_body(body)?;
15324                if metadata.get(MetadataKey::CREATE_KEY) == Some(&wanted) {
15325                    found.push(NativeId(id.to_owned()));
15326                }
15327            }
15328            let next = issues
15329                .pointer("/pageInfo/hasNextPage")
15330                .and_then(Value::as_bool)
15331                .ok_or_else(|| malformed("that does not say whether another follows"))?;
15332            if older || !next {
15333                return Ok(found);
15334            }
15335            // A page that says another follows names where it starts, and never a page already
15336            // read: anything else would ask for the same pages again for ever.
15337            let cursor = issues
15338                .pointer("/pageInfo/endCursor")
15339                .and_then(Value::as_str)
15340                .filter(|cursor| !cursor.is_empty())
15341                .map(str::to_owned);
15342            if cursor
15343                .as_ref()
15344                .is_none_or(|cursor| !followed.insert(cursor.clone()))
15345            {
15346                return Err(SourceError::Malformed {
15347                    message: format!(
15348                        "GitHub answered a page of repository {}'s issues that says another \
15349                         follows without a new cursor to it",
15350                        repository.slug()
15351                    ),
15352                });
15353            }
15354            after = cursor;
15355        }
15356    }
15357
15358    /// `Repository.issues` lists an issue GitHub committed only once its listing catches up.
15359    fn create_key_lags(&self) -> bool {
15360        true
15361    }
15362
15363    /// The task as this process's own latest write of it left it, from the item it recorded
15364    /// that write as — never a request. Its `version` is always `None`: a board's change token
15365    /// is given only once an item has gone unchanged for [`change_token::SETTLED`], which an
15366    /// item this command has just written has not, so no write's own answer can vouch for one.
15367    async fn written_task(&self, id: &NativeId) -> Option<Task> {
15368        let held = self
15369            .created()
15370            .ok()?
15371            .iter()
15372            .find(|held| held.id == *id)
15373            .cloned()
15374            .or_else(|| {
15375                self.updated()
15376                    .ok()?
15377                    .iter()
15378                    .find(|held| held.id == *id)
15379                    .cloned()
15380            })?;
15381        let mut task = held.task().ok()?;
15382        task.version = self.written_token(id);
15383        Some(task)
15384    }
15385
15386    /// Why `creation_owners` refuses a create of `target`, by [`Self::creation_rule`] — read
15387    /// only when the list is not empty, so a source restricting nothing reads nothing.
15388    async fn creation_refusal(
15389        &self,
15390        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15391    ) -> Result<Option<String>, SourceError> {
15392        let onetaskgraph_plugin_api::WriteTarget::New {
15393            repositories,
15394            project,
15395        } = target
15396        else {
15397            return Ok(None);
15398        };
15399        if self.creation_owners.is_empty() {
15400            return Ok(None);
15401        }
15402        let target = self
15403            .creation_rule(repositories, *project, "a new item")
15404            .await?;
15405        Ok(self.owner_refusal(&target))
15406    }
15407
15408    async fn health(&self) -> Result<Health, SourceError> {
15409        let board = self.board_page(None, 1).await?;
15410        Ok(Health {
15411            reachable: true,
15412            detail: Some(format!(
15413                "reading GitHub project {}/{} ({})",
15414                self.owner,
15415                self.project_number,
15416                required_str(&board, "title")?
15417            )),
15418        })
15419    }
15420    /// The board's own node id, digested: the one request reading its fields, or none when
15421    /// this command has read them already.
15422    async fn designator(&self) -> Result<Option<Designator>, SourceError> {
15423        let board = self.board_fields().await?;
15424        Designator::of_backend(KIND, board.id.as_str())
15425            .map(Some)
15426            .map_err(|message| SourceError::Malformed { message })
15427    }
15428    async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError> {
15429        self.item_by_id(id)
15430            .await?
15431            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
15432            .map(|item| item.task())
15433            .transpose()
15434    }
15435    async fn task_assets(
15436        &self,
15437        id: &NativeId,
15438    ) -> Result<Vec<onetaskgraph_plugin_api::Asset>, SourceError> {
15439        self.held_assets(id, BoardKind::Work(ItemKind::Task)).await
15440    }
15441    async fn task_asset(
15442        &self,
15443        id: &NativeId,
15444        name: &onetaskgraph_plugin_api::AssetName,
15445    ) -> Result<Option<Vec<u8>>, SourceError> {
15446        self.held_asset(id, BoardKind::Work(ItemKind::Task), name)
15447            .await
15448    }
15449    async fn set_task_rendering_with_assets(
15450        &self,
15451        id: &NativeId,
15452        content: &str,
15453        provenance: &Value,
15454        _answers: &BTreeMap<String, Value>,
15455        assets: &onetaskgraph_plugin_api::AssetWrite,
15456    ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
15457        self.replace_rendering(
15458            id,
15459            BoardKind::Work(ItemKind::Task),
15460            content,
15461            provenance,
15462            Some(assets),
15463        )
15464        .await
15465    }
15466    async fn document_assets(
15467        &self,
15468        id: &NativeId,
15469    ) -> Result<Vec<onetaskgraph_plugin_api::Asset>, SourceError> {
15470        self.held_assets(id, BoardKind::Document).await
15471    }
15472    async fn document_asset(
15473        &self,
15474        id: &NativeId,
15475        name: &onetaskgraph_plugin_api::AssetName,
15476    ) -> Result<Option<Vec<u8>>, SourceError> {
15477        self.held_asset(id, BoardKind::Document, name).await
15478    }
15479    async fn set_document_rendering_with_assets(
15480        &self,
15481        id: &NativeId,
15482        content: &str,
15483        provenance: &Value,
15484        _answers: &BTreeMap<String, Value>,
15485        assets: &onetaskgraph_plugin_api::AssetWrite,
15486    ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
15487        self.replace_rendering(id, BoardKind::Document, content, provenance, Some(assets))
15488            .await
15489    }
15490    async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError> {
15491        Ok(self
15492            .item_by_id(id)
15493            .await?
15494            .filter(|item| item.kind == BoardKind::Work(ItemKind::Project))
15495            .map(|item| item.project()))
15496    }
15497    /// Every narrowed search and origin lookup asked, a page at a time, as aliased fields of one
15498    /// [`graphql::SEARCH_BATCH`] request a round — a search's issue search in an `s<n>` field,
15499    /// an origin's board filter in an `o<n>` field beside its issue search — and every other
15500    /// query by [`Self::query_tasks`] on its own: one narrowed by a project or by comment
15501    /// activity, one carrying no narrowing, one resumed from a cursor that read handed out, and
15502    /// every query of a process that has written this board, whose own writes complete a
15503    /// narrowed answer. A lone search is its own read too, which costs a batch's point at a
15504    /// page of its own size.
15505    ///
15506    /// Each search's first page asks [`SEARCH_BATCH_FIRST_PAGE`] rows and each later page
15507    /// [`SEARCH_PAGE_SIZE`]. GitHub answers an error about one aliased field at that field's
15508    /// path, beside the others' answers, so a refused page fails that query's answer alone; a
15509    /// request it refuses whole is every query of that request's answer.
15510    async fn query_tasks_batch(
15511        &self,
15512        asks: &[(TaskQuery, PageRequest)],
15513    ) -> Vec<Result<Page<Task>, SourceError>> {
15514        self.search_batched(asks).await
15515    }
15516    async fn query_tasks(
15517        &self,
15518        query: &TaskQuery,
15519        page: &PageRequest,
15520    ) -> Result<Page<Task>, SourceError> {
15521        validate_page(page)?;
15522        refuse_unsearchable(query)?;
15523        // A closed issue reads `done`, `cancelled` or — closed for a reason that implies no
15524        // category — `unknown`; every other category reads only off an open issue or a draft. So
15525        // a status filter naming none of those three asks every issue search it sends for open
15526        // issues alone; each candidate's category is still confirmed from its own item below.
15527        let open_only = open_only(query);
15528        if query.origin.is_none()
15529            && !matches!(query.project, ProjectFilter::Is(_))
15530            && let Some(also) = search_qualifiers(query)
15531        {
15532            return self.search_tasks(query, page, &also).await;
15533        }
15534
15535        // A read narrowed to one project asks that project for its own tasks, so nothing
15536        // about it costs what the rest of the board holds. A read carrying a text, metadata
15537        // or origin predicate asks GitHub the narrower question those predicates are, and a
15538        // read narrowed to comment activity alone asks the board's own issue search for the
15539        // issues updated since, which is every issue a comment could have been written or
15540        // edited on since. Every other task read is a question about the whole board and is
15541        // answered by reading it.
15542        let (held, membership) = match (&query.project, query.commented_since) {
15543            (ProjectFilter::Is(project), _) => (
15544                match self.held_task_children(project)? {
15545                    // Taken as `project_children` takes the project's own sub-issue read: with
15546                    // every item this process wrote under it since, and none it moved away.
15547                    Some(held) => self.completed_with_written(
15548                        held.into_iter()
15549                            .filter(|child| child.parent.as_ref() == Some(project))
15550                            .collect(),
15551                        |own| own.parent.as_ref() == Some(project),
15552                    )?,
15553                    None => self.project_children(project).await?,
15554                },
15555                // Answered by where these items came from; see `task_matches`.
15556                &ProjectFilter::Any,
15557            ),
15558            (ProjectFilter::Any | ProjectFilter::Orphans, since) => {
15559                match (self.narrowed(query).await?, since) {
15560                    (Some(narrowed), _) => (narrowed, &query.project),
15561                    (None, Some(since)) => (self.updated_since(since).await?, &query.project),
15562                    // The board's own items list every draft; only the search half, which
15563                    // completes them with issues they lag behind on, is narrowed — a closed
15564                    // issue that half leaves out is at no category the filter keeps.
15565                    // Every category it keeps reads only off an open item, so it reads the
15566                    // board's open items alone, through the board's own filter.
15567                    (None, None) if open_items_only(query) => {
15568                        (self.open_items().await?, &query.project)
15569                    }
15570                    (None, None) if open_only => (
15571                        self.board_completed_by(Some(OPEN_QUALIFIER)).await?.items,
15572                        &query.project,
15573                    ),
15574                    (None, None) => (self.board().await?.items, &query.project),
15575                }
15576            }
15577        };
15578        // Every candidate this read confirms by its comments is read together.
15579        let candidates = self.comment_candidates(held.iter(), query, membership)?;
15580        self.hold_comment_pages(&candidates).await?;
15581        // Filtered before paged: a page of a filtered result is a page of the survivors,
15582        // never the survivors of a page.
15583        let mut tasks = Vec::new();
15584        for item in held
15585            .iter()
15586            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
15587        {
15588            let task = item.task()?;
15589            if task_matches(&task, query, membership)
15590                && self.commented_since(item, query.commented_since).await?
15591            {
15592                tasks.push(task);
15593            }
15594        }
15595        Ok(offset_page(
15596            tasks,
15597            numeric_cursor(page.cursor.as_ref())?,
15598            page.limit.min(MAX_PAGE_SIZE) as usize,
15599        ))
15600    }
15601    /// Read board pages directly, at the board connection's consistency. Unlike
15602    /// `query_tasks`, this does not complete a lagging board with issue search: a complete
15603    /// sweep needs one request per listing page, including the first comments.
15604    async fn query_task_details(
15605        &self,
15606        query: &TaskQuery,
15607        page: &PageRequest,
15608        comments: Option<&PageRequest>,
15609    ) -> Result<Page<TaskDetailRead>, SourceError> {
15610        let Some(comments) = comments else {
15611            let tasks = self.query_tasks(query, page).await?;
15612            return Ok(Page {
15613                items: tasks
15614                    .items
15615                    .into_iter()
15616                    .map(|task| TaskDetailRead {
15617                        task,
15618                        comments: None,
15619                    })
15620                    .collect(),
15621                next: tasks.next,
15622            });
15623        };
15624        validate_page(page)?;
15625        validate_page(comments)?;
15626        refuse_unsearchable(query)?;
15627        if comments.cursor.is_some() || query.commented_since.is_some() {
15628            return Err(SourceError::Refused {
15629                message: "a board listing with comments requires a first comment page and cannot filter by comment activity".into(),
15630            });
15631        }
15632        let after = page.cursor.as_ref().map(|cursor| cursor.0.as_str());
15633        let data = self
15634            .graphql(
15635                graphql::BOARD_WITH_COMMENTS,
15636                json!({
15637                    "owner":self.owner,"number":self.project_number,
15638                    "first":page.limit.min(MAX_PAGE_SIZE),"after":after,
15639                    "commentFirst":comments.limit.min(MAX_PAGE_SIZE),
15640                    "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true,
15641                }),
15642            )
15643            .await?;
15644        let connection = data
15645            .pointer("/owner/projectV2/items")
15646            .filter(|value| !value.is_null())
15647            .ok_or_else(|| SourceError::Refused {
15648                message: "GitHub project was not found or is not visible to the token".into(),
15649            })?;
15650        let mut items = Vec::new();
15651        for node in optional_nodes(Some(connection), "board items")?
15652            .into_iter()
15653            .flatten()
15654        {
15655            let Some(item) = self.resolve(node)? else {
15656                continue;
15657            };
15658            if item.kind != BoardKind::Work(ItemKind::Task) {
15659                continue;
15660            }
15661            let task = item.task()?;
15662            if !task_matches(&task, query, &query.project) {
15663                continue;
15664            }
15665            let read = if item.content_kind == ContentKind::DraftIssue {
15666                Err(self.draft_has_no_comments(&task.id))
15667            } else {
15668                self.expected.learn_comments(&task.id, &node["content"]);
15669                comment_page(&node["content"], &task.id.0, None).map(Some)
15670            };
15671            items.push(TaskDetailRead {
15672                task,
15673                comments: Some(read),
15674            });
15675        }
15676        let next = next_cursor(connection)?;
15677        if let Some(next) = &next {
15678            validate_cursor_progress(after, &next.0)?;
15679        }
15680        Ok(Page { items, next })
15681    }
15682
15683    async fn query_projects(
15684        &self,
15685        query: &ProjectQuery,
15686        page: &PageRequest,
15687    ) -> Result<Page<Project>, SourceError> {
15688        validate_page(page)?;
15689        refuse_unsearchable_text(query.text.as_ref())?;
15690        // The projects a board holds are found by an issue search scoped to that board,
15691        // never by walking the board's own item connection: what tells a project from a
15692        // task is the `parent` each issue carries, which costs nothing to read. A query
15693        // carrying a text asks that search for the text too, so it reads the issues that
15694        // hold it rather than every issue of the board.
15695        let held = match self.text_searched(query.text.as_ref()).await? {
15696            Some(searched) => searched,
15697            None => self.board_issues().await?,
15698        };
15699        let projects = held
15700            .iter()
15701            .filter(|item| item.kind == BoardKind::Work(ItemKind::Project))
15702            .map(Resolved::project)
15703            .filter(|project| project_matches(project, query))
15704            .collect();
15705        Ok(offset_page(
15706            projects,
15707            numeric_cursor(page.cursor.as_ref())?,
15708            page.limit.min(MAX_PAGE_SIZE) as usize,
15709        ))
15710    }
15711    async fn query_projects_by_origin(
15712        &self,
15713        origin: &str,
15714        page: &PageRequest,
15715    ) -> Result<Page<Project>, SourceError> {
15716        validate_page(page)?;
15717        let projects = self
15718            .copied_from(origin, BoardKind::Work(ItemKind::Project))
15719            .await?
15720            .iter()
15721            .map(Resolved::project)
15722            .collect();
15723        Ok(offset_page(
15724            projects,
15725            numeric_cursor(page.cursor.as_ref())?,
15726            page.limit.min(MAX_PAGE_SIZE) as usize,
15727        ))
15728    }
15729    async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
15730        let Some(item) = self
15731            .document_by_id(id)
15732            .await?
15733            .filter(|item| item.kind == BoardKind::Document)
15734        else {
15735            return Ok(None);
15736        };
15737        self.expected.read_document(&item);
15738        Ok(Some(item.document()))
15739    }
15740    async fn query_documents_by_origin(
15741        &self,
15742        origin: &str,
15743        page: &PageRequest,
15744    ) -> Result<Page<Document>, SourceError> {
15745        validate_page(page)?;
15746        let documents = self
15747            .copied_from(origin, BoardKind::Document)
15748            .await?
15749            .iter()
15750            .map(Resolved::document)
15751            .collect();
15752        Ok(offset_page(
15753            documents,
15754            numeric_cursor(page.cursor.as_ref())?,
15755            page.limit.min(MAX_PAGE_SIZE) as usize,
15756        ))
15757    }
15758    async fn query_documents(
15759        &self,
15760        query: &DocumentQuery,
15761        page: &PageRequest,
15762    ) -> Result<Page<Document>, SourceError> {
15763        validate_page(page)?;
15764        // Narrowed to one project, this is the same sub-issue read a task list scoped to
15765        // that project makes — a document filed under a project is a sub-issue of it too,
15766        // and which of them come back is the kind this caller asked for. Unscoped, a query
15767        // carrying a text asks the board-scoped issue search for it, as a task query does,
15768        // and only one carrying none reads the board.
15769        let (held, membership) = match &query.project {
15770            ProjectFilter::Is(project) => (
15771                self.project_children(project).await?,
15772                // Answered by where these items came from; see `task_matches`.
15773                &ProjectFilter::Any,
15774            ),
15775            ProjectFilter::Any | ProjectFilter::Orphans => {
15776                refuse_unsearchable_text(query.text.as_ref())?;
15777                match self.text_searched(query.text.as_ref()).await? {
15778                    Some(searched) => (searched, &query.project),
15779                    None => (self.board().await?.items, &query.project),
15780                }
15781            }
15782        };
15783        // Filtered before paged, exactly as a task read is: a page of a filtered result is
15784        // a page of the survivors, never the survivors of a page.
15785        let documents = held
15786            .iter()
15787            .filter(|item| item.kind == BoardKind::Document)
15788            .map(Resolved::document)
15789            .filter(|document| document_matches(document, query, membership))
15790            .collect();
15791        Ok(offset_page(
15792            documents,
15793            numeric_cursor(page.cursor.as_ref())?,
15794            page.limit.min(MAX_PAGE_SIZE) as usize,
15795        ))
15796    }
15797    async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError> {
15798        validate_page(page)?;
15799        let offset = numeric_cursor(page.cursor.as_ref())?;
15800        let mut labels = self
15801            .board()
15802            .await?
15803            .items
15804            .into_iter()
15805            .flat_map(|item| item.labels)
15806            .fold(Vec::new(), |mut all, label| {
15807                if !all.iter().any(|x: &Label| x.id == label.id) {
15808                    all.push(label);
15809                }
15810                all
15811            });
15812        labels.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.0.cmp(&b.id.0)));
15813        Ok(offset_page(
15814            labels,
15815            offset,
15816            page.limit.min(MAX_PAGE_SIZE) as usize,
15817        ))
15818    }
15819    async fn task_dependencies(
15820        &self,
15821        id: &NativeId,
15822        direction: Direction,
15823        page: &PageRequest,
15824    ) -> Result<Page<DependencyEdge>, SourceError> {
15825        self.dependencies(id, ItemKind::Task, direction, page).await
15826    }
15827    async fn project_dependencies(
15828        &self,
15829        id: &NativeId,
15830        direction: Direction,
15831        page: &PageRequest,
15832    ) -> Result<Page<DependencyEdge>, SourceError> {
15833        self.dependencies(id, ItemKind::Project, direction, page)
15834            .await
15835    }
15836
15837    fn writes(&self) -> WriteSupport {
15838        WriteSupport::Supported
15839    }
15840
15841    /// Create or update one task.
15842    ///
15843    /// Its `delivers` and `delivered_by` are checked before anything is read or written —
15844    /// neither may name the task itself or name one task twice — and land in the body's
15845    /// metadata slot under their reserved keys, in place of any caller metadata of those
15846    /// names.
15847    async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
15848        if write.item.project.is_some() {
15849            self.projectless()?;
15850        }
15851        self.write_task_assets(write, None)
15852            .await
15853            .map(|written| written.id)
15854    }
15855
15856    async fn read_ahead_origins_for_copy(&self, origins: &[String]) -> Result<(), SourceError> {
15857        self.origins_ahead(origins).await
15858    }
15859
15860    async fn member_classifications(
15861        &self,
15862        project: &NativeId,
15863    ) -> Result<Option<Vec<(Classification, Vec<Repository>)>>, SourceError> {
15864        Ok(self
15865            .member_classes
15866            .lock()
15867            .map_err(|_| SourceError::Unavailable {
15868                message: "a project's members held for its classification were left \
15869                          inconsistent; run the command again"
15870                    .into(),
15871            })?
15872            .remove(project))
15873    }
15874
15875    /// The issue's own web address, as the `createIssue` that made it in this command answered
15876    /// it: a task, a project and a document are each an issue here.
15877    fn written_location(
15878        &self,
15879        _record: onetaskgraph_plugin_api::MetadataRecord,
15880        id: &NativeId,
15881    ) -> Option<Location> {
15882        self.written
15883            .lock()
15884            .unwrap_or_else(std::sync::PoisonError::into_inner)
15885            .get(id)
15886            .cloned()
15887            .map(Location::Url)
15888    }
15889
15890    /// [`MUTATION_BATCH`], while writes are held back: [`graphql::CREATE_ISSUES`] creates that many
15891    /// in one request, and a copy's tasks are created together only then, since their fields
15892    /// and edges are what is held back.
15893    fn create_batch_limit(&self) -> usize {
15894        if self.deferring().unwrap_or(false) {
15895            MUTATION_BATCH
15896        } else {
15897            1
15898        }
15899    }
15900
15901    // llmlint: ignore[invalid_states_unrepresentable] The signature is the plugin contract's additive `TaskSource::write_tasks`, which the manager approved taking `ItemWrite<Task>` as `write_task` does; a create-only input type would be a new contract type. A write naming an existing target is refused below before anything is sent.
15902    async fn write_tasks(&self, writes: &[ItemWrite<Task>]) -> Result<Vec<NativeId>, SourceError> {
15903        if writes.iter().any(|write| write.item.project.is_some()) {
15904            self.projectless()?;
15905        }
15906        if let Some(write) = writes.iter().find(|write| write.target.is_some()) {
15907            return Err(SourceError::Refused {
15908                message: format!(
15909                    "write_tasks creates tasks, and the write of {} names the existing task {}; \
15910                     next: update it with write_task",
15911                    write.item.id,
15912                    write.target.as_ref().map_or("", |target| target.0.as_str())
15913                ),
15914            });
15915        }
15916        if !self.deferring()? {
15917            let mut created = Vec::with_capacity(writes.len());
15918            for write in writes {
15919                match self.write_task(write).await {
15920                    Ok(id) => created.push(id),
15921                    Err(error) => {
15922                        let mut left: Vec<&str> = Vec::new();
15923                        for id in &created {
15924                            if self.delete_issue(id).await.is_err() {
15925                                left.push(id.0.as_str());
15926                            }
15927                        }
15928                        return Err(left_behind(error, &left));
15929                    }
15930                }
15931            }
15932            return Ok(created);
15933        }
15934        self.create_together(writes).await
15935    }
15936
15937    fn begin_deferred_writes(&self) {
15938        if let Ok(mut deferred) = self.deferred.lock() {
15939            deferred.get_or_insert_with(Deferred::default);
15940        }
15941    }
15942
15943    async fn finish_writes(&self) -> Result<(), SourceError> {
15944        self.send_held_updates().await?;
15945        self.send_held_back().await
15946    }
15947
15948    async fn write_task_with_assets(
15949        &self,
15950        write: &ItemWrite<Task>,
15951        _answers: Option<&BTreeMap<String, Value>>,
15952        assets: &onetaskgraph_plugin_api::AssetWrite,
15953    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
15954        self.write_task_assets(write, Some(assets)).await
15955    }
15956
15957    async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
15958        self.projectless()?;
15959        self.write_item(
15960            &Incoming {
15961                written: Written::Work(ItemKind::Project, &write.item.status),
15962                title: &write.item.title,
15963                content: write.item.content.as_deref(),
15964                assets: None,
15965                labels: &write.item.labels,
15966                metadata: &write.item.metadata,
15967                repositories: &write.item.repositories,
15968                classification: write.item.classification,
15969                parent: None,
15970                delivers: &[],
15971                delivered_by: &[],
15972                priority: None,
15973                assignees: None,
15974            },
15975            write.target.as_ref(),
15976            &write.depends_on,
15977        )
15978        .await
15979        .map(|written| written.id)
15980    }
15981
15982    fn task_body_size(
15983        &self,
15984        write: &ItemWrite<Task>,
15985        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
15986    ) -> Option<onetaskgraph_plugin_api::BodySize> {
15987        Some(self.body_size(&self.task_incoming(write, assets).ok()?))
15988    }
15989
15990    fn project_body_size(
15991        &self,
15992        write: &ItemWrite<Project>,
15993    ) -> Option<onetaskgraph_plugin_api::BodySize> {
15994        Some(self.body_size(&Incoming {
15995            written: Written::Work(ItemKind::Project, &write.item.status),
15996            title: &write.item.title,
15997            content: write.item.content.as_deref(),
15998            assets: None,
15999            labels: &write.item.labels,
16000            metadata: &write.item.metadata,
16001            repositories: &write.item.repositories,
16002            classification: write.item.classification,
16003            parent: None,
16004            delivers: &[],
16005            delivered_by: &[],
16006            priority: None,
16007            assignees: None,
16008        }))
16009    }
16010
16011    fn document_body_size(
16012        &self,
16013        write: &ItemWrite<Document>,
16014        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
16015    ) -> Option<onetaskgraph_plugin_api::BodySize> {
16016        Some(self.body_size(&Incoming {
16017            written: Written::Document,
16018            title: &write.item.title,
16019            content: write.item.content.as_deref(),
16020            assets,
16021            labels: &write.item.labels,
16022            metadata: &write.item.metadata,
16023            repositories: &write.item.repositories,
16024            classification: write.item.classification,
16025            parent: write.item.project.as_ref(),
16026            delivers: &[],
16027            delivered_by: &[],
16028            priority: None,
16029            assignees: None,
16030        }))
16031    }
16032
16033    /// Create or update one document, which is one issue titled the way this board spells
16034    /// a document.
16035    ///
16036    /// Everything else is exactly a task write: caller metadata goes to the same canonical
16037    /// JSON slot at the end of the body and comes back with its JSON types intact, a key
16038    /// or a field this board cannot carry is refused by name rather than dropped, a target
16039    /// naming an issue this board does not hold is refused rather than created, and an
16040    /// issue this call created is taken back when the rest of the write fails.
16041    async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
16042        self.write_document_assets(write, None)
16043            .await
16044            .map(|written| written.id)
16045    }
16046
16047    async fn write_document_with_assets(
16048        &self,
16049        write: &ItemWrite<Document>,
16050        _answers: Option<&BTreeMap<String, Value>>,
16051        assets: &onetaskgraph_plugin_api::AssetWrite,
16052    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
16053        self.write_document_assets(write, Some(assets)).await
16054    }
16055
16056    /// Refused exactly as the write refuses it, from what the write reads: the mapping first,
16057    /// which reads nothing; then the board's `Status` option. Over an existing item that is
16058    /// read off the item, as the write reads it, and the item is held among this command's
16059    /// resolved records so the write that follows reuses that read rather than repeating it;
16060    /// an item that does not carry the field takes the board's fields, which are held once
16061    /// read. A create is checked against the board's fields only when this command already
16062    /// holds them, because a create reads them together with its repository, in one request,
16063    /// and refuses a missing option before it writes anything.
16064    async fn check_status_write(
16065        &self,
16066        kind: ItemKind,
16067        category: StatusCategory,
16068        target: Option<&NativeId>,
16069    ) -> Result<(), SourceError> {
16070        let status = self.resolved_target(kind, category)?;
16071        if status.option().is_none() {
16072            return Ok(());
16073        }
16074        let fields = match target {
16075            Some(target) => {
16076                // A target this board does not hold is the write's own refusal to make.
16077                let Some(item) = self.bound_item(target).await? else {
16078                    return Ok(());
16079                };
16080                self.resolved_cache()?.insert(target.clone(), item.clone());
16081                // Only the `Status` field decides whether the write can land.
16082                self.fields_for(Some(&item), false, true, false)
16083                    .await?
16084                    .fields
16085            }
16086            None => {
16087                let held = self
16088                    .board_cache()?
16089                    .as_ref()
16090                    .map(|board| board.fields.clone());
16091                match held.or_else(|| {
16092                    self.fields_cache()
16093                        .ok()
16094                        .and_then(|cache| cache.as_ref().map(|board| board.fields.clone()))
16095                }) {
16096                    Some(fields) => fields,
16097                    None => return Ok(()),
16098                }
16099            }
16100        };
16101        self.column_for(&fields, kind, category, &status)
16102            .map(|_| ())
16103    }
16104
16105    /// What a write of `status` reads back as: the `Status` option its category maps to for
16106    /// `kind`, and for a closing category the closure that option and its fixed reason read
16107    /// as — exactly what [`BoardStatuses::status`] reports of the item once written. A category
16108    /// this instance has no option for is answered as given, since writing it is refused.
16109    fn status_as_written(&self, kind: ItemKind, status: &Status) -> Status {
16110        match self.statuses.target(kind, status.category) {
16111            StatusTarget::Column(name) => {
16112                self.statuses.status(kind, Some(name.as_str()), false, None)
16113            }
16114            StatusTarget::Terminal(name, reason) => {
16115                self.statuses
16116                    .status(kind, Some(name.as_str()), true, Some(reason.reason()))
16117            }
16118            StatusTarget::Disabled(_) => status.clone(),
16119        }
16120    }
16121
16122    /// Set one task's status alone.
16123    ///
16124    /// An open target reopens a closed issue with an `updateIssue` carrying only its
16125    /// `stateInput`, then selects the board option with `updateProjectV2ItemFieldValue`; a
16126    /// terminal target selects its mapped option, then closes with its fixed reason. No
16127    /// request carries a title, a body or a label. The status
16128    /// answered is what [`BoardStatuses::status`] reads off the state just written, which is
16129    /// what a re-read reports.
16130    async fn set_task_status(
16131        &self,
16132        id: &NativeId,
16133        category: StatusCategory,
16134    ) -> Result<Option<Status>, SourceError> {
16135        self.set_status(id, ItemKind::Task, category).await
16136    }
16137
16138    /// Set one task's status and answer the task with it, reading the item once: the read the
16139    /// task is answered from is handed to the status write, which would otherwise read the
16140    /// same issue again — two requests on a fresh process, the read and the field write,
16141    /// where the default's `get_task` before `set_task_status` sent three.
16142    async fn set_task_status_reading(
16143        &self,
16144        id: &NativeId,
16145        category: StatusCategory,
16146    ) -> Result<Option<Task>, SourceError> {
16147        // Refused before anything is read, in the words the write itself refuses it.
16148        self.resolved_target(ItemKind::Task, category)?;
16149        let Some(item) = self
16150            .bound_item(id)
16151            .await?
16152            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
16153        else {
16154            return Ok(None);
16155        };
16156        let mut task = item.task()?;
16157        self.held_cache
16158            .lock()
16159            .map_err(|_| SourceError::Unavailable {
16160                message: "items read by issue reference were left inconsistent; run the \
16161                          command again"
16162                    .into(),
16163            })?
16164            .insert(id.clone(), item);
16165        let Some(status) = self.set_status(id, ItemKind::Task, category).await? else {
16166            return Ok(None);
16167        };
16168        task.status = status;
16169        Ok(Some(task))
16170    }
16171
16172    /// Set one project's status alone, by exactly the paired write a task's status takes, for
16173    /// the project kind: a terminal category selects the project kind's mapped option and then
16174    /// closes the issue with the category's fixed reason — an issue already closed with a
16175    /// reason that reads that category is left as it is — and an open category reopens a closed
16176    /// issue and then selects its option. A board draft is refused a terminal category as a
16177    /// task's is.
16178    async fn set_project_status(
16179        &self,
16180        id: &NativeId,
16181        category: StatusCategory,
16182    ) -> Result<Option<Status>, SourceError> {
16183        self.projectless()?;
16184        self.set_status(id, ItemKind::Project, category).await
16185    }
16186
16187    /// Every task and project whose card contradicts its issue's closure, read through the
16188    /// board's own `is:closed` filter; see [`TaskSource::status_contradictions`].
16189    async fn status_contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
16190        self.contradictions().await
16191    }
16192
16193    /// What this board holds for each issue reference, one request per fifty of them; see
16194    /// [`TaskSource::issue_holdings`].
16195    async fn issue_holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
16196        self.holdings(issues).await
16197    }
16198
16199    /// Set one task's priority alone: one `updateProjectV2ItemFieldValue` selecting the
16200    /// mapped option of the board's `Priority` field, or one `clearProjectV2ItemFieldValue`
16201    /// for `none`. Refused by an instance with no `priority_mapping`.
16202    async fn set_task_priority(
16203        &self,
16204        id: &NativeId,
16205        priority: Priority,
16206    ) -> Result<Option<Priority>, SourceError> {
16207        self.set_priority(id, priority).await
16208    }
16209
16210    /// Replace one task's content with a single body update that keeps the metadata slot
16211    /// byte for byte.
16212    async fn set_task_content(
16213        &self,
16214        id: &NativeId,
16215        content: &str,
16216    ) -> Result<Option<()>, SourceError> {
16217        self.replace_content(id, content).await
16218    }
16219
16220    /// Replace one task issue's content and its provenance slot entry with a single body
16221    /// update. The answers are not kept: see `replace_rendering`.
16222    async fn set_task_rendering(
16223        &self,
16224        id: &NativeId,
16225        content: &str,
16226        provenance: &Value,
16227        _answers: &BTreeMap<String, Value>,
16228    ) -> Result<Option<()>, SourceError> {
16229        self.replace_rendering(
16230            id,
16231            BoardKind::Work(ItemKind::Task),
16232            content,
16233            provenance,
16234            None,
16235        )
16236        .await
16237        .map(|written| written.map(|_| ()))
16238    }
16239
16240    /// Replace one design-document issue's content and its provenance slot entry, on exactly
16241    /// the terms of [`set_task_rendering`](TaskSource::set_task_rendering).
16242    async fn set_document_rendering(
16243        &self,
16244        id: &NativeId,
16245        content: &str,
16246        provenance: &Value,
16247        _answers: &BTreeMap<String, Value>,
16248    ) -> Result<Option<()>, SourceError> {
16249        self.replace_rendering(id, BoardKind::Document, content, provenance, None)
16250            .await
16251            .map(|written| written.map(|_| ()))
16252    }
16253
16254    /// Replace one project issue's content and its provenance slot entry, on exactly the
16255    /// terms of [`set_task_rendering`](TaskSource::set_task_rendering).
16256    async fn set_project_rendering(
16257        &self,
16258        id: &NativeId,
16259        content: &str,
16260        provenance: &Value,
16261        _answers: &BTreeMap<String, Value>,
16262    ) -> Result<Option<()>, SourceError> {
16263        self.projectless()?;
16264        self.replace_rendering(
16265            id,
16266            BoardKind::Work(ItemKind::Project),
16267            content,
16268            provenance,
16269            None,
16270        )
16271        .await
16272        .map(|written| written.map(|_| ()))
16273    }
16274
16275    /// Apply a targeted update with one read of the item and a write only for what differs:
16276    /// the `Status` and `Priority` field writes in one request, the `blockedBy` difference,
16277    /// and last one `updateIssue` for title, body and state. See `targeted_update`.
16278    async fn update_task(
16279        &self,
16280        id: &NativeId,
16281        update: &TaskUpdate,
16282    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
16283        self.targeted_update(id, update).await
16284    }
16285
16286    /// Each issue's sub-issue parent and children and its links, read in batches.
16287    async fn read_relations(
16288        &self,
16289        ids: &[NativeId],
16290    ) -> Vec<Result<Option<onetaskgraph_plugin_api::Relations>, SourceError>> {
16291        self.relations_of(ids).await
16292    }
16293
16294    async fn set_parents(
16295        &self,
16296        writes: &[onetaskgraph_plugin_api::ParentWrite],
16297    ) -> Vec<Result<onetaskgraph_plugin_api::ParentAnswer, SourceError>> {
16298        self.parents_set(writes).await
16299    }
16300
16301    fn link_types(&self) -> onetaskgraph_plugin_api::LinkTypes {
16302        self.link_types.clone()
16303    }
16304
16305    async fn add_native_links(
16306        &self,
16307        links: &[onetaskgraph_plugin_api::NativeLink],
16308    ) -> Vec<Result<(), SourceError>> {
16309        self.native_links(links, relations::NativeWrite::Add).await
16310    }
16311
16312    async fn remove_native_links(
16313        &self,
16314        links: &[onetaskgraph_plugin_api::NativeLink],
16315    ) -> Vec<Result<(), SourceError>> {
16316        self.native_links(links, relations::NativeWrite::Remove)
16317            .await
16318    }
16319
16320    /// Every task read together — [`DETAIL_BATCH`] to a [`graphql::ISSUE_DETAILS`] request —
16321    /// and each update's hold and guard decided on that read; then each update the read lets
16322    /// through composed exactly as [`Self::update_task`] composes one, its board field writes
16323    /// and its issue update held back and sent in [`graphql::WRITE_TASKS`] requests: every
16324    /// field write first, then the issue update of every task whose field writes all landed.
16325    ///
16326    /// **Where GitHub would refuse the batch as a whole, each item is read on its own:** a
16327    /// batched node read naming an id that resolves to nothing is refused whole, so each id of
16328    /// that batch is read by itself, the missing one answered missing and the rest as
16329    /// themselves. A batch of one, an update of a board draft, one naming dependencies and one
16330    /// of an item whose body this process has not read are each made on their own, as
16331    /// [`Self::update_task`] makes them, because each sends writes of its own in an order the
16332    /// batch does not hold. A field write GitHub refuses fails that task's update alone and
16333    /// sends nothing of its body.
16334    async fn update_tasks(
16335        &self,
16336        updates: &[onetaskgraph_plugin_api::BatchUpdate],
16337    ) -> Vec<Result<onetaskgraph_plugin_api::BatchAnswer<TaskUpdateOutcome>, SourceError>> {
16338        self.updates_batched(updates).await
16339    }
16340
16341    /// Replace one task's `delivered_by` with a single body update that changes the
16342    /// metadata slot and nothing outside it.
16343    async fn set_delivered_by(
16344        &self,
16345        id: &NativeId,
16346        delivered_by: &[TaskRef],
16347    ) -> Result<Option<()>, SourceError> {
16348        self.replace_delivered_by(id, delivered_by).await
16349    }
16350
16351    /// Set one key of one task issue's metadata with a single body update that changes the
16352    /// metadata slot and nothing outside it — no title, label, state or board field request —
16353    /// and sends nothing when the task already holds that value under the key.
16354    async fn set_task_metadata(
16355        &self,
16356        id: &NativeId,
16357        key: &MetadataKey,
16358        value: &Value,
16359    ) -> Result<Option<Task>, SourceError> {
16360        Ok(self
16361            .set_slot_key(id, BoardKind::Work(ItemKind::Task), key, value)
16362            .await?
16363            .map(|item| item.task())
16364            .transpose()?)
16365    }
16366
16367    /// Set one key of one project issue's metadata, on exactly the terms of
16368    /// [`set_task_metadata`](TaskSource::set_task_metadata).
16369    async fn set_project_metadata(
16370        &self,
16371        id: &NativeId,
16372        key: &MetadataKey,
16373        value: &Value,
16374    ) -> Result<Option<Project>, SourceError> {
16375        self.projectless()?;
16376        Ok(self
16377            .set_slot_key(id, BoardKind::Work(ItemKind::Project), key, value)
16378            .await?
16379            .map(|item| item.project()))
16380    }
16381
16382    /// Set one key of one design-document issue's metadata, on exactly the terms of
16383    /// [`set_task_metadata`](TaskSource::set_task_metadata).
16384    async fn set_document_metadata(
16385        &self,
16386        id: &NativeId,
16387        key: &MetadataKey,
16388        value: &Value,
16389    ) -> Result<Option<Document>, SourceError> {
16390        Ok(self
16391            .set_slot_key(id, BoardKind::Document, key, value)
16392            .await?
16393            .map(|item| item.document()))
16394    }
16395
16396    /// Take one key out of one issue's metadata slot with a single body update that changes the
16397    /// slot and nothing outside it, sending nothing when the slot does not hold the key.
16398    async fn remove_record_metadata(
16399        &self,
16400        record: onetaskgraph_plugin_api::MetadataRecord,
16401        id: &NativeId,
16402        key: &MetadataKey,
16403    ) -> Result<Option<Option<String>>, SourceError> {
16404        let kind = match record {
16405            onetaskgraph_plugin_api::MetadataRecord::Task => BoardKind::Work(ItemKind::Task),
16406            onetaskgraph_plugin_api::MetadataRecord::Project => BoardKind::Work(ItemKind::Project),
16407            onetaskgraph_plugin_api::MetadataRecord::Document => BoardKind::Document,
16408        };
16409        let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
16410            return Ok(None);
16411        };
16412        if item.slot.contains_key(key.as_str()) {
16413            let mut slot = item.slot.clone();
16414            slot.remove(key.as_str());
16415            self.write_slot(&mut item, &slot).await?;
16416            self.remember_written(item.clone(), false)?;
16417        }
16418        Ok(Some(match record {
16419            onetaskgraph_plugin_api::MetadataRecord::Task => item.task()?.version,
16420            onetaskgraph_plugin_api::MetadataRecord::Project => item.project().version,
16421            onetaskgraph_plugin_api::MetadataRecord::Document => item.document().version,
16422        }))
16423    }
16424
16425    async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
16426        self.delete_item(id).await
16427    }
16428
16429    async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
16430        self.projectless()?;
16431        self.delete_item(id).await
16432    }
16433
16434    async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
16435        self.delete_item(id).await
16436    }
16437
16438    /// One page of the task issue's own comments, walked by GitHub's own cursor.
16439    ///
16440    /// Nothing here filters, so nothing has to be read ahead of the page: the caller's limit is
16441    /// the page GitHub is asked for and GitHub's `endCursor` is the cursor handed back.
16442    ///
16443    /// One request, [`graphql::ISSUE_DETAIL`]: the read that says the id names a task of this
16444    /// board is the read of its comments. A draft this process already resolved is refused
16445    /// without one.
16446    async fn task_comments(
16447        &self,
16448        task: &NativeId,
16449        page: &PageRequest,
16450    ) -> Result<Option<Page<Comment>>, SourceError> {
16451        validate_page(page)?;
16452        let cached = self.resolved_cache()?.get(task).cloned();
16453        if let Some(item) = cached {
16454            if item.kind != BoardKind::Work(ItemKind::Task) {
16455                return Ok(None);
16456            }
16457            if item.content_kind == ContentKind::DraftIssue {
16458                return Err(self.draft_has_no_comments(task));
16459            }
16460        }
16461        // The first page a comment-activity read just read of this task, at the size asked, is
16462        // that read's answer: taken, so it answers once.
16463        if page.cursor.is_none()
16464            && page.limit >= MAX_PAGE_SIZE
16465            && let Some(held) = self.held_comments()?.remove(task)
16466        {
16467            return Ok(Some(held));
16468        }
16469        match self.issue_detail(task, page).await? {
16470            Some(TaskDetailRead {
16471                comments: Some(comments),
16472                ..
16473            }) => comments,
16474            _ => Ok(None),
16475        }
16476    }
16477
16478    /// Every id's task, with the first page of its comments when `comments` names it:
16479    /// [`DETAIL_BATCH`] items per [`graphql::ISSUE_DETAILS`] request, and one item with its
16480    /// comments in one [`graphql::ISSUE_DETAIL`] request.
16481    async fn get_task_details(
16482        &self,
16483        ids: &[NativeId],
16484        comments: Option<&PageRequest>,
16485    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
16486        if let Some(page) = comments
16487            && let Err(error) = validate_page(page)
16488        {
16489            return ids.iter().map(|_| Err(error.clone())).collect();
16490        }
16491        match (ids, comments) {
16492            ([id], Some(page)) => vec![self.issue_detail(id, page).await],
16493            ([id], None) => vec![self.task_read(id).await],
16494            _ => self.issue_details(ids, comments).await,
16495        }
16496    }
16497
16498    /// Every id's task with the first page of its comments and its `blockedBy`, as a copy reads
16499    /// the tasks it carries: [`COPY_DETAIL_BATCH`] items per [`graphql::ISSUE_COPY_DETAILS`]
16500    /// request, so the dependency read a copy makes of each next is answered from this one.
16501    async fn get_task_details_for_copy(
16502        &self,
16503        ids: &[NativeId],
16504        comments: &PageRequest,
16505    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
16506        // A page past the first is a page of one task's comments, which the detail read of it
16507        // alone answers.
16508        if comments.cursor.is_some() {
16509            return self.get_task_details(ids, Some(comments)).await;
16510        }
16511        if let Err(error) = validate_page(comments) {
16512            return ids.iter().map(|_| Err(error.clone())).collect();
16513        }
16514        let mut read = Vec::with_capacity(ids.len());
16515        for batch in ids.chunks(COPY_DETAIL_BATCH) {
16516            match self
16517                .graphql(
16518                    graphql::ISSUE_COPY_DETAILS,
16519                    copy_detail_batch(batch, comments, false),
16520                )
16521                .await
16522            {
16523                Ok(data) => {
16524                    for (slot, id) in batch.iter().enumerate() {
16525                        let read_one = match data.get(format!("i{slot}")) {
16526                            Some(node) => self.detail_of(id, node, true, None).await,
16527                            None => Err(SourceError::Malformed {
16528                                message: format!(
16529                                    "GitHub answered a batch read with no item for {}",
16530                                    id.0
16531                                ),
16532                            }),
16533                        };
16534                        read.push(read_one);
16535                    }
16536                }
16537                Err(error) if unresolvable_node(&error) => {
16538                    for id in batch {
16539                        read.push(self.issue_detail(id, comments).await);
16540                    }
16541                }
16542                Err(error) => read.extend(batch.iter().map(|_| Err(error.clone()))),
16543            }
16544        }
16545        read
16546    }
16547
16548    /// Every id's item, whatever kind it is, read [`COPY_DETAIL_BATCH`] at a time with
16549    /// [`graphql::ISSUE_COPY_DETAILS`] — the document a copy reads the tasks it carries with —
16550    /// and held for the next read of each by id; see `read_ahead`.
16551    ///
16552    /// What this run wrote is never read: its own record answers, as it does for a read by id.
16553    /// Nor is an item a listing of its project carried whole earlier in this command — see
16554    /// `carried` — which is held in place of reading it.
16555    /// A batch GitHub refuses because one of its ids resolves to no node at all holds nothing,
16556    /// so each of its ids is read on its own and answered as that read answers; a draft, and an
16557    /// answer naming another issue than the one asked for, are left to their own reads too.
16558    async fn read_ahead_for_copy(&self, ids: &[NativeId]) -> Result<(), SourceError> {
16559        // The origins asked just before go out now, beside the members of the one project this
16560        // names when it names one; a project those origins answered whole is held for its next
16561        // read by id rather than read again here.
16562        let hinted = match ids {
16563            [one] => Some(one),
16564            _ => None,
16565        };
16566        self.send_pending_origins(hinted).await?;
16567        if let Some(project) = hinted {
16568            let answered = self.resolved_cache()?.get(project).cloned();
16569            if let Some(answered) = answered
16570                && answered.kind == BoardKind::Work(ItemKind::Project)
16571            {
16572                self.read_ahead()?.insert(project.clone(), Some(answered));
16573                return Ok(());
16574            }
16575        }
16576        let mut unread: Vec<NativeId> = Vec::new();
16577        // Read whole by a listing of its project in this command, which a mutation naming it
16578        // would have dropped: held as a batch would have held it, once every batch is answered.
16579        let mut listed: Vec<NativeId> = Vec::new();
16580        {
16581            let created = self.created()?;
16582            let held = self.read_ahead()?;
16583            let carried = self.carried()?;
16584            for id in ids {
16585                if unread.contains(id)
16586                    || listed.contains(id)
16587                    || held.contains_key(id)
16588                    || created.iter().any(|own| own.id == *id)
16589                {
16590                    continue;
16591                }
16592                // An issue a listing carried without the whole of what blocks it is read in a
16593                // batch too, which carries that, rather than having its dependency read sent
16594                // on its own once the copy reconciles its edges.
16595                let whole = carried.get(id).is_some_and(|item| {
16596                    item.content_kind != ContentKind::Issue || item.blocked_by.is_some()
16597                });
16598                if whole {
16599                    listed.push(id.clone());
16600                } else {
16601                    unread.push(id.clone());
16602                }
16603            }
16604        }
16605        // Nothing of an item's comments is wanted here: the smallest page keeps the read to
16606        // what the item itself costs.
16607        let comments = PageRequest {
16608            cursor: None,
16609            limit: 1,
16610        };
16611        // Held only once every batch has been answered, so a read-ahead that fails part way
16612        // holds nothing — what a listing carried included, which stays carried — and every
16613        // item is read on its own, as the method promises.
16614        let mut read: Vec<(NativeId, Option<Resolved>)> = Vec::new();
16615        // The issues the first id names as sub-issues, as `ISSUE_COPY_DETAILS`'s `children`
16616        // answered them: what a project copy's orphan check asks, when that first id is its
16617        // project.
16618        let mut children: Option<(NativeId, Vec<(String, String)>)> = None;
16619        for (index, batch) in unread.chunks(COPY_DETAIL_BATCH).enumerate() {
16620            let data = match self
16621                .graphql(
16622                    graphql::ISSUE_COPY_DETAILS,
16623                    copy_detail_batch(batch, &comments, index == 0),
16624                )
16625                .await
16626            {
16627                Ok(data) => data,
16628                Err(error) if unresolvable_node(&error) => continue,
16629                Err(error) => return Err(error),
16630            };
16631            for (slot, id) in batch.iter().enumerate() {
16632                let Some(node) = data.get(format!("i{slot}")) else {
16633                    continue;
16634                };
16635                let held = if node.is_null() {
16636                    None
16637                } else {
16638                    match optional_str(node, "__typename")? {
16639                        Some("DraftIssue") => continue,
16640                        Some("Issue") if required_str(node, "id")? != id.0 => continue,
16641                        _ => {}
16642                    }
16643                    // Remembered below with the rest, so a later batch refused leaves no
16644                    // dependency read answered from this one either.
16645                    self.resolve_issue_as(node, false).await?
16646                };
16647                read.push((id.clone(), held));
16648            }
16649            if index == 0
16650                && let Some(node) = data.get("children").filter(|node| !node.is_null())
16651                && node.get("id").and_then(Value::as_str) == batch.first().map(|id| id.0.as_str())
16652                && node.pointer("/subIssues/pageInfo/hasNextPage") == Some(&Value::Bool(false))
16653            {
16654                // A list GitHub did not answer is not an empty one: it would answer the project's
16655                // task listing with nothing, and the orphan check with no orphans.
16656                let listed = node
16657                    .pointer("/subIssues/nodes")
16658                    .and_then(Value::as_array)
16659                    .ok_or_else(|| SourceError::Malformed {
16660                        message: format!(
16661                            "GitHub answered the sub-issues of project {} with no list of them",
16662                            batch[0].0
16663                        ),
16664                    })?
16665                    .iter()
16666                    .map(|child| {
16667                        Ok((
16668                            required_str(child, "id")?.to_owned(),
16669                            required_str(child, "title")?.to_owned(),
16670                        ))
16671                    })
16672                    .collect::<Result<Vec<_>, SourceError>>()?;
16673                children = Some((batch[0].clone(), listed));
16674            }
16675        }
16676        // The project's tasks are known from this read alone when every child it named is held
16677        // from it, but for a document, which its title says is one and which a task listing
16678        // never answers: then a listing of the project's tasks is answered from them.
16679        if let Some((project, listed)) = children
16680            && read.iter().any(|(id, held)| {
16681                *id == project
16682                    && held
16683                        .as_ref()
16684                        .is_some_and(|held| held.kind == BoardKind::Work(ItemKind::Project))
16685            })
16686        {
16687            let mut tasks = Vec::new();
16688            let mut whole = true;
16689            for (child, title) in &listed {
16690                match read.iter().find(|(id, _)| id.0 == *child) {
16691                    Some((_, Some(held))) if held.parent.as_ref() == Some(&project) => {
16692                        if held.kind == BoardKind::Work(ItemKind::Task) {
16693                            tasks.push(held.clone());
16694                        }
16695                    }
16696                    _ if title.starts_with(DESIGN_TITLE_PREFIX) => {}
16697                    _ => whole = false,
16698                }
16699            }
16700            if whole {
16701                self.task_children()?.insert(project, tasks);
16702            }
16703        }
16704        let mut resolved = self.resolved_cache()?;
16705        let mut ahead = self.read_ahead()?;
16706        let mut carried = self.carried()?;
16707        for item in read.iter().filter_map(|(_, held)| held.as_ref()) {
16708            resolved.insert(item.id.clone(), item.clone());
16709        }
16710        // Taken only if still carried: a mutation naming it while the batches ran dropped it,
16711        // and its next read is then its own.
16712        for id in &listed {
16713            let Some(item) = carried.remove(id) else {
16714                continue;
16715            };
16716            // The whole of what it is blocked by came with it, so the dependency read a copy
16717            // makes next is answered from this one, as a copy's detail read is.
16718            if item.blocked_by.is_some() {
16719                resolved.insert(item.id.clone(), item.clone());
16720            }
16721            read.push((id.clone(), Some(item)));
16722        }
16723        for (id, held) in read {
16724            ahead.insert(id, held);
16725        }
16726        Ok(())
16727    }
16728
16729    /// Add one comment to the task's issue, as the account the token belongs to.
16730    ///
16731    /// The author is refused before anything is sent — not even the task is read — because
16732    /// no answer GitHub could give would make posting under another name than the one asked
16733    /// for the right outcome.
16734    async fn add_comment(
16735        &self,
16736        task: &NativeId,
16737        comment: &NewComment,
16738    ) -> Result<Option<Comment>, SourceError> {
16739        if let Some(author) = &comment.author {
16740            return Err(SourceError::Refused {
16741                message: format!(
16742                    "source {} cannot post a comment as {author:?}: GitHub records the account \
16743                     the token signs in as the author of every comment; next: leave --author \
16744                     out, and the comment is posted as that account",
16745                    self.name
16746                ),
16747            });
16748        }
16749        let Some(issue) = self.commented_issue(task).await? else {
16750            return Ok(None);
16751        };
16752        let data = self
16753            .graphql(
16754                graphql::ADD_COMMENT,
16755                json!({"input":{"subjectId":issue.0,"body":comment.body.as_str()}}),
16756            )
16757            .await?;
16758        let subject = data
16759            .pointer("/addComment/subject")
16760            .filter(|value| !value.is_null())
16761            .ok_or_else(|| SourceError::Malformed {
16762                message: "GitHub comment addition returned no subject".into(),
16763            })?;
16764        if required_str(subject, "id")? != issue.0 {
16765            return Err(SourceError::Malformed {
16766                message: "GitHub comment addition answered about another issue".into(),
16767            });
16768        }
16769        let added = data
16770            .pointer("/addComment/commentEdge/node")
16771            .filter(|value| !value.is_null())
16772            .ok_or_else(|| SourceError::Malformed {
16773                message: "GitHub comment addition returned no comment".into(),
16774            })?;
16775        let added = comment_from(added)?;
16776        self.remember_commented(&issue)?;
16777        Ok(Some(added))
16778    }
16779
16780    /// Every task commented on read together — [`DETAIL_BATCH`] to a
16781    /// [`graphql::ISSUE_DETAILS`] request — and each comment's hold decided on that read; then
16782    /// every comment it lets through added by aliased `addComment`s of one
16783    /// [`graphql::ADD_COMMENTS`] request per [`COMMENT_BATCH`]. GitHub answers a refusal of one
16784    /// alias at that alias's path, so it fails that comment alone.
16785    ///
16786    /// **Where GitHub would refuse the batch as a whole, each item is read on its own:** a
16787    /// batched node read naming an id that resolves to nothing is refused whole, so each id of
16788    /// that batch is read by itself, the missing one answered missing. A batch of one is the
16789    /// comment alone, as [`Self::add_comment`] adds it.
16790    async fn add_comments(
16791        &self,
16792        comments: &[onetaskgraph_plugin_api::BatchComment],
16793    ) -> Vec<Result<onetaskgraph_plugin_api::BatchAnswer<Comment>, SourceError>> {
16794        self.comments_batched(comments).await
16795    }
16796
16797    async fn edit_comment(
16798        &self,
16799        task: &NativeId,
16800        comment: &NativeId,
16801        body: &CommentBody,
16802    ) -> Result<Option<Comment>, SourceError> {
16803        let Some(issue) = self.commented_issue(task).await? else {
16804            return Ok(None);
16805        };
16806        let Some(held) = self.comment_on(&issue, comment).await? else {
16807            return Ok(None);
16808        };
16809        // A comment a copy wrote keeps its origin through an edit: its marker is carried over.
16810        let body = CommentOrigin::kept(&held, body)?;
16811        let data = self
16812            .graphql(
16813                graphql::UPDATE_COMMENT,
16814                json!({"input":{"id":comment.0,"body":body.as_str()}}),
16815            )
16816            .await?;
16817        let edited = data
16818            .pointer("/updateIssueComment/issueComment")
16819            .filter(|value| !value.is_null())
16820            .ok_or_else(|| SourceError::Malformed {
16821                message: "GitHub comment update returned no comment".into(),
16822            })?;
16823        let edited = comment_from(edited)?;
16824        if edited.id != *comment {
16825            return Err(SourceError::Malformed {
16826                message: "GitHub comment update returned the wrong comment".into(),
16827            });
16828        }
16829        self.remember_commented(&issue)?;
16830        Ok(Some(edited))
16831    }
16832
16833    async fn delete_comment(
16834        &self,
16835        task: &NativeId,
16836        comment: &NativeId,
16837    ) -> Result<Option<NativeId>, SourceError> {
16838        let Some(issue) = self.commented_issue(task).await? else {
16839            return Ok(None);
16840        };
16841        if !self.comment_is_on(&issue, comment).await? {
16842            return Ok(None);
16843        }
16844        self.held_comments()?.remove(&issue);
16845        let data = self
16846            .graphql(graphql::DELETE_COMMENT, json!({"input":{"id":comment.0}}))
16847            .await?;
16848        // The payload says nothing about the comment it removed, so what is checked is that
16849        // GitHub answered the mutation at all rather than leaving it unanswered.
16850        data.get("deleteIssueComment")
16851            .filter(|value| !value.is_null())
16852            .ok_or_else(|| SourceError::Malformed {
16853                message: "GitHub comment deletion returned no payload".into(),
16854            })?;
16855        Ok(Some(comment.clone()))
16856    }
16857
16858    /// Every request this source has recorded, and what each of GitHub's two budgets was
16859    /// attributed — read off the same accounting the session report is rendered from, so
16860    /// the two cannot count one request two ways.
16861    async fn metering(&self) -> Result<Option<Metering>, SourceError> {
16862        Ok(Some(self.ledger.snapshot().metering()))
16863    }
16864
16865    /// One `GET /rate_limit` at this source's endpoint, every resource it reports, asked
16866    /// afresh each time and counted in nothing [`metering`](TaskSource::metering) reports:
16867    /// GitHub documents the endpoint as free. See [`quota`].
16868    async fn quota(&self) -> Result<Vec<onetaskgraph_plugin_api::QuotaReading>, SourceError> {
16869        self.rate_limits().await
16870    }
16871
16872    /// Drop every item, search answer and board read this source holds, so the next command
16873    /// reads the board as a person has since left it.
16874    ///
16875    /// Every one of those is held on the assumption that nothing but this source writes the
16876    /// board while a command runs, which stops being true the moment the command is over: a
16877    /// body a person edited would be overwritten from the record held here, and a card they
16878    /// moved would be read as still where this source left it. The board's own field
16879    /// definitions go too, because a person can add or delete a `Status` option and a write
16880    /// resolved against the held list would not re-read on a miss. What stays is what stays
16881    /// valid in normal use: each repository's node id, which a miss re-reads, the pacing of
16882    /// mutations, which is about GitHub's limiter rather than anybody's work, and the running
16883    /// accounting [`metering`](TaskSource::metering) answers from.
16884    ///
16885    /// Infallible in practice: a lock an earlier failure poisoned is cleared rather than
16886    /// refused, because clearing it is what puts it right.
16887    async fn end_command(&self) -> Result<(), SourceError> {
16888        fn clear<T: Default>(held: &Mutex<T>) {
16889            *held
16890                .lock()
16891                .unwrap_or_else(std::sync::PoisonError::into_inner) = T::default();
16892            held.clear_poison();
16893        }
16894        clear(&self.created);
16895        clear(&self.updated);
16896        clear(&self.commented);
16897        clear(&self.board_cache);
16898        clear(&self.search_cache);
16899        clear(&self.narrowed_cache);
16900        clear(&self.search_next);
16901        clear(&self.resolved_cache);
16902        clear(&self.read_ahead);
16903        clear(&self.pending_origins);
16904        clear(&self.member_classes);
16905        clear(&self.carried);
16906        clear(&self.held_cache);
16907        clear(&self.children_cache);
16908        clear(&self.task_children);
16909        clear(&self.written);
16910        clear(&self.fields_cache);
16911        clear(&self.held_comments);
16912        clear(&self.task_writes);
16913        clear(&self.written_tokens);
16914        self.forget_at_end_of_call();
16915        self.expected.end_command();
16916        Ok(())
16917    }
16918}
16919
16920/// One member of a project as a classification-only read answers it: its classification and
16921/// the repositories its work changes.
16922type MemberClass = (Classification, Vec<Repository>);
16923
16924/// Each project's sub-issues as one command read them, keyed by the selector they were asked
16925/// for under, beside the project that selector named; see `children_cache`.
16926type ProjectChildren = BTreeMap<NativeId, (NativeId, Vec<Resolved>)>;
16927
16928/// One issue comment as the contract carries it.
16929///
16930/// `author` is absent both when GitHub answers `null` for an account that no longer exists
16931/// and when it answers an actor with no login, because either way the source did not say who
16932/// wrote it — which is what an absent author means, rather than an author called nothing.
16933///
16934/// A comment a copy wrote here carries its origin as the hidden marker at the end of its body
16935/// — GitHub sets every comment's author and times itself, so there is nowhere else to keep it —
16936/// and is read back with the marker taken out and reported as its origin.
16937fn comment_from(value: &Value) -> Result<Comment, SourceError> {
16938    let actor = value.get("author").unwrap_or(&Value::Null);
16939    // A bot's login is spelled as GitHub's own pages spell it, `<login>[bot]`, so a reader —
16940    // and every copy of the comment — can tell it from a person's.
16941    let bot = actor.get("__typename").and_then(Value::as_str) == Some("Bot");
16942    Ok(Comment {
16943        origin: None,
16944        id: NativeId(required_str(value, "id")?.to_owned()),
16945        author: optional_str(actor, "login")?.map(|login| {
16946            if bot && !login.ends_with("[bot]") {
16947                format!("{login}[bot]")
16948            } else {
16949                login.to_owned()
16950            }
16951        }),
16952        created_at: optional_time(value, "createdAt")?,
16953        updated_at: optional_time(value, "updatedAt")?,
16954        body: required_str(value, "body")?.to_owned(),
16955        url: optional_str(value, "url")?.map(str::to_owned),
16956    }
16957    .unmarked())
16958}
16959
16960/// The page of comments one issue node carries, resumed from `after`.
16961fn comment_page(
16962    node: &Value,
16963    issue: &str,
16964    after: Option<&str>,
16965) -> Result<Page<Comment>, SourceError> {
16966    let connection = node
16967        .get("comments")
16968        .filter(|value| !value.is_null())
16969        .ok_or_else(|| SourceError::Malformed {
16970            message: format!("GitHub issue {issue} answered with no comments connection"),
16971        })?;
16972    let items = optional_nodes(Some(connection), "issue comments")?
16973        .into_iter()
16974        .flatten()
16975        .map(comment_from)
16976        .collect::<Result<Vec<_>, _>>()?;
16977    let next = next_cursor(connection)?;
16978    if let Some(next) = &next {
16979        validate_cursor_progress(after, &next.0)?;
16980    }
16981    Ok(Page { items, next })
16982}
16983
16984/// The far ends of an issue's whole `blockedBy` connection, when the read carried it to its
16985/// end — `None` when it carried none, or a page with more past it.
16986fn carried_blocked_by(content: &Value) -> Result<Option<Vec<Value>>, SourceError> {
16987    let Some(connection) = content.get("blockedBy").filter(|value| !value.is_null()) else {
16988        return Ok(None);
16989    };
16990    if next_cursor(connection)?.is_some() {
16991        return Ok(None);
16992    }
16993    Ok(Some(
16994        optional_nodes(Some(connection), "blocked-by issues")?
16995            .into_iter()
16996            .flatten()
16997            .cloned()
16998            .collect(),
16999    ))
17000}
17001
17002/// Where the recorded tail of a dependency walk resumes; see
17003/// [`GitHubProjectsSource::recorded_edges`].
17004const RECORDED_CURSOR: &str = "onetaskgraph.depends_on:";
17005
17006/// The board text field this source keeps a copy's origin in.
17007///
17008/// Named after the key it holds, and held to that name by the guard below rather than by
17009/// a reader noticing.
17010const ORIGIN_FIELD: &str = "onetaskgraph.origin";
17011
17012/// The metadata key that field holds.
17013///
17014/// The engine owns this key and spells it once as `GlobalId::ORIGIN_KEY`; a plugin never
17015/// constructs or interprets the qualified id it carries. This source names it only to
17016/// route it — a short, typed value belongs in a typed field rather than in the body slot
17017/// a caller's own prose shares.
17018///
17019/// Restated rather than imported, because no plugin crate may depend on the engine. What
17020/// keeps the two spellings one contract is `scripts/check-origin-key-spelling.sh`, a
17021/// target in `check`: it reads the engine's own literal and fails naming the file and the
17022/// line when a plugin's parts from it either way. Drift here has one symptom — a copy
17023/// that creates a second item every run instead of finding the one it wrote — and that is
17024/// too late to learn it.
17025const ORIGIN_KEY: &str = "onetaskgraph.origin";
17026
17027/// Where a recorded tail resumes, refusing a cursor no walk in `direction` reported.
17028///
17029/// The reserved key holds forward edges and nothing else — the reverse of a recorded edge
17030/// is derived from the far end, never written down on the near item — so only a forward
17031/// walk ever reports one of these cursors. A reverse read carrying one is resuming a walk
17032/// it did not come from, and it is told so rather than answered with an empty page that
17033/// reads as a walk which ended.
17034fn recorded_offset(
17035    cursor: Option<&str>,
17036    direction: Direction,
17037) -> Result<Option<usize>, SourceError> {
17038    cursor
17039        .and_then(|cursor| cursor.strip_prefix(RECORDED_CURSOR))
17040        .map(|offset| {
17041            if direction != Direction::DependsOn {
17042                return Err(SourceError::Config {
17043                    message: format!(
17044                        "{RECORDED_CURSOR}{offset} resumes recorded forward edges, which a \
17045                         reverse dependency read never issues; resume it in the direction \
17046                         that reported it"
17047                    ),
17048                });
17049            }
17050            offset.parse().map_err(|_| SourceError::Config {
17051                message: format!("{RECORDED_CURSOR}{offset} is not a recorded-edge cursor"),
17052            })
17053        })
17054        .transpose()
17055}
17056
17057/// What a dependency read's own answer says of a board draft: `None` when the item is not a
17058/// draft, or the answer did not carry its board item; `Some(None)` for a draft whose one board
17059/// item is not on this board, which this source does not hold; and `Some(Some(slot))`, the
17060/// draft's metadata, for one it does — its board item naming this board by its number and by
17061/// the id the same answer read of the board, as [`GitHubProjectsSource::draft_by_id`] decides.
17062fn draft_slot(
17063    data: &Value,
17064    id: &NativeId,
17065    project_number: u32,
17066) -> Result<Option<Option<BTreeMap<String, Value>>>, SourceError> {
17067    let Some(draft) = data
17068        .get("node")
17069        .filter(|node| node.get("__typename").and_then(Value::as_str) == Some("DraftIssue"))
17070    else {
17071        return Ok(None);
17072    };
17073    let Some(items) = data.pointer("/draft/projectV2Items") else {
17074        return Ok(None);
17075    };
17076    if required_str(draft, "id")? != id.0 {
17077        return Err(SourceError::Malformed {
17078            message: format!("GitHub answered a different draft for {}", id.0),
17079        });
17080    }
17081    let nodes = items
17082        .get("nodes")
17083        .and_then(Value::as_array)
17084        .ok_or_else(|| SourceError::Malformed {
17085            message: format!("GitHub draft {} projectV2Items.nodes is not an array", id.0),
17086        })?;
17087    let info = items
17088        .get("pageInfo")
17089        .ok_or_else(|| SourceError::Malformed {
17090            message: format!("GitHub draft {} projectV2Items has no pageInfo", id.0),
17091        })?;
17092    if required_bool(info, "hasNextPage")? || nodes.len() > 1 {
17093        return Err(SourceError::Malformed {
17094            message: format!(
17095                "GitHub draft {} reports more board items than the one GitHub links a draft to",
17096                id.0
17097            ),
17098        });
17099    }
17100    let board = data
17101        .pointer("/board/projectV2/id")
17102        .and_then(Value::as_str)
17103        .ok_or_else(|| SourceError::Malformed {
17104            message: format!(
17105                "GitHub answered draft {} without this board's own id beside it",
17106                id.0
17107            ),
17108        })?;
17109    let mut held = false;
17110    for node in nodes {
17111        let project = node.get("project").ok_or_else(|| SourceError::Malformed {
17112            message: format!("GitHub draft {} board item has no project", id.0),
17113        })?;
17114        let number = project
17115            .get("number")
17116            .and_then(Value::as_u64)
17117            .ok_or_else(|| SourceError::Malformed {
17118                message: format!(
17119                    "GitHub draft {} board item has no numeric project number",
17120                    id.0
17121                ),
17122            })?;
17123        let project_id = required_str(project, "id")?;
17124        held |= number == u64::from(project_number) && project_id == board;
17125    }
17126    if !held {
17127        return Ok(Some(None));
17128    }
17129    Ok(Some(Some(
17130        metadata_body(optional_str(draft, "body")?.map(str::to_owned))?.1,
17131    )))
17132}
17133
17134fn recorded_page(edges: Vec<DependencyEdge>, offset: usize, limit: usize) -> Page<DependencyEdge> {
17135    let mut page = offset_page(edges, offset, limit.max(1));
17136    page.next = page
17137        .next
17138        .map(|cursor| Cursor(format!("{RECORDED_CURSOR}{}", cursor.0)));
17139    page
17140}
17141
17142/// The kind of one issue reached through a dependency connection.
17143///
17144/// The same questions the board scan asks, over the fields the dependency document
17145/// selects, and in the same order: the design prefix first, then a sub-issue is a task,
17146/// then anything with sub-issues or the marker is a project.
17147///
17148/// # Errors
17149///
17150/// A far end this board holds as a document is refused rather than reported. The two
17151/// answers that are not refusals would both be wrong: reporting it as a task names an id
17152/// no task read of this source can find, and reporting it as a project names one no
17153/// project read can. There is no third value to return — `ItemKind` has no document
17154/// variant, because nothing may point at a document — so the relationship itself is what
17155/// the person is told about.
17156fn related_kind(value: &Value, meaning: SubIssues) -> Result<ItemKind, SourceError> {
17157    let id = required_str(value, "id")?;
17158    if required_str(value, "title")?.starts_with(DESIGN_TITLE_PREFIX) {
17159        return Err(SourceError::Refused {
17160            message: format!(
17161                "GitHub issue {id} is a document of this board — its title begins \
17162                 {DESIGN_TITLE_PREFIX:?} — and nothing may depend on a document or be depended \
17163                 on by one; next: remove that issue's blocking relationship on this board"
17164            ),
17165        });
17166    }
17167    let parent = optional_str(value.get("parent").unwrap_or(&Value::Null), "id")?;
17168    if parent.is_some() || meaning == SubIssues::Parent {
17169        return Ok(ItemKind::Task);
17170    }
17171    let (_, slot) = metadata_body(optional_str(value, "body")?.map(str::to_owned))?;
17172    let marked = ItemKind::from_metadata(&slot).map_err(|message| SourceError::Malformed {
17173        message: format!("GitHub issue {id}: {message}"),
17174    })?;
17175    let sub_issues = sub_issue_total(value)?;
17176    Ok(if sub_issues > 0 || marked == Some(ItemKind::Project) {
17177        ItemKind::Project
17178    } else {
17179        ItemKind::Task
17180    })
17181}
17182
17183/// The reason GitHub records an issue closed as a duplicate of another under.
17184const DUPLICATE_REASON: &str = "DUPLICATE";
17185
17186/// The `stateInput` that closes an issue for `reason`.
17187fn closed_input(reason: ClosedState) -> Value {
17188    json!({"value":"CLOSED","stateReason":reason.reason()})
17189}
17190
17191/// The `IssueStateUpdateInput` one status target asks for.
17192///
17193/// `stateInput` and `state` are mutually exclusive on `UpdateIssueInput`, and only this
17194/// one is ever sent. A non-terminal status always asks for `OPEN`, which is what reopens
17195/// a currently-closed issue: without that the item would read back `Unknown` and a copy
17196/// would report a change forever. A document has no status at all, and asks for neither.
17197fn state_input(target: Option<&StatusTarget>) -> Value {
17198    match target {
17199        Some(StatusTarget::Terminal(_, reason)) => closed_input(*reason),
17200        Some(StatusTarget::Column(_) | StatusTarget::Disabled(_)) => json!({"value":"OPEN"}),
17201        // A document has no status, so a write of one says nothing about the issue's open
17202        // or closed state rather than forcing it open: `stateInput` is what carries that
17203        // instruction, and an explicit null asks for no change to it.
17204        None => Value::Null,
17205    }
17206}
17207
17208/// The metadata one write stores in the item's body slot.
17209///
17210/// The typed fields travel as themselves, so the three reserved keys are rebuilt here
17211/// rather than carried: the kind marker so an empty project stays readable, the
17212/// repository list only when it is not exactly the issue's own repository, and the far
17213/// ends no relationship here can name.
17214///
17215/// The copy origin is the one typed field that is also mirrored here, and only as a
17216/// mirror: it lands in the board's origin field as well, which stays the one every reader
17217/// takes it from, and it is here so that GitHub's issue search — which indexes this comment
17218/// and catches up with a write in seconds rather than minutes — can find the item by it.
17219/// A reader of the release before this one drops the slot's copy and reads the field, so an
17220/// item written here still reads with exactly one origin there.
17221fn slot_metadata(
17222    incoming: &Incoming<'_>,
17223    own_repository: Option<&Repository>,
17224    fallback: &[DependencyEdge],
17225) -> BTreeMap<String, Value> {
17226    let mut metadata = incoming.metadata.clone();
17227    match metadata.remove(ORIGIN_KEY) {
17228        Some(Value::String(origin)) if !origin.is_empty() => {
17229            metadata.insert(ORIGIN_KEY.to_owned(), Value::String(origin));
17230        }
17231        _ => {}
17232    }
17233    match incoming.written.kind() {
17234        BoardKind::Work(kind) => metadata.insert(
17235            ItemKind::METADATA_KEY.to_owned(),
17236            Value::String(kind.marker().to_owned()),
17237        ),
17238        // A document is told by its title, so it carries no kind marker: that key names
17239        // what a dependency endpoint points at, and nothing may point at a document.
17240        BoardKind::Document => metadata.remove(ItemKind::METADATA_KEY),
17241    };
17242    incoming.classification.record(&mut metadata);
17243    let derivable = own_repository
17244        .map(|own| incoming.repositories == [own.clone()])
17245        .unwrap_or(incoming.repositories.is_empty());
17246    if derivable {
17247        metadata.remove(Repository::METADATA_KEY);
17248    } else {
17249        metadata.insert(
17250            Repository::METADATA_KEY.to_owned(),
17251            Value::Array(
17252                incoming
17253                    .repositories
17254                    .iter()
17255                    .map(|repository| Value::String(repository.as_str().to_owned()))
17256                    .collect(),
17257            ),
17258        );
17259    }
17260    // The typed lists are what land, whatever the caller's own metadata held under their
17261    // keys: a key of either name travelling beside the field would otherwise be a second
17262    // answer to the same question, and the field is the one the contract names.
17263    for (key, entries) in [
17264        (TaskRef::DELIVERS_KEY, incoming.delivers),
17265        (TaskRef::DELIVERED_BY_KEY, incoming.delivered_by),
17266    ] {
17267        set_task_list(&mut metadata, key, entries);
17268    }
17269    record_edges(&mut metadata, fallback);
17270    metadata
17271}
17272
17273/// Hold the far ends no relationship here can name under [`DependencyEdge::RECORDED_KEY`] in
17274/// one slot's metadata, or no such key when there are none.
17275fn record_edges(metadata: &mut BTreeMap<String, Value>, fallback: &[DependencyEdge]) {
17276    if fallback.is_empty() {
17277        metadata.remove(DependencyEdge::RECORDED_KEY);
17278    } else {
17279        metadata.insert(
17280            DependencyEdge::RECORDED_KEY.to_owned(),
17281            Value::Array(
17282                fallback
17283                    .iter()
17284                    .map(|edge| {
17285                        serde_json::to_value(&edge.to).expect("an endpoint renders as JSON")
17286                    })
17287                    .collect(),
17288            ),
17289        );
17290    }
17291}
17292
17293/// Every label one item carries, from its content's own connection and nowhere else.
17294///
17295/// There is no second place to read one from: no document this source sends selects the
17296/// board's built-in `Labels` field, because GitHub derives it from the content and a draft
17297/// cannot carry one at all. The module documentation records the three schema facts that
17298/// settle it.
17299fn labels(content: &Value) -> Result<Vec<Label>, SourceError> {
17300    optional_nodes(content.get("labels"), "content labels")?
17301        .into_iter()
17302        .flatten()
17303        .map(|v| {
17304            Ok(Label {
17305                id: NativeId(required_str(v, "id")?.to_owned()),
17306                name: required_str(v, "name")?.to_owned(),
17307                color: optional_str(v, "color")?.map(str::to_owned),
17308            })
17309        })
17310        .collect()
17311}
17312
17313/// Each board field value one item holds, as the change token's facets name it: the field's
17314/// name, with the single-select option's name or the text. A value of a type no read here
17315/// selects, and one naming no field, says nothing a person can rename and is left out.
17316fn facet_fields(field_values: &[Value]) -> Vec<(String, String)> {
17317    field_values
17318        .iter()
17319        .filter_map(|value| {
17320            let field = value.pointer("/field/name")?.as_str()?;
17321            let held = value.get("name").or_else(|| value.get("text"))?.as_str()?;
17322            Some((field.to_owned(), held.to_owned()))
17323        })
17324        .collect()
17325}
17326
17327/// The digest of the facets of the issue `content`, whose board item's values are
17328/// `field_values` — or `None` when the response did not carry, whole, every member they are read
17329/// from: the title, the parent, the sub-issue summary and the body its kind is read from, every
17330/// label, and every field value.
17331///
17332/// What a write's own response spells its token from, by exactly the rules a read takes them by.
17333fn facets_of(content: &Value, field_values: &Value) -> Option<change_token::FacetsDigest> {
17334    let ended = |connection: &Value| {
17335        connection.pointer("/pageInfo/hasNextPage") == Some(&Value::Bool(false))
17336    };
17337    let labels = content.get("labels").filter(|labels| ended(labels))?;
17338    if !ended(field_values) {
17339        return None;
17340    }
17341    let parent = content.get("parent")?;
17342    let (_, slot) = metadata_body(content.get("body")?.as_str().map(str::to_owned)).ok()?;
17343    let kind = BoardKind::of(
17344        content.get("title")?.as_str()?,
17345        !parent.is_null(),
17346        sub_issue_total(content).ok()?,
17347        ItemKind::from_metadata(&slot).ok()?,
17348    );
17349    let labels = self::labels(&json!({"labels": labels})).ok()?;
17350    let nodes = field_values.get("nodes")?.as_array()?;
17351    Some(change_token::Facets::new(kind.facet(), facet_fields(nodes), &labels).digest())
17352}
17353
17354/// The definition of each board field one item's values are values of, in the shape a read
17355/// of the board's own `fields` gives one.
17356///
17357/// A value names its field through a fragment on that field's own type, so the type is
17358/// known from which kind of value it is: a single-select value's field is a
17359/// `ProjectV2SingleSelectField`, options and all, and a text value's is a `ProjectV2Field`.
17360/// A value whose field carried no id, or an empty one, says nothing usable and is left out.
17361fn field_definitions(field_values: &[Value]) -> Vec<Value> {
17362    field_values
17363        .iter()
17364        .filter_map(|value| {
17365            let field = value.get("field")?.as_object()?;
17366            field.get("id")?.as_str().filter(|id| !id.is_empty())?;
17367            let typename = if value.get("text").is_some() {
17368                "ProjectV2Field"
17369            } else if value.get("name").is_some() {
17370                "ProjectV2SingleSelectField"
17371            } else {
17372                return None;
17373            };
17374            let mut defined = field.clone();
17375            defined.insert("__typename".to_owned(), json!(typename));
17376            // Only a text field holds a text value, so the value says the field's type too.
17377            if typename == "ProjectV2Field" {
17378                defined.insert("dataType".to_owned(), json!("TEXT"));
17379            }
17380            Some(Value::Object(defined))
17381        })
17382        .collect()
17383}
17384
17385fn text_field(field_values: &[Value], name: &str) -> Result<Option<String>, SourceError> {
17386    let Some(node) = field_values
17387        .iter()
17388        .find(|node| node.pointer("/field/name").and_then(Value::as_str) == Some(name))
17389    else {
17390        return Ok(None);
17391    };
17392    Ok(optional_str(node, "text")?.map(str::to_owned))
17393}
17394
17395fn valid_github_owner(owner: &str) -> bool {
17396    !owner.is_empty()
17397        && owner.len() <= 39
17398        && !owner.starts_with('-')
17399        && !owner.ends_with('-')
17400        && !owner.contains("--")
17401        && owner
17402            .bytes()
17403            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
17404}
17405
17406/// GitHub's repository-name grammar: 1-100 ASCII letters, digits, `-`, `_` or `.`, and
17407/// neither of the two names a path segment already means.
17408fn valid_github_repository_name(name: &str) -> bool {
17409    !name.is_empty()
17410        && name.len() <= 100
17411        && name != "."
17412        && name != ".."
17413        && name
17414            .bytes()
17415            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
17416}
17417
17418fn valid_environment_name(name: &str) -> bool {
17419    let mut bytes = name.bytes();
17420    bytes
17421        .next()
17422        .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
17423        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
17424}
17425
17426/// How many sub-issues one issue has.
17427///
17428/// `Issue.subIssuesSummary` is `SubIssuesSummary!` and its `total` is `Int!`, so an
17429/// absent or non-integer one is a response this source cannot read — and reading it as
17430/// zero would classify a project as a task, which is exactly the mistake the marker
17431/// exists to keep from happening quietly.
17432fn sub_issue_total(issue: &Value) -> Result<u64, SourceError> {
17433    let summary = issue
17434        .get("subIssuesSummary")
17435        .ok_or_else(|| SourceError::Malformed {
17436            message: "GitHub issue is missing subIssuesSummary".into(),
17437        })?;
17438    summary
17439        .get("total")
17440        .and_then(Value::as_u64)
17441        .ok_or_else(|| SourceError::Malformed {
17442            message: "GitHub issue subIssuesSummary.total is not an unsigned integer".into(),
17443        })
17444}
17445
17446/// One issue's own `number`.
17447///
17448/// An issue always has one: GitHub declares `Issue.number` as `Int!` and every selection of
17449/// an issue in this module asks for it. So a read of one that comes back without it, or
17450/// with something that is not an unsigned integer, is a response this source cannot read —
17451/// absence here is **not** "this issue has no number". A draft is the content that has
17452/// none, and a draft never reaches this: the caller decides on `__typename` first, the way
17453/// it does for `subIssuesSummary`, which `DraftIssue` equally declares nothing for.
17454fn issue_number(issue: &Value) -> Result<u64, SourceError> {
17455    issue
17456        .get("number")
17457        .and_then(Value::as_u64)
17458        .ok_or_else(|| SourceError::Malformed {
17459            message: "GitHub issue number is missing or is not an unsigned integer".into(),
17460        })
17461}
17462
17463/// The `number` a creating mutation answered with, and `None` when it answered without one;
17464/// why a missing one is tolerated is at the call in `create_and_file_issue`.
17465fn created_issue_number(created: &Value) -> Result<Option<u64>, SourceError> {
17466    match created.get("number") {
17467        None | Some(Value::Null) => Ok(None),
17468        Some(value) => value
17469            .as_u64()
17470            .map(Some)
17471            .ok_or_else(|| SourceError::Malformed {
17472                message: "GitHub created issue number is not an unsigned integer".into(),
17473            }),
17474    }
17475}
17476
17477fn required_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
17478    value
17479        .get(field)
17480        .and_then(Value::as_str)
17481        .ok_or_else(|| SourceError::Malformed {
17482            message: format!("GitHub response is missing string field {field}"),
17483        })
17484}
17485
17486fn required_nonblank_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
17487    let found = required_str(value, field)?;
17488    if found.trim().is_empty() {
17489        return Err(SourceError::Malformed {
17490            message: format!("GitHub response has blank string field {field}"),
17491        });
17492    }
17493    Ok(found)
17494}
17495
17496/// The slot's delimiters, which `docs/metadata.md` settles once for every source that
17497/// needs one — Linear spells them too, in its own description field.
17498///
17499/// Restated rather than shared, because a plugin crate depends on the contract crate and
17500/// nothing else of this workspace. `scripts/check-metadata-slot-encoding.sh`, a target in
17501/// `check`, is what keeps the two one encoding: drift is otherwise quiet, since each
17502/// source round-trips its own writes perfectly well under its own spelling.
17503const METADATA_OPEN: &str = "<!-- onetaskgraph.metadata\n";
17504const METADATA_CLOSE: &str = "\n-->";
17505
17506/// What the composer puts between a non-empty visible body and the slot, and the one thing
17507/// the parser takes off the visible body when it takes the slot off — exactly once, so every
17508/// other trailing byte of the body comes back as it was written.
17509// llmlint: ignore[contracts_have_one_source_or_a_drift_gate] How a composer lays the slot after prose is this source's own; `docs/metadata.md` and its gate settle only the delimiters, and no other source declares a separator to reconcile against.
17510const METADATA_SEPARATOR: &str = "\n\n";
17511
17512/// The visible body and the metadata slot at the end of it.
17513///
17514/// The encoding is the one `docs/metadata.md` settles for Linear, which is where its
17515/// reasons are. Only a comment at the very end is a slot; one in the middle is a person's
17516/// own content and is left alone. The visible body is everything before the slot less the
17517/// one [`METADATA_SEPARATOR`] the composer put there, byte for byte.
17518fn metadata_body(
17519    body: Option<String>,
17520) -> Result<(Option<String>, BTreeMap<String, Value>), SourceError> {
17521    let Some(body) = body else {
17522        return Ok((None, BTreeMap::new()));
17523    };
17524    let Some(slot) = slot_span(&body)? else {
17525        return Ok((Some(body), BTreeMap::new()));
17526    };
17527    let metadata =
17528        serde_json::from_str(&body[slot.encoded_start..slot.encoded_end]).map_err(|error| {
17529            SourceError::Malformed {
17530                message: format!(
17531                    "invalid canonical JSON in GitHub issue onetaskgraph metadata slot: {error}"
17532                ),
17533            }
17534        })?;
17535    let before = &body[..slot.start];
17536    let visible = before.strip_suffix(METADATA_SEPARATOR).unwrap_or(before);
17537    Ok(((!visible.is_empty()).then(|| visible.to_owned()), metadata))
17538}
17539
17540/// Where the metadata slot sits in one body, as byte offsets into it.
17541struct SlotSpan {
17542    /// Where [`METADATA_OPEN`] begins.
17543    start: usize,
17544    /// Where the encoded JSON begins, just past [`METADATA_OPEN`].
17545    encoded_start: usize,
17546    /// Where the encoded JSON ends, at the start of [`METADATA_CLOSE`].
17547    encoded_end: usize,
17548    /// Just past [`METADATA_CLOSE`].
17549    end: usize,
17550}
17551
17552/// The slot at the very end of `body`, or `None` when it has none.
17553///
17554/// The one reading of *where the slot is*, shared by [`metadata_body`], which reads it, and
17555/// [`with_slot`], which rewrites it — so the two cannot disagree about which comment is the
17556/// slot.
17557fn slot_span(body: &str) -> Result<Option<SlotSpan>, SourceError> {
17558    let Some(start) = body.rfind(METADATA_OPEN) else {
17559        return Ok(None);
17560    };
17561    let encoded_start = start + METADATA_OPEN.len();
17562    let Some(relative_end) = body[encoded_start..].find(METADATA_CLOSE) else {
17563        return Err(SourceError::Malformed {
17564            message: "unterminated onetaskgraph metadata slot in GitHub issue body".into(),
17565        });
17566    };
17567    let encoded_end = encoded_start + relative_end;
17568    let end = encoded_end + METADATA_CLOSE.len();
17569    if !body[end..].trim().is_empty() {
17570        return Ok(None);
17571    }
17572    Ok(Some(SlotSpan {
17573        start,
17574        encoded_start,
17575        encoded_end,
17576        end,
17577    }))
17578}
17579
17580/// `body` with its metadata slot holding exactly `metadata`, and every byte outside the
17581/// slot as it was.
17582///
17583/// A slot that is there has its JSON replaced in place; one that becomes empty is removed
17584/// together with the one [`METADATA_SEPARATOR`] separating it from the prose before it. A
17585/// body with no slot gains one the way [`compose_body`] writes it — after that separator,
17586/// or alone in an empty body — and a body with no slot that is given no metadata is
17587/// returned as it is.
17588fn with_slot(body: &str, metadata: &BTreeMap<String, Value>) -> Result<String, SourceError> {
17589    let encoded = if metadata.is_empty() {
17590        None
17591    } else {
17592        Some(
17593            serde_json::to_string(metadata).map_err(|error| SourceError::Malformed {
17594                message: error.to_string(),
17595            })?,
17596        )
17597    };
17598    Ok(match (slot_span(body)?, encoded) {
17599        (Some(slot), Some(encoded)) => format!(
17600            "{}{encoded}{}",
17601            &body[..slot.encoded_start],
17602            &body[slot.encoded_end..]
17603        ),
17604        (Some(slot), None) => {
17605            let before = &body[..slot.start];
17606            format!(
17607                "{}{}",
17608                before.strip_suffix(METADATA_SEPARATOR).unwrap_or(before),
17609                &body[slot.end..]
17610            )
17611        }
17612        (None, None) => body.to_owned(),
17613        (None, Some(encoded)) if body.is_empty() => {
17614            format!("{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17615        }
17616        (None, Some(encoded)) => {
17617            format!("{body}{METADATA_SEPARATOR}{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17618        }
17619    })
17620}
17621
17622/// `body` with everything before its metadata slot replaced by `content`, and the slot
17623/// itself kept byte for byte.
17624///
17625/// The inverse of how [`metadata_body`] splits a body: the slot, when there is one, follows
17626/// `content` after the one [`METADATA_SEPARATOR`] the composer puts there — or alone, when
17627/// `content` is empty — so a read of the result reports `content` as the visible body and
17628/// the slot's metadata exactly as it was.
17629fn with_content(body: &str, content: &str) -> Result<String, SourceError> {
17630    let Some(slot) = slot_span(body)? else {
17631        return Ok(content.to_owned());
17632    };
17633    let kept = &body[slot.start..];
17634    Ok(if content.is_empty() {
17635        kept.to_owned()
17636    } else {
17637        format!("{content}{METADATA_SEPARATOR}{kept}")
17638    })
17639}
17640
17641/// Hold `entries` under `key` in one slot's metadata, or no such key when there are none.
17642fn set_task_list(metadata: &mut BTreeMap<String, Value>, key: &str, entries: &[TaskRef]) {
17643    if entries.is_empty() {
17644        metadata.remove(key);
17645    } else {
17646        metadata.insert(
17647            key.to_owned(),
17648            Value::Array(
17649                entries
17650                    .iter()
17651                    .map(|entry| Value::String(entry.as_str().to_owned()))
17652                    .collect(),
17653            ),
17654        );
17655    }
17656}
17657
17658fn compose_body(
17659    content: Option<&str>,
17660    metadata: &BTreeMap<String, Value>,
17661) -> Result<Option<String>, SourceError> {
17662    let visible = content.unwrap_or_default();
17663    if metadata.is_empty() {
17664        return Ok((!visible.is_empty()).then(|| visible.to_owned()));
17665    }
17666    let encoded = serde_json::to_string(metadata).map_err(|error| SourceError::Malformed {
17667        message: error.to_string(),
17668    })?;
17669    Ok(Some(if visible.is_empty() {
17670        format!("{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17671    } else {
17672        format!("{visible}{METADATA_SEPARATOR}{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17673    }))
17674}
17675
17676fn required_bool(value: &Value, field: &str) -> Result<bool, SourceError> {
17677    value
17678        .get(field)
17679        .and_then(Value::as_bool)
17680        .ok_or_else(|| SourceError::Malformed {
17681            message: format!("GitHub response is missing boolean field {field}"),
17682        })
17683}
17684fn optional_str<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>, SourceError> {
17685    match value.get(field) {
17686        None | Some(Value::Null) => Ok(None),
17687        Some(value) => value
17688            .as_str()
17689            .map(Some)
17690            .ok_or_else(|| SourceError::Malformed {
17691                message: format!("GitHub response field {field} is not a string or null"),
17692            }),
17693    }
17694}
17695fn optional_nodes<'a>(
17696    connection: Option<&'a Value>,
17697    name: &str,
17698) -> Result<Option<&'a Vec<Value>>, SourceError> {
17699    match connection {
17700        None | Some(Value::Null) => Ok(None),
17701        Some(value) => value
17702            .get("nodes")
17703            .and_then(Value::as_array)
17704            .map(Some)
17705            .ok_or_else(|| SourceError::Malformed {
17706                message: format!("GitHub {name}.nodes is not an array"),
17707            }),
17708    }
17709}
17710fn complete_connection(connection: &Value, name: &str, size: u32) -> Result<(), SourceError> {
17711    let page_info = connection
17712        .get("pageInfo")
17713        .ok_or_else(|| SourceError::Malformed {
17714            message: format!("GitHub {name} has no pageInfo"),
17715        })?;
17716    if required_bool(page_info, "hasNextPage")? {
17717        return Err(SourceError::Malformed {
17718            message: format!(
17719                "GitHub {name} exceeds the supported nested connection size of {size}"
17720            ),
17721        });
17722    }
17723    Ok(())
17724}
17725fn optional_time(value: &Value, field: &str) -> Result<Option<DateTime<Utc>>, SourceError> {
17726    optional_str(value, field)?
17727        .map(|timestamp| {
17728            timestamp.parse().map_err(|error| SourceError::Malformed {
17729                message: format!("GitHub response field {field} is not a timestamp: {error}"),
17730            })
17731        })
17732        .transpose()
17733}
17734fn validate_page(page: &PageRequest) -> Result<(), SourceError> {
17735    if page.limit == 0 {
17736        Err(SourceError::Config {
17737            message: "page limit must be at least 1".into(),
17738        })
17739    } else {
17740        Ok(())
17741    }
17742}
17743fn next_cursor(connection: &Value) -> Result<Option<Cursor>, SourceError> {
17744    let page = connection
17745        .get("pageInfo")
17746        .filter(|value| value.is_object())
17747        .ok_or_else(|| SourceError::Malformed {
17748            message: "GitHub connection is missing pageInfo".into(),
17749        })?;
17750    if required_bool(page, "hasNextPage")? {
17751        let cursor = required_str(page, "endCursor")?;
17752        validate_cursor_progress(None, cursor)?;
17753        Ok(Some(Cursor(cursor.into())))
17754    } else {
17755        Ok(None)
17756    }
17757}
17758fn validate_cursor_progress(previous: Option<&str>, next: &str) -> Result<(), SourceError> {
17759    if next.is_empty() || previous == Some(next) {
17760        Err(SourceError::Malformed {
17761            message: "GitHub pagination cursor is empty or did not advance".into(),
17762        })
17763    } else {
17764        Ok(())
17765    }
17766}
17767/// The version of this plugin's opaque narrowing-search cursor.
17768pub const SEARCH_CURSOR_VERSION: u32 = 4;
17769
17770#[derive(Serialize, Deserialize)]
17771#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
17772enum SearchConnection {
17773    Initial {},
17774    Continuing { after: Cursor },
17775    Exhausted {},
17776}
17777impl SearchConnection {
17778    fn after(&self) -> Option<&str> {
17779        match self {
17780            Self::Continuing { after } => Some(&after.0),
17781            _ => None,
17782        }
17783    }
17784    fn exhausted(&self) -> bool {
17785        matches!(self, Self::Exhausted { .. })
17786    }
17787    /// Whether a cursor naming this position, `offset` rows into its page, is one this
17788    /// plugin could have handed out: a page is resumed only part of the way through it — an
17789    /// offset of a whole page or more would skip rows nobody was given — an initial page
17790    /// only once some of it was handed out, and an exhausted connection has no page to be
17791    /// part of the way through.
17792    fn valid_resume(&self, offset: usize) -> bool {
17793        let within = offset < SEARCH_PAGE_SIZE as usize;
17794        match self {
17795            Self::Initial { .. } => offset > 0 && within,
17796            Self::Continuing { after } => !after.0.is_empty() && within,
17797            Self::Exhausted { .. } => offset == 0,
17798        }
17799    }
17800}
17801
17802/// Versioned source cursor. A zero offset and empty own-write ids are omitted.
17803#[derive(Serialize, Deserialize)]
17804#[serde(deny_unknown_fields)]
17805struct SearchPosition {
17806    version: u32,
17807    connection: SearchConnection,
17808    /// How many rows of the page `connection` starts were already handed out.
17809    #[serde(default, skip_serializing_if = "is_zero")]
17810    offset: usize,
17811    #[serde(default, skip_serializing_if = "Vec::is_empty")]
17812    seen: Vec<NativeId>,
17813    #[serde(default, skip_serializing_if = "Vec::is_empty")]
17814    own: Vec<NativeId>,
17815}
17816impl Default for SearchPosition {
17817    fn default() -> Self {
17818        Self {
17819            version: SEARCH_CURSOR_VERSION,
17820            connection: SearchConnection::Initial {},
17821            offset: 0,
17822            seen: Vec::new(),
17823            own: Vec::new(),
17824        }
17825    }
17826}
17827
17828fn is_zero(offset: &usize) -> bool {
17829    *offset == 0
17830}
17831
17832fn numeric_cursor(cursor: Option<&Cursor>) -> Result<usize, SourceError> {
17833    cursor.map_or(Ok(0), |c| {
17834        c.0.parse().map_err(|_| SourceError::Config {
17835            message: "page cursor is invalid".into(),
17836        })
17837    })
17838}
17839fn offset_page<T>(mut items: Vec<T>, offset: usize, limit: usize) -> Page<T> {
17840    if offset > items.len() {
17841        return Page::last(vec![]);
17842    }
17843    let tail = items.split_off(offset);
17844    let mut selected = tail;
17845    let next = (selected.len() > limit).then(|| Cursor((offset + limit).to_string()));
17846    selected.truncate(limit);
17847    Page {
17848        items: selected,
17849        next,
17850    }
17851}
17852
17853impl GitHubProjectsSource {
17854    /// The body [`Self::write_item`] would compose for `incoming`, sized in the characters
17855    /// [`BODY_LIMIT`] counts, without a request: its slot as `slot_metadata` writes it, every
17856    /// asset reference rewritten to its recorded URL or — for one not uploaded yet — to an
17857    /// address as long as GitHub's, and the heading markup this board's bodies carry.
17858    ///
17859    /// What the write reads rather than knows is taken as it most often lands: the issue in
17860    /// the one repository the item names, else the configured one, and every edge on the
17861    /// board's own relationships rather than in the slot.
17862    fn body_size(&self, incoming: &Incoming<'_>) -> onetaskgraph_plugin_api::BodySize {
17863        let own = match incoming.repositories {
17864            [named] => Some(named.clone()),
17865            _ => self
17866                .repository
17867                .as_ref()
17868                .and_then(|target| Repository::try_from(target.origin()).ok()),
17869        };
17870        let mut slot = slot_metadata(incoming, own.as_ref(), &[]);
17871        let content = match incoming.assets {
17872            Some(assets) => {
17873                let mut uploads = onetaskgraph_plugin_api::AssetUploads::default();
17874                for asset in &assets.assets {
17875                    let url = assets
17876                        .recorded_assets
17877                        .as_ref()
17878                        .and_then(|recorded| recorded.reusable(&asset.name, &asset.sha256))
17879                        .unwrap_or(PREDICTED_ATTACHMENT_URL)
17880                        .to_owned();
17881                    uploads.0.insert(
17882                        asset.name.clone(),
17883                        onetaskgraph_plugin_api::AssetUpload {
17884                            sha256: asset.sha256.clone(),
17885                            url,
17886                        },
17887                    );
17888                }
17889                incoming.content.map(|content| {
17890                    onetaskgraph_plugin_api::serve_asset_references(content, &mut slot, &uploads)
17891                })
17892            }
17893            None => incoming.content.map(str::to_owned),
17894        };
17895        let marked = content.as_deref().map(|content| self.marked(content));
17896        let size = compose_body(marked.as_deref(), &slot)
17897            .ok()
17898            .flatten()
17899            .map_or(0, |body| body.chars().count());
17900        onetaskgraph_plugin_api::BodySize {
17901            size: u64::try_from(size).unwrap_or(u64::MAX),
17902            limit: Some(BODY_LIMIT),
17903        }
17904    }
17905
17906    async fn write_task_assets(
17907        &self,
17908        write: &ItemWrite<Task>,
17909        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
17910    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
17911        self.write_item(
17912            &self.task_incoming(write, assets)?,
17913            write.target.as_ref(),
17914            &write.depends_on,
17915        )
17916        .await
17917    }
17918
17919    /// One task write as [`Self::write_item`] takes it, once what it delivers and its priority
17920    /// are known to be ones this source can write.
17921    fn task_incoming<'a>(
17922        &self,
17923        write: &'a ItemWrite<Task>,
17924        assets: Option<&'a onetaskgraph_plugin_api::AssetWrite>,
17925    ) -> Result<Incoming<'a>, SourceError> {
17926        let near = write.target.as_ref().unwrap_or(&write.item.id);
17927        for (key, entries) in [
17928            (TaskRef::DELIVERS_KEY, &write.item.delivers),
17929            (TaskRef::DELIVERED_BY_KEY, &write.item.delivered_by),
17930        ] {
17931            TaskRef::listed(key, near, Some(&self.name), entries.clone())
17932                .map_err(|message| SourceError::Refused { message })?;
17933        }
17934        if self.priorities.is_none() && write.item.priority != Priority::None {
17935            return Err(self.holds_no_priority());
17936        }
17937        if write.item.assignees.is_some() && !self.assignees {
17938            return Err(onetaskgraph_plugin_api::unwritable_field(KIND, "assignees"));
17939        }
17940        Ok(Incoming {
17941            written: Written::Work(ItemKind::Task, &write.item.status),
17942            title: &write.item.title,
17943            content: write.item.content.as_deref(),
17944            assets,
17945            labels: &write.item.labels,
17946            metadata: &write.item.metadata,
17947            repositories: &write.item.repositories,
17948            classification: write.item.classification,
17949            parent: write.item.project.as_ref(),
17950            delivers: &write.item.delivers,
17951            delivered_by: &write.item.delivered_by,
17952            priority: self.priorities.as_ref().map(|_| write.item.priority),
17953            assignees: write.item.assignees.as_deref(),
17954        })
17955    }
17956    async fn write_document_assets(
17957        &self,
17958        write: &ItemWrite<Document>,
17959        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
17960    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
17961        // A document takes part in no dependency graph, so there is no far end to write
17962        // natively and none to record: a caller naming one is told so rather than having it
17963        // stored under the reserved key, where a later read would report an edge the
17964        // contract says cannot exist.
17965        if !write.depends_on.is_empty() {
17966            return Err(SourceError::Refused {
17967                message: format!(
17968                    "this write names {} dependencies for a document, and a document takes \
17969                     part in no dependency graph; next: put the dependency on the task or \
17970                     project the document is about",
17971                    write.depends_on.len()
17972                ),
17973            });
17974        }
17975        self.write_item(
17976            &Incoming {
17977                written: Written::Document,
17978                title: &write.item.title,
17979                content: write.item.content.as_deref(),
17980                assets,
17981                labels: &write.item.labels,
17982                metadata: &write.item.metadata,
17983                repositories: &write.item.repositories,
17984                classification: write.item.classification,
17985                parent: write.item.project.as_ref(),
17986                delivers: &[],
17987                delivered_by: &[],
17988                priority: None,
17989                assignees: None,
17990            },
17991            write.target.as_ref(),
17992            &[],
17993        )
17994        .await
17995    }
17996}
17997
17998/// What [`TaskSource::end_command`] leaves of this source's held state, asserted on the state
17999/// itself, for the two things no journey can observe.
18000///
18001/// The journeys in `crates/onetaskgraph-e2e/tests/e2e/end_command.rs` prove through the engine,
18002/// with and without the call, that a settlement, a board listing and a metadata search each
18003/// read afresh after it — the resolved records, the written-item overlay, the board and its
18004/// search, and the narrowed searches. What they cannot reach is the held field definitions,
18005/// because a status write naming an option a person deleted is refused the same whether or
18006/// not the list is held, and a poisoned lock, because nothing outside the source can panic
18007/// while one of its locks is held. So these assert those directly, and every other holder
18008/// beside them so a holder added later without a clear in the call fails here.
18009#[cfg(test)]
18010mod end_command_tests {
18011    use super::*;
18012
18013    struct Token;
18014
18015    impl SecretResolver for Token {
18016        fn get(&self, var: &str) -> Option<SecretString> {
18017            (var == "GH_PROJECTS_TOKEN").then(|| "test-token".into())
18018        }
18019    }
18020
18021    fn source() -> GitHubProjectsSource {
18022        let config = serde_json::from_value(json!({
18023            "owner": "octo-org", "project_number": 7, "repository": "acme/work",
18024            // Nothing here is sent: the source is only built and its state inspected.
18025            "endpoint": "http://127.0.0.1:9/graphql",
18026        }))
18027        .expect("a usable configuration");
18028        GitHubProjectsSource::new(&SourceName::new("work").unwrap(), config, &Token)
18029            .expect("the source builds")
18030    }
18031
18032    /// One issue as a board read answers it.
18033    fn resolved(source: &GitHubProjectsSource) -> Resolved {
18034        source
18035            .resolve(&json!({
18036                "id": "ITEM-1",
18037                "content": {"__typename": "Issue", "id": "I_1", "title": "Held",
18038                            "body": "what a person may since have edited", "state": "OPEN",
18039                            "stateReason": null, "url": null, "number": 1,
18040                            "subIssuesSummary": {"total": 0},
18041                            "labels": {"nodes": [], "pageInfo": {"hasNextPage": false}}},
18042                "fieldValues": {"nodes": [], "pageInfo": {"hasNextPage": false}},
18043            }))
18044            .expect("the item reads")
18045            .expect("an issue")
18046    }
18047
18048    /// Hold something in every holder the call clears, and the repository id it keeps.
18049    fn fill(source: &GitHubProjectsSource) {
18050        let item = resolved(source);
18051        source.created.lock().unwrap().push(item.clone());
18052        source.updated.lock().unwrap().push(item.clone());
18053        *source.board_cache.lock().unwrap() = Some(Board {
18054            id: "PVT-board".into(),
18055            fields: json!({"nodes": []}),
18056            items: vec![item.clone()],
18057        });
18058        *source.search_cache.lock().unwrap() = Some(vec![item.clone()]);
18059        source
18060            .narrowed_cache
18061            .lock()
18062            .unwrap()
18063            .insert("status:todo".into(), vec![item.clone()]);
18064        source.children_cache.lock().unwrap().insert(
18065            NativeId("P-1".into()),
18066            (NativeId("P-1".into()), vec![item.clone()]),
18067        );
18068        source
18069            .search_next
18070            .lock()
18071            .unwrap()
18072            .insert("status:todo".into(), Some("cursor".into()));
18073        source
18074            .resolved_cache
18075            .lock()
18076            .unwrap()
18077            .insert(item.id.clone(), item);
18078        *source.fields_cache.lock().unwrap() = Some(BoardFields {
18079            id: BoardId::parse("PVT-board").unwrap(),
18080            fields: json!({"nodes": []}),
18081        });
18082        source
18083            .repository_cache
18084            .lock()
18085            .unwrap()
18086            .insert(RepositoryTarget::parse("acme/work").unwrap(), "R_1".into());
18087    }
18088
18089    fn assert_dropped(source: &GitHubProjectsSource) {
18090        assert!(source.created().unwrap().is_empty(), "created");
18091        assert!(source.updated().unwrap().is_empty(), "updated");
18092        assert!(source.board_cache().unwrap().is_none(), "board");
18093        assert!(source.search_cache.lock().unwrap().is_none(), "search");
18094        assert!(source.narrowed_cache.lock().unwrap().is_empty(), "narrowed");
18095        assert!(
18096            source.children_cache.lock().unwrap().is_empty(),
18097            "project children"
18098        );
18099        assert!(
18100            source.search_next.lock().unwrap().is_empty(),
18101            "search paging"
18102        );
18103        assert!(
18104            source.resolved_cache().unwrap().is_empty(),
18105            "resolved records"
18106        );
18107        assert!(source.fields_cache().unwrap().is_none(), "board fields");
18108        assert_eq!(
18109            source.repository_cache().unwrap().len(),
18110            1,
18111            "a repository's node id stays valid and is kept"
18112        );
18113    }
18114
18115    fn end(source: &GitHubProjectsSource) {
18116        tokio::runtime::Builder::new_current_thread()
18117            .build()
18118            .unwrap()
18119            .block_on(source.end_command())
18120            .expect("the command ends");
18121    }
18122
18123    #[test]
18124    fn the_call_drops_every_item_search_and_board_read_and_keeps_repository_ids() {
18125        let source = source();
18126        fill(&source);
18127        end(&source);
18128        assert_dropped(&source);
18129    }
18130
18131    #[test]
18132    fn the_call_clears_a_lock_an_earlier_failure_poisoned() {
18133        fn poison<T: Send>(held: &Mutex<T>) {
18134            std::thread::scope(|scope| {
18135                let _ = scope
18136                    .spawn(|| {
18137                        let _guard = held.lock().unwrap();
18138                        panic!("a failure while the lock is held");
18139                    })
18140                    .join();
18141            });
18142            assert!(held.is_poisoned());
18143        }
18144        let source = source();
18145        fill(&source);
18146        poison(&source.created);
18147        poison(&source.updated);
18148        poison(&source.board_cache);
18149        poison(&source.search_cache);
18150        poison(&source.narrowed_cache);
18151        poison(&source.search_next);
18152        poison(&source.resolved_cache);
18153        poison(&source.fields_cache);
18154        assert!(
18155            source.resolved_cache().is_err(),
18156            "a poisoned lock is refused before the call"
18157        );
18158        end(&source);
18159        assert_dropped(&source);
18160    }
18161}
18162
18163#[cfg(test)]
18164mod unprojectable_fields_tests {
18165    use super::*;
18166
18167    /// The field names `docs/metadata.md` says a `metadata_fields` entry may not name.
18168    fn documented() -> std::collections::BTreeSet<String> {
18169        let document = std::fs::read_to_string(
18170            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/metadata.md"),
18171        )
18172        .expect("docs/metadata.md is readable");
18173        let document = document.split_whitespace().collect::<Vec<_>>().join(" ");
18174        let lead = "a `field` equal, ignoring case, to ";
18175        let start = document.find(lead).expect("the refused-field sentence") + lead.len();
18176        let sentence = &document[start..];
18177        let sentence = &sentence[..sentence
18178            .find("; and two entries naming one field")
18179            .expect("the refused-field sentence ends at the duplicate rule")];
18180        let (own, github) = sentence
18181            .split_once(" or a field GitHub owns on every board (")
18182            .expect("the sentence names GitHub's own fields");
18183        own.split('`')
18184            .skip(1)
18185            .step_by(2)
18186            .chain(
18187                github
18188                    .strip_suffix(')')
18189                    .expect("GitHub's own fields close the sentence")
18190                    .split(", "),
18191            )
18192            .map(str::to_owned)
18193            .collect()
18194    }
18195
18196    /// `docs/metadata.md` states the text field's limit a caller is held to; it is this source's
18197    /// own constant, so the two cannot part.
18198    #[test]
18199    fn the_documented_text_field_limit_is_the_one_the_source_shortens_at() {
18200        let document = std::fs::read_to_string(
18201            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/metadata.md"),
18202        )
18203        .expect("docs/metadata.md is readable");
18204        let lead = "**A text field holds at most ";
18205        let start = document.find(lead).expect("the limit sentence") + lead.len();
18206        let stated = &document[start..start + document[start..].find(',').unwrap() + 4];
18207        assert_eq!(
18208            stated.replace(',', "").parse::<usize>().ok(),
18209            Some(TEXT_FIELD_LIMIT),
18210            "docs/metadata.md states {stated:?}"
18211        );
18212        assert!(document[start..].starts_with(&format!("{stated}, counted here in UTF-8 bytes.")));
18213    }
18214
18215    #[test]
18216    fn the_documented_refused_fields_are_exactly_the_ones_the_configuration_refuses() {
18217        let refused: std::collections::BTreeSet<String> = UNPROJECTABLE_FIELDS
18218            .iter()
18219            .map(|&name| name.to_owned())
18220            .collect();
18221        assert_eq!(documented(), refused, "the fields docs/metadata.md lists");
18222        let instance = SourceName::new("work").unwrap();
18223        for name in UNPROJECTABLE_FIELDS {
18224            for spelled in [name.to_owned(), name.to_uppercase()] {
18225                let entry = MetadataFieldConfig {
18226                    field: spelled.clone(),
18227                    key: "team.machine".to_owned(),
18228                    path: Vec::new(),
18229                };
18230                let refused = MetadataField::resolve(vec![entry], &instance)
18231                    .expect_err("an unprojectable field is refused");
18232                assert!(
18233                    refused.to_string().contains(&format!("{name:?}")),
18234                    "{spelled}: {refused}"
18235                );
18236            }
18237        }
18238    }
18239}