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            if let Err(refused) = <dyn onetaskgraph_plugin_api::RequestGate>::before(
6420                &gated_graphql(query, &variables),
6421            )
6422            .await
6423            {
6424                self.paced(ticket, mutation);
6425                return Err(refused);
6426            }
6427            let attempt = self.send_once(query, &variables, waits + 1).await;
6428            self.paced(ticket, mutation);
6429            let remaining = self.pacing.retry_budget.saturating_sub(waited);
6430            let (wait, cause) = match attempt {
6431                Ok(data) => return Ok(data),
6432                Err(Attempt::Failed(error)) => return Err(error),
6433                Err(Attempt::Conflicted(said)) => {
6434                    // A create is never replayed: see `CONFLICT_WORDINGS`.
6435                    if query.contains("createIssue(") || backoff.is_zero() || backoff > remaining {
6436                        return Err(SourceError::Unavailable {
6437                            message: format!(
6438                                "GitHub refused this source while {doing} as a temporary \
6439                                 conflict ({said}); it retried {} over {} and the conflict \
6440                                 did not clear within the {} one call may spend waiting. \
6441                                 next: run the command again once nothing else is writing to \
6442                                 the same items",
6443                                plural(waits, "time"),
6444                                seconds(waited),
6445                                seconds(self.pacing.retry_budget),
6446                            ),
6447                        });
6448                    }
6449                    (backoff, pacing::cause::BACKOFF)
6450                }
6451                Err(Attempt::Limited(limited)) => {
6452                    let (wait, cause) = limited.wait(backoff);
6453                    // A wait of nothing spends none of the budget, so it is exhaustion rather
6454                    // than a retry. `Pacing::resolve` rules out every way of configuring one
6455                    // except a budget of zero, where reporting the first refusal is the ask.
6456                    if wait.is_zero() || wait > remaining {
6457                        return Err(limited.exhausted(
6458                            doing,
6459                            waits,
6460                            waited,
6461                            wait,
6462                            self.pacing.retry_budget,
6463                        ));
6464                    }
6465                    (wait, cause)
6466                }
6467            };
6468            self.clock.sleep_because(wait, cause).await;
6469            waited += wait;
6470            waits += 1;
6471            backoff = backoff.saturating_mul(2);
6472        }
6473    }
6474
6475    /// Hold one request charging `charge` until every secondary window it charges has room for
6476    /// the whole of it — and, for a mutation of an instance configured with
6477    /// `pacing.min_mutation_interval_ms`, until that interval has passed since the last one
6478    /// finished — then count it, answering the ticket [`Self::paced`] finishes it with.
6479    ///
6480    /// The moment is decided and counted under the lock and waited out outside it, so two
6481    /// callers take two places rather than the same one, and no lock is held across an await.
6482    /// A request with room goes out at once: nothing here waits that a window does not ask for.
6483    async fn pace(&self, charge: pacing::Charge, mutation: bool) -> pacing::Ticket {
6484        let (wait, cause, ticket) = {
6485            // A poisoned lock here costs pacing, not correctness, and refusing the write over
6486            // it would turn an earlier failure into a second one for no gain.
6487            let mut windows = self
6488                .windows
6489                .lock()
6490                .unwrap_or_else(std::sync::PoisonError::into_inner);
6491            let now = self.clock.now();
6492            let (mut at, mut cause) = if self.pacing.windows {
6493                windows.room(now, charge)
6494            } else {
6495                (now, None)
6496            };
6497            if mutation && !self.pacing.min_mutation_interval.is_zero() {
6498                let mut last = self
6499                    .last_mutation
6500                    .lock()
6501                    .unwrap_or_else(std::sync::PoisonError::into_inner);
6502                // `checked_add` rather than `+`: adding durations can panic on overflow, and
6503                // pacing is not worth a panic even at a bound `MAX_PACING_MS` already rules out.
6504                if let Some(earliest) = last
6505                    .and_then(|previous| previous.checked_add(self.pacing.min_mutation_interval))
6506                    && earliest > at
6507                {
6508                    at = earliest;
6509                    cause = Some(pacing::cause::MIN_INTERVAL);
6510                }
6511                *last = Some(at);
6512            }
6513            let ticket = windows.charge(at, charge);
6514            (at.saturating_sub(now), cause, ticket)
6515        };
6516        if let (false, Some(cause)) = (wait.is_zero(), cause) {
6517            self.clock.sleep_because(wait, cause).await;
6518        }
6519        ticket
6520    }
6521
6522    /// Record that the request `ticket` was charged for has finished, so each window — and
6523    /// the configured spacing — counts it from here rather than from the moment it left.
6524    ///
6525    /// This source can only choose when a request *departs*; GitHub's limiter counts when it
6526    /// *arrives*, and the two differ by whatever the request spent in transit. Counting from
6527    /// departure would hand the limiter a window that looked roomier than it is, so a source
6528    /// pacing exactly at a limit could still be seen arriving over it — which is how a copy
6529    /// paced well inside a board's threshold was once refused by it on a slower machine while
6530    /// passing on a quick one. The previous request had arrived before its response came back,
6531    /// so counting from here is never earlier than the limiter does, whatever transit costs
6532    /// and on whatever platform: the safe side of a limit that punishes being wrong by refusing
6533    /// reads for the next fifty minutes.
6534    ///
6535    /// A failed attempt is finished too: a request refused by the limiter still arrived, and
6536    /// one that never left costs only room nobody needed.
6537    fn paced(&self, ticket: pacing::Ticket, mutation: bool) {
6538        let now = self.clock.now();
6539        self.windows
6540            .lock()
6541            .unwrap_or_else(std::sync::PoisonError::into_inner)
6542            .finish(ticket, now);
6543        if mutation && !self.pacing.min_mutation_interval.is_zero() {
6544            let mut last = self
6545                .last_mutation
6546                .lock()
6547                .unwrap_or_else(std::sync::PoisonError::into_inner);
6548            // `max` rather than an assignment: a concurrent caller may already have reserved a
6549            // slot further out, and completing this request must never pull that slot back in.
6550            *last = Some(last.map_or(now, |reserved| reserved.max(now)));
6551        }
6552    }
6553
6554    /// One HTTP attempt, classified into an answer, a rate limit to wait out, or a
6555    /// failure that waiting cannot help — and recorded, whichever of the three it was.
6556    ///
6557    /// This is the one place a request leaves this crate, which is why the accounting is
6558    /// here rather than at each of the callers: a read path added later is counted without
6559    /// anybody remembering to count it, and
6560    /// `the_session_report_counts_every_request_the_board_served_and_what_each_cost` fails
6561    /// when one is not.
6562    async fn send_once(
6563        &self,
6564        query: &str,
6565        variables: &Value,
6566        number: u32,
6567    ) -> Result<Value, Attempt> {
6568        // A lookup goes out sized to the people it names, and the record names and counts it as
6569        // what it is; everything that decides how it is retried or read compares `query`, the
6570        // constant it was written as.
6571        let sized = graphql::sized(query, variables);
6572        let executed = self.ledger.priced_document(sized.as_ref());
6573        let Attempted {
6574            result,
6575            limits,
6576            reported_cost,
6577            response_outcome,
6578        } = self.attempt(executed.as_ref(), variables).await;
6579        // No `otherwise` name: every document this source sends is one of its own, and the
6580        // inventory gate on `graphql::DOCUMENTS` is what keeps that true.
6581        let sending = accounting::Request::graphql(sized.as_ref(), variables, None, reported_cost);
6582        let outcome = match &result {
6583            Ok(_) => accounting::Outcome::Answered,
6584            Err(Attempt::Limited(_)) => accounting::Outcome::RateLimited,
6585            Err(Attempt::Failed(_) | Attempt::Conflicted(_)) => accounting::Outcome::Refused,
6586        };
6587        self.ledger
6588            .record(sending.finished(outcome, limits).with_execution(
6589                Some(executed.into_owned()),
6590                response_outcome,
6591                number,
6592            ));
6593        result
6594    }
6595
6596    /// The attempt itself, with what its response said about the rate limit alongside.
6597    ///
6598    /// The two are returned together rather than recorded here because every one of the
6599    /// early exits below is a different outcome, and a record written at each of them is a
6600    /// record one of them can be added without.
6601    async fn attempt(&self, query: &str, variables: &Value) -> Attempted {
6602        let mut limits = accounting::RateLimit::default();
6603        let mut reported_cost = None;
6604        let mut response_outcome = accounting::ResponseOutcome::TransportError;
6605        // Spelled here, at the one place a document leaves for GitHub, and nowhere earlier:
6606        // everything that decides how a document is retried or how its answer is read compares
6607        // it with the constant it was written as.
6608        let spelled = self
6609            .assignees
6610            .then(|| graphql::with_assignees(query))
6611            .flatten();
6612        let result = self
6613            .attempted(
6614                query,
6615                spelled.as_deref().unwrap_or(query),
6616                variables,
6617                &mut limits,
6618                &mut reported_cost,
6619                &mut response_outcome,
6620            )
6621            .await;
6622        Attempted {
6623            result,
6624            limits,
6625            reported_cost,
6626            response_outcome,
6627        }
6628    }
6629
6630    /// One HTTP attempt, filling in what its response said about the rate limit as it goes.
6631    async fn attempted(
6632        &self,
6633        query: &str,
6634        sent: &str,
6635        variables: &Value,
6636        limits: &mut accounting::RateLimit,
6637        reported_cost: &mut Option<u64>,
6638        response_outcome: &mut accounting::ResponseOutcome,
6639    ) -> Result<Value, Attempt> {
6640        let response = self
6641            .client()
6642            .map_err(Attempt::Failed)?
6643            .post(self.endpoint.clone())
6644            .bearer_auth(self.token.expose_secret())
6645            .json(&json!({"query": sent, "variables": variables}))
6646            .send()
6647            .await
6648            .map_err(|e| {
6649                Attempt::Failed(SourceError::Unavailable {
6650                    message: format!("GitHub GraphQL request failed: {}", transport_error(&e)),
6651                })
6652            })?;
6653        let status = response.status();
6654        if !status.is_success() {
6655            *response_outcome = accounting::ResponseOutcome::HttpError;
6656        }
6657        let header = |name: &str| whole_seconds(response.headers().get(name));
6658        let served = response
6659            .headers()
6660            .get(reqwest::header::DATE)
6661            .and_then(|value| value.to_str().ok())
6662            .and_then(|value| DateTime::parse_from_rfc2822(value).ok())
6663            .map(|at| at.with_timezone(&Utc));
6664        *limits = accounting::RateLimit::read(|name| {
6665            response
6666                .headers()
6667                .get(name)
6668                .and_then(|value| value.to_str().ok())
6669                .map(str::to_owned)
6670        });
6671        // Each response's own reading, as it gave it: never merged with another window's.
6672        <dyn onetaskgraph_plugin_api::RequestGate>::after(&quota::header_readings(limits));
6673        // Exactly `0` is exhaustion and everything else — a count, an empty value, bytes
6674        // that are not text at all — is "not known to be exhausted". This never makes a
6675        // response a refusal on its own: it says which limiter a refusal is attributed to
6676        // and where its hint comes from, so a value this cannot read costs a hint rather
6677        // than an answer.
6678        let exhausted = response
6679            .headers()
6680            .get("x-ratelimit-remaining")
6681            .and_then(|value| value.to_str().ok())
6682            == Some("0");
6683        // `retry-after` is what GitHub asks for when it asks; when it does not and the
6684        // primary budget is spent, `x-ratelimit-reset` says when that budget comes back,
6685        // which is the same question answered as an absolute time. Nothing else here is a
6686        // hint, and a schedule is what answers a refusal that carries none.
6687        let retry_after = header("retry-after");
6688        let hinted_by = if retry_after.is_some() || !exhausted {
6689            Hint::RetryAfter
6690        } else {
6691            Hint::PrimaryReset
6692        };
6693        let hint = retry_after.or_else(|| {
6694            exhausted
6695                .then(|| header("x-ratelimit-reset"))
6696                .flatten()
6697                .map(|reset| reset.saturating_sub(Utc::now().timestamp().max(0).unsigned_abs()))
6698        });
6699        // Read before it is parsed, because the evidence which tells a secondary rate
6700        // limit from a rejected credential is in the body of a response whose status says
6701        // only "forbidden" — and a non-success response was never parsed at all.
6702        let body = response.text().await.map_err(|e| {
6703            Attempt::Failed(SourceError::Unavailable {
6704                message: format!(
6705                    "GitHub GraphQL response could not be read: {}",
6706                    transport_error(&e)
6707                ),
6708            })
6709        })?;
6710        *reported_cost = serde_json::from_str::<Value>(&body)
6711            .ok()
6712            .as_ref()
6713            .and_then(|body| body.pointer("/data/rateLimit/cost"))
6714            .and_then(Value::as_u64);
6715        let parsed = serde_json::from_str::<Value>(&body).ok();
6716        *response_outcome = accounting::ResponseOutcome::of_graphql_reply(status, parsed.as_ref());
6717        if let Some(limiter) = Limiter::classify(status, exhausted, &body) {
6718            return Err(Attempt::Limited(Limited {
6719                limiter,
6720                hint,
6721                hinted_by,
6722            }));
6723        }
6724        if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
6725            return Err(Attempt::Failed(SourceError::Auth {
6726                message: format!(
6727                    "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"
6728                ),
6729            }));
6730        }
6731        if !status.is_success() {
6732            return Err(Attempt::Failed(SourceError::Unavailable {
6733                message: format!("GitHub GraphQL returned HTTP {status}"),
6734            }));
6735        }
6736        let said = refusal_wording(status, &body);
6737        let normalized = said.to_ascii_lowercase();
6738        if CONFLICT_WORDINGS
6739            .iter()
6740            .any(|wording| normalized.contains(wording))
6741        {
6742            return Err(Attempt::Conflicted(said));
6743        }
6744        // A lookup is read as the inventoried document it was sized from.
6745        let query = graphql::inventoried(query);
6746        let answered = if query == graphql::ISSUES_BY_REFERENCE {
6747            self.answer_unresolved(&body)
6748        } else if [
6749            graphql::CREATE_ISSUES,
6750            graphql::SEARCH_BATCH,
6751            graphql::USER_IDS,
6752            graphql::ADD_COMMENTS,
6753            graphql::WRITE_TASKS,
6754            graphql::SET_PARENTS,
6755            graphql::ADD_RELATES_TO,
6756            graphql::REMOVE_RELATES_TO,
6757        ]
6758        .contains(&query)
6759        {
6760            answer_with_errors(&body).map_or_else(|| self.answer(&body), Ok)
6761        } else {
6762            self.answer(&body)
6763        };
6764        let mut data = answered.map_err(Attempt::Failed)?;
6765        if let Some(served) = served {
6766            *self
6767                .last_served
6768                .lock()
6769                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(served);
6770            stamp_served(&mut data, &served.to_rfc3339());
6771        }
6772        Ok(data)
6773    }
6774
6775    /// What one successful HTTP response says, once its GraphQL errors are read.
6776    /// [`Self::answer`], for a read of issues by reference: a reference GitHub cannot resolve
6777    /// for this credential — a repository it cannot see, an issue number it does not hold —
6778    /// is answered `null` beside a `NOT_FOUND` error naming it, and that is an answer about
6779    /// that reference rather than a failure of the others. Any other error refuses the read,
6780    /// as there.
6781    fn answer_unresolved(&self, body: &str) -> Result<Value, SourceError> {
6782        let parsed: Option<Value> = serde_json::from_str(body).ok();
6783        // Each error is a `NOT_FOUND` whose path names one slot of the batch, `r<n>` or its
6784        // `issue`, and the answer holds `null` at exactly that path: anything else — another
6785        // kind of error, one naming no slot, or one beside a value it says is not there — is a
6786        // refusal of the whole read.
6787        let unresolved = |data: &Value, error: &Value| {
6788            error.get("type").and_then(Value::as_str) == Some("NOT_FOUND")
6789                && error
6790                    .get("path")
6791                    .and_then(Value::as_array)
6792                    .is_some_and(|path| {
6793                        let alias = path.first().and_then(Value::as_str).and_then(|alias| {
6794                            alias
6795                                .strip_prefix('r')
6796                                .and_then(|slot| slot.parse::<usize>().ok())
6797                                .filter(|slot| *slot < REFERENCE_BATCH)
6798                                .map(|_| alias)
6799                        });
6800                        match (alias, path.get(1).and_then(Value::as_str), path.len()) {
6801                            (Some(alias), None, 1) => data.get(alias).is_some_and(Value::is_null),
6802                            (Some(alias), Some("issue"), 2) => data
6803                                .get(alias)
6804                                .and_then(|repository| repository.get("issue"))
6805                                .is_some_and(Value::is_null),
6806                            _ => false,
6807                        }
6808                    })
6809        };
6810        let unresolved_only = parsed.as_ref().is_some_and(|parsed| {
6811            parsed.get("data").is_some_and(|data| {
6812                data.is_object()
6813                    && parsed
6814                        .get("errors")
6815                        .and_then(Value::as_array)
6816                        .is_some_and(|errors| errors.iter().all(|error| unresolved(data, error)))
6817            })
6818        });
6819        match parsed {
6820            Some(parsed) if unresolved_only => Ok(parsed["data"].clone()),
6821            _ => self.answer(body),
6822        }
6823    }
6824
6825    fn answer(&self, body: &str) -> Result<Value, SourceError> {
6826        let body: Value = serde_json::from_str(body).map_err(|e| SourceError::Malformed {
6827            message: format!("GitHub returned invalid JSON: {e}"),
6828        })?;
6829        let errors = body
6830            .get("errors")
6831            .map(|value| {
6832                value.as_array().ok_or_else(|| SourceError::Malformed {
6833                    message: "GitHub response errors is not an array".into(),
6834                })
6835            })
6836            .transpose()?;
6837        if let Some(errors) = errors.filter(|errors| !errors.is_empty()) {
6838            let messages = errors
6839                .iter()
6840                .filter_map(|e| e.get("message").and_then(Value::as_str))
6841                .collect::<Vec<_>>()
6842                .join("; ");
6843            let message = if messages.is_empty() {
6844                "GitHub returned GraphQL errors".into()
6845            } else {
6846                messages
6847            };
6848            let normalized = message.to_ascii_lowercase();
6849            if normalized.contains("resource not accessible") || normalized.contains("scope") {
6850                return Err(SourceError::Auth {
6851                    message: format!(
6852                        "{message}; grant {} Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board",
6853                        self.credential_name
6854                    ),
6855                });
6856            }
6857            return Err(SourceError::Refused { message });
6858        }
6859        body.get("data")
6860            .filter(|data| data.is_object())
6861            .cloned()
6862            .ok_or_else(|| SourceError::Malformed {
6863                message: "GitHub response has no data object".into(),
6864            })
6865    }
6866
6867    // llmlint: ignore[boundary_inputs_validated] GitHub caps nested connections at 100 and
6868    // GraphQL cannot independently page them inside the outer item page. This source page is
6869    // deliberately bounded at that published maximum; the live drift journey exercises it.
6870    async fn board_page(
6871        &self,
6872        items_after: Option<&str>,
6873        items_first: u32,
6874    ) -> Result<Value, SourceError> {
6875        let data = self
6876            .graphql(
6877                graphql::BOARD,
6878                json!({"owner":self.owner,"number":self.project_number,
6879                       "first":items_first.min(MAX_PAGE_SIZE),"after":items_after,
6880                       "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
6881            )
6882            .await?;
6883        data.pointer("/owner/projectV2")
6884            .filter(|v| !v.is_null())
6885            .cloned()
6886            .ok_or_else(|| SourceError::Refused {
6887                message: format!(
6888                    "GitHub project {}/{} was not found or is not visible to the token",
6889                    self.owner, self.project_number
6890                ),
6891            })
6892    }
6893
6894    /// The search that finds the issues of this board, narrowed by `also` when it is
6895    /// given.
6896    ///
6897    /// `project:owner/number` is what scopes a search to one board, and `is:issue` is what
6898    /// keeps pull requests out of it: GitHub's `ISSUE` search type covers both, and a pull
6899    /// request is somebody's change rather than a unit of plan. `-has:parent` is *not*
6900    /// here on purpose — GitHub accepts it and silently ignores it, so a project is told
6901    /// from a task by the `parent` field each issue carries rather than by the search.
6902    fn board_search(&self, also: Option<&str>) -> String {
6903        let scope = format!("project:{}/{} is:issue", self.owner, self.project_number);
6904        match also {
6905            Some(also) => format!("{scope} {also}"),
6906            None => scope,
6907        }
6908    }
6909
6910    /// One issue this source reached directly, as the board item a read of the board would
6911    /// have produced — or `None` when this board does not hold it.
6912    ///
6913    /// The board half of an issue rides along on `Issue.projectItems`, so the value handed
6914    /// to [`Self::resolve`] is the very shape a `ProjectV2.items` read gives it: the board
6915    /// item's own id, that item's field values, and the issue as its content. One resolver
6916    /// for both routes is what makes an issue read through a search, through its own node
6917    /// id, or through its project's sub-issues report the same title, the same status, the
6918    /// same labels and the same qualified id.
6919    ///
6920    /// An issue with no entry for *this* board is not this source's to report, which is
6921    /// what keeps an id naming some other repository's issue from being answered as an item
6922    /// of this board. That answer is given about an **exhausted** connection and never
6923    /// about an unread page: the entry is looked for on the page in hand, and only if that
6924    /// page reports more of the connection, in [`Self::board_membership`]'s walk of the
6925    /// rest of it.
6926    async fn resolve_issue(&self, issue: &Value) -> Result<Option<Resolved>, SourceError> {
6927        self.resolve_issue_as(issue, true).await
6928    }
6929
6930    /// [`Self::resolve_issue`], remembering what it resolves for this command's later reads
6931    /// and writes only when `remember` says to.
6932    async fn resolve_issue_as(
6933        &self,
6934        issue: &Value,
6935        remember: bool,
6936    ) -> Result<Option<Resolved>, SourceError> {
6937        if optional_str(issue, "__typename")? != Some("Issue") {
6938            return Ok(None);
6939        }
6940        let memberships = issue
6941            .get("projectItems")
6942            .ok_or_else(|| SourceError::Malformed {
6943                message: "GitHub issue is missing projectItems".into(),
6944            })?;
6945        let nodes = memberships
6946            .get("nodes")
6947            .and_then(Value::as_array)
6948            .ok_or_else(|| SourceError::Malformed {
6949                message: "GitHub issue projectItems.nodes is not an array".into(),
6950            })?;
6951        let held = match self.board_entry(nodes) {
6952            Some(held) => held.clone(),
6953            None => {
6954                let info = memberships
6955                    .get("pageInfo")
6956                    .ok_or_else(|| SourceError::Malformed {
6957                        message: "GitHub issue projectItems has no pageInfo".into(),
6958                    })?;
6959                // The page held no entry for this board. Whether that means the issue is
6960                // not on it is a question about the rest of the connection, and only a
6961                // connection with no rest answers it here.
6962                if !required_bool(info, "hasNextPage")? {
6963                    return Ok(None);
6964                }
6965                let cursor = required_str(info, "endCursor")?;
6966                validate_cursor_progress(None, cursor)?;
6967                let issue_id = required_str(issue, "id")?;
6968                match self.board_membership(issue_id, cursor).await? {
6969                    Some(held) => held,
6970                    None => return Ok(None),
6971                }
6972            }
6973        };
6974        // The membership's own `updatedAt` rides along: it is the board half of the item's change
6975        // token, which a field change moves where the issue's own time does not.
6976        let item = json!({
6977            "id": required_str(&held, "id")?,
6978            "updatedAt": held.get("updatedAt"),
6979            "project": held.get("project"),
6980            "fieldValues": held.get("fieldValues"),
6981            "content": issue,
6982        });
6983        if remember {
6984            self.resolve(&item)
6985        } else {
6986            self.resolve_unremembered(&item)
6987        }
6988    }
6989
6990    /// This board's own entry among one page of an issue's `Issue.projectItems`.
6991    ///
6992    /// One spelling of *which membership is this board's*, so the page a read carries and
6993    /// the pages [`Self::board_membership`] walks are searched by the same rule.
6994    fn board_entry<'a>(&self, nodes: &'a [Value]) -> Option<&'a Value> {
6995        nodes.iter().find(|node| {
6996            node.pointer("/project/number").and_then(Value::as_u64)
6997                == Some(u64::from(self.project_number))
6998        })
6999    }
7000
7001    /// The rest of one issue's board memberships, from `after`, for this board's entry.
7002    ///
7003    /// The recovery read: a page of memberships that holds no entry for this board says
7004    /// nothing about the memberships past it, so the connection is walked to exhaustion
7005    /// before an issue is reported as one this board does not hold. `Ok(None)` is that
7006    /// positive answer — the whole connection was read and no entry named this board —
7007    /// rather than a failure, and the walk is held to
7008    /// [`validate_cursor_progress`] like every other page walk here, so a source answering
7009    /// with a cursor that does not advance is refused instead of spun on.
7010    async fn board_membership(
7011        &self,
7012        issue: &str,
7013        after: &str,
7014    ) -> Result<Option<Value>, SourceError> {
7015        let mut after = after.to_owned();
7016        loop {
7017            let data = self
7018                .graphql(
7019                    graphql::ISSUE_BOARD_ITEMS,
7020                    json!({"id":issue,"first":MAX_PAGE_SIZE,"after":after,
7021                           "nestedFirst":NESTED_PAGE_SIZE}),
7022                )
7023                .await?;
7024            let Some(connection) = data
7025                .pointer("/node/projectItems")
7026                .filter(|value| !value.is_null())
7027            else {
7028                // The id resolved to nothing, or to something with no memberships to walk —
7029                // which is the same answer as a connection holding no entry for this board.
7030                return Ok(None);
7031            };
7032            let nodes = connection
7033                .get("nodes")
7034                .and_then(Value::as_array)
7035                .ok_or_else(|| SourceError::Malformed {
7036                    message: "GitHub issue projectItems.nodes is not an array".into(),
7037                })?;
7038            if let Some(held) = self.board_entry(nodes) {
7039                return Ok(Some(held.clone()));
7040            }
7041            let info = connection
7042                .get("pageInfo")
7043                .ok_or_else(|| SourceError::Malformed {
7044                    message: "GitHub issue projectItems has no pageInfo".into(),
7045                })?;
7046            let next = required_bool(info, "hasNextPage")?
7047                .then(|| required_str(info, "endCursor"))
7048                .transpose()?;
7049            match next {
7050                Some(next) => {
7051                    validate_cursor_progress(Some(&after), next)?;
7052                    after = next.to_owned();
7053                }
7054                None => return Ok(None),
7055            }
7056        }
7057    }
7058
7059    /// One page of a board-scoped issue search, and where the next page resumes.
7060    async fn search_page(
7061        &self,
7062        search: &str,
7063        first: u32,
7064        after: Option<&str>,
7065    ) -> Result<(Vec<Resolved>, Option<String>), SourceError> {
7066        let data = self
7067            .graphql(
7068                graphql::SEARCH_ISSUES,
7069                json!({"search":search,"type":"ISSUE","first":first.min(MAX_PAGE_SIZE),
7070                       "after":after,"nestedFirst":NESTED_PAGE_SIZE,
7071                       "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
7072            )
7073            .await?;
7074        let connection = data.get("search").ok_or_else(|| SourceError::Malformed {
7075            message: "GitHub search response has no search connection".into(),
7076        })?;
7077        let mut found = Vec::new();
7078        for node in connection
7079            .get("nodes")
7080            .and_then(Value::as_array)
7081            .ok_or_else(|| SourceError::Malformed {
7082                message: "GitHub search nodes is not an array".into(),
7083            })?
7084        {
7085            if let Some(resolved) = self.resolve_issue(node).await? {
7086                found.push(resolved);
7087            }
7088        }
7089        let info = connection
7090            .get("pageInfo")
7091            .ok_or_else(|| SourceError::Malformed {
7092                message: "GitHub search connection has no pageInfo".into(),
7093            })?;
7094        let next = required_bool(info, "hasNextPage")?
7095            .then(|| required_str(info, "endCursor"))
7096            .transpose()?
7097            .map(str::to_owned);
7098        if let Some(next) = &next {
7099            validate_cursor_progress(after, next)?;
7100        }
7101        Ok((found, next))
7102    }
7103
7104    /// Every issue this board holds, completed with what this run wrote.
7105    ///
7106    /// The completion is not an optimisation and it is not a cache: GitHub's issue search
7107    /// is an index and is eventually consistent, so an issue this run created seconds ago
7108    /// can be absent from it, and a project listed straight after being written would
7109    /// otherwise be missing from its own board. What is added back is only what this
7110    /// process itself wrote, out of [`Self::created`], which lives and dies with the
7111    /// process.
7112    async fn board_issues(&self) -> Result<Vec<Resolved>, SourceError> {
7113        let found = self.searched_issues().await?;
7114        self.completed_with_written(found, |_| true)
7115    }
7116
7117    /// Every issue this board's own search reports, walked to exhaustion, read once per
7118    /// source.
7119    ///
7120    /// The uncompleted half of [`Self::board_issues`], separated because [`Self::board`]
7121    /// needs it too and the two would otherwise walk the same search twice in one command.
7122    /// See [`Self::search_cache`] for why holding it is the same bargain holding the board
7123    /// is.
7124    async fn searched_issues(&self) -> Result<Vec<Resolved>, SourceError> {
7125        let cached = self.search_cache()?.clone();
7126        if let Some(held) = cached {
7127            return Ok(held);
7128        }
7129        let mut after: Option<String> = None;
7130        let mut found = Vec::new();
7131        let search = self.board_search(None);
7132        loop {
7133            let (page, next) = self
7134                .search_page(&search, MAX_PAGE_SIZE, after.as_deref())
7135                .await?;
7136            found.extend(page);
7137            match next {
7138                Some(next) => after = Some(next),
7139                None => break,
7140            }
7141        }
7142        *self.search_cache()? = Some(found.clone());
7143        Ok(found)
7144    }
7145
7146    /// Every issue this board's own search reports with `also` beside its scope, walked to
7147    /// exhaustion — held for no later read, which may not be narrowed alike.
7148    async fn searched_narrowly(&self, also: &str) -> Result<Vec<Resolved>, SourceError> {
7149        let mut after: Option<String> = None;
7150        let mut found = Vec::new();
7151        let search = self.board_search(Some(also));
7152        loop {
7153            let (page, next) = self
7154                .search_page(&search, MAX_PAGE_SIZE, after.as_deref())
7155                .await?;
7156            found.extend(page);
7157            match next {
7158                Some(next) => after = Some(next),
7159                None => return Ok(found),
7160            }
7161        }
7162    }
7163
7164    /// This process's own view of the board's issues, or the refusal a poisoned lock is.
7165    fn search_cache(
7166        &self,
7167    ) -> Result<std::sync::MutexGuard<'_, Option<Vec<Resolved>>>, SourceError> {
7168        self.search_cache
7169            .lock()
7170            .map_err(|_| SourceError::Unavailable {
7171                message: "this source's view of the board's issues was left inconsistent by an \
7172                      earlier failure; next: run the command again"
7173                    .into(),
7174            })
7175    }
7176
7177    /// `found`, with everything this run wrote that `keep` accepts and the read did not
7178    /// report.
7179    ///
7180    /// See [`Self::created`] and [`Self::board_issues`] for why a read has to be completed
7181    /// at all: the search index is behind, and a node read of an item filed moments ago can
7182    /// be too.
7183    fn completed_with_written(
7184        &self,
7185        mut found: Vec<Resolved>,
7186        keep: impl Fn(&Resolved) -> bool,
7187    ) -> Result<Vec<Resolved>, SourceError> {
7188        for own in self.created()?.iter().filter(|own| keep(own)) {
7189            if !found.iter().any(|item| item.id == own.id) {
7190                found.push(own.clone());
7191            }
7192        }
7193        Ok(found)
7194    }
7195
7196    /// What resolving one node id reached.
7197    ///
7198    /// Three answers rather than an `Option`, because a board *draft* is none of the other
7199    /// two: it is not an issue, so the issue fragment reads nothing of it, and a read of one
7200    /// is completed by a read of the draft itself rather than reported as nothing.
7201    async fn reach(&self, id: &NativeId) -> Result<Reached, SourceError> {
7202        let asked = self
7203            .graphql(
7204                graphql::ISSUE,
7205                json!({"id":id.0,"first":MAX_PAGE_SIZE,"nestedFirst":NESTED_PAGE_SIZE,
7206                       "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
7207            )
7208            .await;
7209        let data = match asked {
7210            Ok(data) => data,
7211            // A string that is not a node id at all is not a failure to report: it is an id
7212            // this board does not hold, which is what every read of one already answers.
7213            Err(error) if unresolvable_node(&error) => return Ok(Reached::Nothing),
7214            Err(error) => return Err(error),
7215        };
7216        let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
7217            return Ok(Reached::Nothing);
7218        };
7219        if optional_str(node, "__typename")? == Some("DraftIssue") {
7220            return Ok(Reached::Draft);
7221        }
7222        Ok(match self.resolve_issue(node).await? {
7223            Some(item) => Reached::Held(Box::new(item)),
7224            None => Reached::Nothing,
7225        })
7226    }
7227
7228    /// One item of this board by its own id, whatever kind it is.
7229    ///
7230    /// Resolved from the identifier alone: no search, board-wide or otherwise. What this
7231    /// run wrote is read first, because a node read of an item created moments ago can
7232    /// still be behind the board field values written onto it — see [`Self::created`].
7233    async fn item_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7234        if let Some(own) = self.created()?.iter().find(|own| own.id == *id) {
7235            return Ok(Some(own.clone()));
7236        }
7237        if let Some(held) = self.read_ahead()?.remove(id) {
7238            return Ok(held);
7239        }
7240        match self.reach(id).await? {
7241            Reached::Held(item) => Ok(Some(*item)),
7242            Reached::Nothing => Ok(None),
7243            Reached::Draft => self.draft_by_id(id).await,
7244        }
7245    }
7246
7247    /// [`Self::item_by_id`] for a document: one [`graphql::DOCUMENT_IN_PROJECT`] read, which
7248    /// answers the project it is filed under and that project's members beside it.
7249    ///
7250    /// Each is held for this command as a read of it would have been: the project for the
7251    /// next read of it by its id, and — when its page of members is the whole of them — the
7252    /// members for the next listing of that project. So a write held to who may read the
7253    /// document, which reads all three, is answered by this one request.
7254    async fn document_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7255        if self.created()?.iter().any(|own| own.id == *id) || self.read_ahead()?.contains_key(id) {
7256            return self.item_by_id(id).await;
7257        }
7258        let asked = self
7259            .graphql(
7260                graphql::DOCUMENT_IN_PROJECT,
7261                json!({"id":id.0,"first":MAX_PAGE_SIZE,"memberFirst":MEMBER_PAGE_SIZE,
7262                       "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
7263                       "duplicates":true}),
7264            )
7265            .await;
7266        let data = match asked {
7267            Ok(data) => data,
7268            Err(error) if unresolvable_node(&error) => return Ok(None),
7269            Err(error) => return Err(error),
7270        };
7271        let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
7272            return Ok(None);
7273        };
7274        if optional_str(node, "__typename")? == Some("DraftIssue") {
7275            return self.draft_by_id(id).await;
7276        }
7277        let Some(item) = self.resolve_issue(node).await? else {
7278            return Ok(None);
7279        };
7280        // An answer for another issue than the one asked about says nothing of that one.
7281        if item.id != *id {
7282            return Err(SourceError::Malformed {
7283                message: format!(
7284                    "GitHub answered issue {} when asked for document {}",
7285                    item.id.0, id.0
7286                ),
7287            });
7288        }
7289        if let Some(project) = node.get("project").filter(|value| !value.is_null())
7290            && let Some(parent) = self
7291                .resolve_issue(project)
7292                .await?
7293                .filter(|parent| Some(&parent.id) == item.parent.as_ref())
7294        {
7295            let members = project.get("subIssues").filter(|value| !value.is_null());
7296            let whole = members
7297                .and_then(|members| members.pointer("/pageInfo/hasNextPage"))
7298                .and_then(Value::as_bool)
7299                == Some(false);
7300            if whole {
7301                let nodes = members
7302                    .and_then(|members| members.get("nodes"))
7303                    .and_then(Value::as_array)
7304                    .ok_or_else(|| SourceError::Malformed {
7305                        message: "GitHub subIssues.nodes is not an array".into(),
7306                    })?;
7307                let mut children = Vec::new();
7308                for member in nodes {
7309                    if let Some(resolved) = self.resolve_issue(member).await? {
7310                        children.push(resolved);
7311                    }
7312                }
7313                // Held as the project's members only when every one resolved and says it is
7314                // filed under it: a page with any other answers nothing of all the members.
7315                if children.len() == nodes.len()
7316                    && children
7317                        .iter()
7318                        .all(|child| child.parent.as_ref() == Some(&parent.id))
7319                {
7320                    self.children_cache()?
7321                        .insert(parent.id.clone(), (parent.id.clone(), children));
7322                }
7323            }
7324            self.read_ahead()?.insert(parent.id.clone(), Some(parent));
7325        }
7326        Ok(Some(item))
7327    }
7328
7329    /// Several items of this board, each by its own id, in order — what [`Self::item_by_id`]
7330    /// answers for each, read [`DETAIL_BATCH`] at a time with [`graphql::ISSUE_DETAILS`] rather
7331    /// than one request per id.
7332    ///
7333    /// What this run wrote answers first, as it does there, and only the rest is read. One id
7334    /// left to read is read by [`Self::item_by_id`] itself, which costs what a batch does. A
7335    /// batch GitHub refuses because one of its ids resolves to no node at all is read again one
7336    /// id at a time, so that id is answered as not held and the others as themselves; a draft
7337    /// is completed by a read of the draft, exactly as there.
7338    async fn items_by_ids(&self, ids: &[NativeId]) -> Result<Vec<Option<Resolved>>, SourceError> {
7339        let mut found: Vec<Option<Option<Resolved>>> = {
7340            let created = self.created()?;
7341            ids.iter()
7342                .map(|id| {
7343                    created
7344                        .iter()
7345                        .find(|own| own.id == *id)
7346                        .map(|own| Some(own.clone()))
7347                })
7348                .collect()
7349        };
7350        let unread: Vec<NativeId> = ids
7351            .iter()
7352            .zip(&found)
7353            .filter(|(_, found)| found.is_none())
7354            .map(|(id, _)| id.clone())
7355            .collect();
7356        let mut read = Vec::with_capacity(unread.len());
7357        if let [one] = unread.as_slice() {
7358            read.push(self.item_by_id(one).await?);
7359        } else {
7360            for batch in unread.chunks(DETAIL_BATCH) {
7361                let data = match self
7362                    .graphql(graphql::ISSUE_DETAILS, detail_batch(batch, None))
7363                    .await
7364                {
7365                    Ok(data) => data,
7366                    Err(error) if unresolvable_node(&error) => {
7367                        for id in batch {
7368                            read.push(self.item_by_id(id).await?);
7369                        }
7370                        continue;
7371                    }
7372                    Err(error) => return Err(error),
7373                };
7374                for (slot, id) in batch.iter().enumerate() {
7375                    let node =
7376                        data.get(format!("i{slot}"))
7377                            .ok_or_else(|| SourceError::Malformed {
7378                                message: format!(
7379                                    "GitHub answered a batch read with no item for {}",
7380                                    id.0
7381                                ),
7382                            })?;
7383                    read.push(if node.is_null() {
7384                        None
7385                    } else if optional_str(node, "__typename")? == Some("DraftIssue") {
7386                        self.draft_by_id(id).await?
7387                    } else {
7388                        if optional_str(node, "__typename")? == Some("Issue")
7389                            && required_str(node, "id")? != id.0
7390                        {
7391                            return Err(SourceError::Malformed {
7392                                message: format!(
7393                                    "GitHub answered the read of {} with issue {}",
7394                                    id.0,
7395                                    required_str(node, "id")?
7396                                ),
7397                            });
7398                        }
7399                        self.resolve_issue(node).await?
7400                    });
7401                }
7402            }
7403        }
7404        let mut read = read.into_iter();
7405        Ok(found
7406            .iter_mut()
7407            .map(|slot| slot.take().unwrap_or_else(|| read.next().flatten()))
7408            .collect())
7409    }
7410
7411    fn read_ahead(
7412        &self,
7413    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Option<Resolved>>>, SourceError> {
7414        self.read_ahead
7415            .lock()
7416            .map_err(|_| SourceError::Unavailable {
7417                message:
7418                    "items read ahead for a copy were left inconsistent; run the command again"
7419                        .into(),
7420            })
7421    }
7422
7423    fn resolved_cache(
7424        &self,
7425    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Resolved>>, SourceError> {
7426        self.resolved_cache
7427            .lock()
7428            .map_err(|_| SourceError::Unavailable {
7429                message: "resolved item records were left inconsistent; run the command again"
7430                    .into(),
7431            })
7432    }
7433
7434    /// Reuse a record this invocation already resolved. The mutation sender invalidates
7435    /// it before writing, so a partial failure cannot leave a pre-write binding behind.
7436    async fn bound_item(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7437        let cached = self.resolved_cache()?.get(id).cloned();
7438        if let Some(item) = cached {
7439            return Ok(Some(item));
7440        }
7441        self.item_by_id(id).await
7442    }
7443
7444    /// Take out the item an issue read by reference reached for `id`, when one is held: the
7445    /// status write it was read for is the one caller, so no other read or write is ever
7446    /// answered from a read that selected only what that write needs.
7447    fn take_held(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7448        Ok(self
7449            .held_cache
7450            .lock()
7451            .map_err(|_| SourceError::Unavailable {
7452                message: "items read by issue reference were left inconsistent; run the \
7453                          command again"
7454                    .into(),
7455            })?
7456            .remove(id))
7457    }
7458
7459    /// One board draft by its own id, with the board item it sits in — or `None` when no
7460    /// item of this board is that draft's.
7461    ///
7462    /// The same decision [`Self::resolve_issue`] makes for an issue, over the draft's own
7463    /// `projectV2Items`: an entry naming this board is what makes it this board's. GitHub
7464    /// links a draft to one board item, so the page this read carries is the whole of that
7465    /// connection, and a page that reports more than it holds is refused rather than read
7466    /// as an answer about memberships nobody read.
7467    async fn draft_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7468        let data = self
7469            .graphql(
7470                graphql::DRAFT,
7471                json!({"id":id.0,"nestedFirst":NESTED_PAGE_SIZE,
7472                       "boardItems":BOARD_ITEMS_PAGE_SIZE}),
7473            )
7474            .await?;
7475        // Gone between the two reads is an answer — the draft is no longer there. Anything
7476        // else than the draft [`Self::reach`] was just told this id is, is not one.
7477        let Some(draft) = data.get("node").filter(|node| !node.is_null()) else {
7478            return Ok(None);
7479        };
7480        if optional_str(draft, "__typename")? != Some("DraftIssue") {
7481            return Err(SourceError::Malformed {
7482                message: format!(
7483                    "GitHub answered {} as a draft and then as something else",
7484                    id.0
7485                ),
7486            });
7487        }
7488        if required_str(draft, "id")? != id.0 {
7489            return Err(SourceError::Malformed {
7490                message: format!("GitHub answered a different draft for {}", id.0),
7491            });
7492        }
7493        let memberships = draft
7494            .get("projectV2Items")
7495            .ok_or_else(|| SourceError::Malformed {
7496                message: format!("GitHub draft {} is missing projectV2Items", id.0),
7497            })?;
7498        let nodes = memberships
7499            .get("nodes")
7500            .and_then(Value::as_array)
7501            .ok_or_else(|| SourceError::Malformed {
7502                message: format!("GitHub draft {} projectV2Items.nodes is not an array", id.0),
7503            })?;
7504        let info = memberships
7505            .get("pageInfo")
7506            .ok_or_else(|| SourceError::Malformed {
7507                message: format!("GitHub draft {} projectV2Items has no pageInfo", id.0),
7508            })?;
7509        // Read whether or not this board's entry is on the page: a page claiming more than
7510        // the one item GitHub links a draft to is a malformed answer either way.
7511        if required_bool(info, "hasNextPage")? || nodes.len() > 1 {
7512            return Err(SourceError::Malformed {
7513                message: format!(
7514                    "GitHub draft {} reports more board items than the one GitHub links a draft \
7515                     to",
7516                    id.0
7517                ),
7518            });
7519        }
7520        if let Some(node) = nodes.first()
7521            && node
7522                .pointer("/project/number")
7523                .and_then(Value::as_u64)
7524                .is_none()
7525        {
7526            return Err(SourceError::Malformed {
7527                message: format!(
7528                    "GitHub draft {} board item has no numeric project number",
7529                    id.0
7530                ),
7531            });
7532        }
7533        let Some(held) = self.board_entry(nodes) else {
7534            return Ok(None);
7535        };
7536        if required_str(
7537            held.get("project").ok_or_else(|| SourceError::Malformed {
7538                message: format!("GitHub draft {} board item has no project", id.0),
7539            })?,
7540            "id",
7541        )? != self.board_fields().await?.id.as_str()
7542        {
7543            return Ok(None);
7544        }
7545        let item = json!({
7546            "id": required_str(held, "id")?,
7547            "project": held.get("project"),
7548            "fieldValues": held.get("fieldValues"),
7549            "content": draft,
7550        });
7551        self.resolve(&item)
7552    }
7553
7554    /// The board's own id and field definitions, for a write whose item does not carry
7555    /// them — never its items.
7556    ///
7557    /// A board this command has already listed supplies them, since it read them beside its
7558    /// items; otherwise they come from [`graphql::BOARD_FIELDS`], once per command. Neither
7559    /// is consulted about which items the board holds: see the module documentation for
7560    /// why a question about one known item is answered by reading that item.
7561    async fn board_fields(&self) -> Result<BoardFields, SourceError> {
7562        if let Some(board) = self.board_cache()?.as_ref() {
7563            return Ok(BoardFields {
7564                id: BoardId::parse(&board.id)?,
7565                fields: board.fields.clone(),
7566            });
7567        }
7568        if let Some(held) = self.fields_cache()?.clone() {
7569            return Ok(held);
7570        }
7571        let data = self
7572            .graphql(
7573                graphql::BOARD_FIELDS,
7574                json!({"owner":self.owner,"number":self.project_number,
7575                       "nestedFirst":NESTED_PAGE_SIZE}),
7576            )
7577            .await?;
7578        self.fields_read(&data)
7579    }
7580
7581    /// The board's id and fields out of an answer carrying the `boardFields` root, held for
7582    /// the rest of this command.
7583    fn fields_read(&self, data: &Value) -> Result<BoardFields, SourceError> {
7584        let board = data
7585            .pointer("/boardFields/projectV2")
7586            .filter(|value| !value.is_null())
7587            .ok_or_else(|| SourceError::Refused {
7588                message: format!(
7589                    "GitHub project {}/{} was not found or is not visible to the token",
7590                    self.owner, self.project_number
7591                ),
7592            })?;
7593        let read = BoardFields {
7594            id: BoardId::parse(required_str(board, "id")?)?,
7595            fields: board.get("fields").cloned().unwrap_or(Value::Null),
7596        };
7597        *self.fields_cache()? = Some(read.clone());
7598        Ok(read)
7599    }
7600
7601    /// Read what creating an issue in `repository` needs and this command has not read yet —
7602    /// the board's fields and the repository's node id — in one request when it needs both.
7603    ///
7604    /// When either is already known this sends nothing, and the other is read by its own
7605    /// document where it is asked for, so no create reads anything twice.
7606    async fn creation_context(
7607        &self,
7608        repository: &RepositoryTarget,
7609        incoming: &Incoming<'_>,
7610    ) -> Result<(), SourceError> {
7611        let fields_known = self.board_cache()?.is_some() || self.fields_cache()?.is_some();
7612        if fields_known || self.repository_cache()?.contains_key(repository) {
7613            return Ok(());
7614        }
7615        // A placement an earlier process kept is taken only while the project issue this create
7616        // has just read shows its setup-context token unchanged; see `projection`.
7617        if self.placed_by_kept(repository, incoming.parent) {
7618            return Ok(());
7619        }
7620        let data = self
7621            .graphql(
7622                graphql::CREATION_CONTEXT,
7623                json!({"owner":self.owner,"number":self.project_number,
7624                       "nestedFirst":NESTED_PAGE_SIZE,"repositoryOwner":repository.owner,
7625                       "repositoryName":repository.name}),
7626            )
7627            .await?;
7628        self.fields_read(&data)?;
7629        self.repository_read(&data, repository, incoming)?;
7630        Ok(())
7631    }
7632
7633    /// This process's own view of the board's fields, or the refusal a poisoned lock is.
7634    fn fields_cache(&self) -> Result<std::sync::MutexGuard<'_, Option<BoardFields>>, SourceError> {
7635        self.fields_cache
7636            .lock()
7637            .map_err(|_| SourceError::Unavailable {
7638                message: "this source's view of the board's fields was left inconsistent by an \
7639                      earlier failure; next: run the command again"
7640                    .into(),
7641            })
7642    }
7643
7644    /// What a write to `item` needs of the board, read off that item when it says enough and
7645    /// off [`Self::board_fields`] when it does not.
7646    ///
7647    /// A node read of an item names its board and carries the definition of every field it
7648    /// holds a value of — so an item naming its board, holding a value of the origin field
7649    /// when the write carries an origin, and, when the write carries a status, holding a
7650    /// `Status` value, needs no read of the board at all. **Nothing the item does not say is
7651    /// guessed:** a field it holds no value of may still be on the board, and a view reading it
7652    /// as absent would refuse a write the board can take or skip a field write the board
7653    /// needs, so such an item — and a create, which has no item yet — takes the board's fields
7654    /// from their own read instead. A write carrying no origin to an item holding none — every
7655    /// write out of a source declared private — writes no origin whatever the board defines,
7656    /// so it needs no definition of that field.
7657    async fn fields_for(
7658        &self,
7659        item: Option<&Resolved>,
7660        writes_origin: bool,
7661        writes_status: bool,
7662        selects_priority: bool,
7663    ) -> Result<BoardFields, SourceError> {
7664        if let Some(board) = item.and_then(Resolved::carried_board) {
7665            return Ok(board);
7666        }
7667        if let Some(item) = item
7668            && let Some(board_id) = item.named_board()
7669            && (!writes_origin || item.defines(ORIGIN_FIELD))
7670            && (!writes_status || item.defines("Status"))
7671            && (!selects_priority || item.defines(PRIORITY_FIELD))
7672            && self
7673                .metadata_fields
7674                .iter()
7675                .all(|projection| item.defines(&projection.field))
7676        {
7677            return Ok(BoardFields {
7678                id: board_id,
7679                fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
7680            });
7681        }
7682        self.board_fields().await
7683    }
7684
7685    /// Everything filed under one issue of this board, walked to exhaustion — or `None`
7686    /// when that id names nothing here with a sub-issue relationship to walk.
7687    ///
7688    /// `None` and an empty answer are different: `None` is *this is not an issue of this
7689    /// GitHub*, which is what sends a project selector on to be read as a name, and an
7690    /// empty vector is a project that holds nothing.
7691    async fn sub_issues(&self, id: &NativeId) -> Result<Option<Vec<Resolved>>, SourceError> {
7692        let mut after: Option<String> = None;
7693        let mut children = Vec::new();
7694        // The project issue as the first page carried it, held once the walk has ended.
7695        let mut parent: Option<Resolved> = None;
7696        loop {
7697            let asked = self
7698                .graphql(
7699                    graphql::SUB_ISSUES,
7700                    json!({"id":id.0,"memberFirst":MEMBER_PAGE_SIZE,"after":after,
7701                           "nestedFirst":NESTED_PAGE_SIZE,
7702                           "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
7703                )
7704                .await;
7705            let data = match asked {
7706                Ok(data) => data,
7707                // A string that is not a node id at all is not a failure to report: it is
7708                // the ordinary answer to a selector naming a project by its name.
7709                Err(error) if unresolvable_node(&error) => return Ok(None),
7710                Err(error) => return Err(error),
7711            };
7712            let Some(connection) = data
7713                .pointer("/node/subIssues")
7714                .filter(|value| !value.is_null())
7715            else {
7716                // No such node, or one with no sub-issue relationship — a board draft is
7717                // the one this board can really hold.
7718                return Ok(None);
7719            };
7720            if after.is_none()
7721                && let Some(node) = data.get("node").filter(|node| node.get("id").is_some())
7722            {
7723                parent = self
7724                    .resolve_issue(node)
7725                    .await?
7726                    .filter(|resolved| resolved.id == *id);
7727            }
7728            for node in connection
7729                .get("nodes")
7730                .and_then(Value::as_array)
7731                .ok_or_else(|| SourceError::Malformed {
7732                    message: "GitHub subIssues.nodes is not an array".into(),
7733                })?
7734            {
7735                if let Some(resolved) = self.resolve_issue(node).await? {
7736                    children.push(resolved);
7737                }
7738            }
7739            let info = connection
7740                .get("pageInfo")
7741                .ok_or_else(|| SourceError::Malformed {
7742                    message: "GitHub subIssues connection has no pageInfo".into(),
7743                })?;
7744            let next = required_bool(info, "hasNextPage")?
7745                .then(|| required_str(info, "endCursor"))
7746                .transpose()?;
7747            match next {
7748                Some(next) => {
7749                    validate_cursor_progress(after.as_deref(), next)?;
7750                    after = Some(next.to_owned());
7751                }
7752                None => {
7753                    // Held only once the walk has ended, so one failing part way holds
7754                    // nothing and every read it would have answered is made.
7755                    // The project issue the first page carried answers the next read of the
7756                    // project by its id in this command, as a read of it made now would: what
7757                    // classifying a project for a write reads straight after its members.
7758                    if let Some(parent) = &parent {
7759                        self.read_ahead()?
7760                            .entry(parent.id.clone())
7761                            .or_insert_with(|| Some(parent.clone()));
7762                    }
7763                    let mut carried = self.carried()?;
7764                    for item in parent.into_iter().chain(children.iter().cloned()) {
7765                        carried.insert(item.id.clone(), item);
7766                    }
7767                    return Ok(Some(children));
7768                }
7769            }
7770        }
7771    }
7772
7773    fn carried(
7774        &self,
7775    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Resolved>>, SourceError> {
7776        self.carried.lock().map_err(|_| SourceError::Unavailable {
7777            message: "items a project's listing carried were left inconsistent; run the \
7778                      command again"
7779                .into(),
7780        })
7781    }
7782
7783    /// Which issue of this board a project *name* is, or `None` when none is.
7784    ///
7785    /// One bounded query which filters on that name at the server, rather than a walk of
7786    /// every issue the board holds. The name is compared again here: the qualifier narrows
7787    /// what GitHub sends, and this source decides what it names.
7788    async fn project_by_name(&self, name: &str) -> Result<Option<NativeId>, SourceError> {
7789        let search = self.board_search(Some(&title_qualifier(name)));
7790        let mut after = None;
7791        loop {
7792            let (candidates, next) = self
7793                .search_page(&search, SEARCH_PAGE_SIZE, after.as_deref())
7794                .await?;
7795            if let Some(item) = candidates.into_iter().find(|item| {
7796                item.kind == BoardKind::Work(ItemKind::Project)
7797                    && item.title.eq_ignore_ascii_case(name)
7798            }) {
7799                return Ok(Some(item.id));
7800            }
7801            match next {
7802                Some(next) => after = Some(next),
7803                None => return Ok(None),
7804            }
7805        }
7806    }
7807
7808    /// Everything filed under one project of this board: the sub-issues of the issue that
7809    /// project is.
7810    ///
7811    /// Tasks *and* documents, because a document filed under a project is a sub-issue of it
7812    /// too — the caller keeps the kind it asked for. Nothing about this grows as the board
7813    /// gains projects, or as another project gains tasks.
7814    ///
7815    /// A qualified id names the issue and is asked for its sub-issues directly: one
7816    /// request, no search of any kind. Only a selector GitHub cannot resolve that way is
7817    /// read as a project *name*, which costs the one bounded search
7818    /// [`Self::project_by_name`] makes.
7819    ///
7820    /// What GitHub answered is held for the rest of the command — see [`Self::children_cache`]
7821    /// — and each answer is still cut to the items whose parent is this project, so one this
7822    /// process has since filed elsewhere is not reported here, and completed with what this
7823    /// process filed under it.
7824    async fn project_children(&self, selector: &NativeId) -> Result<Vec<Resolved>, SourceError> {
7825        let held = self.children_cache()?.get(selector).cloned();
7826        let (project, children) = match held {
7827            Some(held) => held,
7828            None => {
7829                let answered = match self.sub_issues(selector).await? {
7830                    Some(children) => (selector.clone(), children),
7831                    None => match self.project_by_name(&selector.0).await? {
7832                        Some(project) => {
7833                            let children = self.sub_issues(&project).await?.unwrap_or_default();
7834                            (project, children)
7835                        }
7836                        None => return Ok(Vec::new()),
7837                    },
7838                };
7839                self.children_cache()?
7840                    .insert(selector.clone(), answered.clone());
7841                answered
7842            }
7843        };
7844        let mut children: Vec<Resolved> = children
7845            .into_iter()
7846            .filter(|child| child.parent.as_ref() == Some(&project))
7847            .collect();
7848        for own in self.updated()?.iter() {
7849            if own.parent.as_ref() == Some(&project) && !children.iter().any(|c| c.id == own.id) {
7850                children.push(own.clone());
7851            }
7852        }
7853        self.completed_with_written(children, |own| own.parent.as_ref() == Some(&project))
7854    }
7855
7856    /// Every issue of this board GitHub's issue search reports updated at or after `since`,
7857    /// completed with what this run wrote — the candidates a comment-activity read confirms.
7858    ///
7859    /// Scoped by the board and by nothing else: `project:<owner>/<number>` reaches every issue
7860    /// on the board whatever repository, and whatever owner, it lives in, so no repository or
7861    /// owner qualifier is added and none is needed. What makes the `updated:` qualifier
7862    /// sufficient is a fact about GitHub rather than about this source: a comment written on an
7863    /// issue **and a comment edited on it** both move that issue's `updatedAt`. The credentialed
7864    /// journey `an_edited_comment_moves_its_issue_and_is_selected_since` in `tests/journey`
7865    /// re-takes that fact on every run of the lane, so a change on GitHub's side fails there
7866    /// rather than silently narrowing a caller's answer.
7867    ///
7868    /// The instant is written to the second, rounded down, which can only widen what the
7869    /// search returns; confirmation against each candidate's own comments is what makes the
7870    /// answer exact. The search is an index that lags a write by a second or two — the module
7871    /// documentation records it — so a caller that asks again from its last instant should
7872    /// overlap the two by more than that.
7873    async fn updated_since(&self, since: DateTime<Utc>) -> Result<Vec<Resolved>, SourceError> {
7874        let found = self.searched(&updated_qualifier(since)).await?;
7875        self.completed_with_written(found, |_| true)
7876    }
7877
7878    /// Every issue of this board GitHub's issue search reports for the board-scoped search
7879    /// narrowed by `also`, in pages of [`SEARCH_PAGE_SIZE`].
7880    ///
7881    /// Uncompleted: what this process wrote is added by the caller, which knows whether its
7882    /// own record is the fresher of the two.
7883    async fn searched(&self, also: &str) -> Result<Vec<Resolved>, SourceError> {
7884        let search = self.board_search(Some(also));
7885        let mut after: Option<String> = None;
7886        let mut found = Vec::new();
7887        loop {
7888            let (page, next) = self
7889                .search_page(&search, SEARCH_PAGE_SIZE, after.as_deref())
7890                .await?;
7891            found.extend(page);
7892            match next {
7893                Some(next) => after = Some(next),
7894                None => return Ok(found),
7895            }
7896        }
7897    }
7898
7899    /// A bounded task answer; the versioned cursor carries the connection position, how
7900    /// many rows of the page starting there were already handed out, and the own-write ids
7901    /// already observed, including across a new source instance.
7902    ///
7903    /// Every page is sent at [`SEARCH_PAGE_SIZE`] whatever the caller's limit, and a limit is
7904    /// sliced from the pages it needs; why is the module documentation's paging contract.
7905    async fn search_tasks(
7906        &self,
7907        query: &TaskQuery,
7908        page: &PageRequest,
7909        also: &str,
7910    ) -> Result<Page<Task>, SourceError> {
7911        let mut position = match &page.cursor {
7912            None => SearchPosition::default(),
7913            Some(cursor) => serde_json::from_str::<SearchPosition>(&cursor.0)
7914                .ok()
7915                .filter(|position| {
7916                    position.version == SEARCH_CURSOR_VERSION
7917                        && position.connection.valid_resume(position.offset)
7918                })
7919                .ok_or_else(|| SourceError::Config {
7920                    message: "page cursor is invalid".into(),
7921                })?,
7922        };
7923        let search = self.board_search(Some(also));
7924        let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
7925        let own = self.with_own_writes(Vec::new())?;
7926        // An issue this process commented on is a candidate of a comment-activity read
7927        // whether or not the search has caught up with the comment; see `Self::commented`.
7928        let commented = match query.commented_since {
7929            Some(_) => self.commented()?.clone(),
7930            None => Vec::new(),
7931        };
7932        for id in own.iter().map(|item| &item.id).chain(&commented) {
7933            if !position.own.contains(id) {
7934                position.own.push(id.clone());
7935            }
7936        }
7937        let mut tasks = Vec::new();
7938        while !position.connection.exhausted() && tasks.len() < limit {
7939            let first = SEARCH_PAGE_SIZE;
7940            // Page size is part of the key: a short cached answer cannot answer a wider ask.
7941            let key =
7942                serde_json::to_string(&("page", &search, &position.connection.after(), first))
7943                    .expect("search page key is serializable");
7944            let cached = if query.commented_since.is_none() {
7945                self.narrowed_cache()?.get(&key).cloned()
7946            } else {
7947                None
7948            };
7949            let (found, next) = match cached {
7950                Some(found) => {
7951                    let next = self
7952                        .search_next
7953                        .lock()
7954                        .map_err(|_| SourceError::Unavailable {
7955                            message:
7956                                "search pagination was left inconsistent; run the command again"
7957                                    .into(),
7958                        })?
7959                        .get(&key)
7960                        .cloned()
7961                        .flatten();
7962                    (found, next)
7963                }
7964                None => {
7965                    let (found, next) = self
7966                        .search_page(&search, first, position.connection.after())
7967                        .await?;
7968                    if query.commented_since.is_none() {
7969                        self.search_next
7970                            .lock()
7971                            .map_err(|_| SourceError::Unavailable {
7972                                message:
7973                                    "search pagination was left inconsistent; run the command again"
7974                                        .into(),
7975                            })?
7976                            .insert(key.clone(), next.clone());
7977                        self.narrowed_cache()?.insert(key, found.clone());
7978                    }
7979                    (found, next)
7980                }
7981            };
7982            let rows = found.len();
7983            // Every candidate of the page this read confirms by its comments is read together.
7984            let candidates =
7985                self.comment_candidates(found.iter().skip(position.offset), query, &query.project)?;
7986            self.hold_comment_pages(&candidates).await?;
7987            for mut item in found.into_iter().skip(position.offset) {
7988                if tasks.len() == limit {
7989                    break;
7990                }
7991                position.offset += 1;
7992                if position.own.contains(&item.id) {
7993                    if position.seen.contains(&item.id) {
7994                        continue;
7995                    }
7996                    position.seen.push(item.id.clone());
7997                    // The search's own copy of an issue this process only commented on is as
7998                    // good as a node read of it, since its comments are read either way.
7999                    let only_commented = commented.contains(&item.id)
8000                        && !own.iter().any(|written| written.id == item.id);
8001                    if !only_commented {
8002                        let updated_at = item.updated_at;
8003                        let Some(written) = self.search_written(&own, &item.id).await? else {
8004                            continue;
8005                        };
8006                        item = written;
8007                        item.updated_at = item.updated_at.max(updated_at);
8008                        self.resolved_cache()?.insert(item.id.clone(), item.clone());
8009                    }
8010                }
8011                if item.kind == BoardKind::Work(ItemKind::Task) {
8012                    let task = item.task()?;
8013                    if task_matches(&task, query, &query.project)
8014                        && self.commented_since(&item, query.commented_since).await?
8015                    {
8016                        tasks.push(task);
8017                    }
8018                }
8019            }
8020            if position.offset < rows {
8021                continue;
8022            }
8023            position.offset = 0;
8024            position.connection = match next {
8025                Some(after) => SearchConnection::Continuing {
8026                    after: Cursor(after),
8027                },
8028                None => SearchConnection::Exhausted {},
8029            };
8030        }
8031        if position.connection.exhausted() {
8032            for id in position.own.clone() {
8033                if position.seen.contains(&id) {
8034                    continue;
8035                }
8036                if tasks.len() == limit {
8037                    break;
8038                }
8039                position.seen.push(id.clone());
8040                let Some(item) = self.search_written(&own, &id).await? else {
8041                    continue;
8042                };
8043                if item.kind == BoardKind::Work(ItemKind::Task) {
8044                    let task = item.task()?;
8045                    if task_matches(&task, query, &query.project)
8046                        && self.commented_since(&item, query.commented_since).await?
8047                    {
8048                        tasks.push(task);
8049                    }
8050                }
8051            }
8052        }
8053        let more = !position.connection.exhausted()
8054            || position.own.iter().any(|id| !position.seen.contains(id));
8055        Ok(Page {
8056            items: tasks,
8057            next: more.then(|| {
8058                Cursor(serde_json::to_string(&position).expect("search position is serializable"))
8059            }),
8060        })
8061    }
8062
8063    /// A resumed process has the ids but no write records; resolve only a record the
8064    /// current page needs, by its uncached node read rather than the lagging search index.
8065    async fn search_written(
8066        &self,
8067        own: &[Resolved],
8068        id: &NativeId,
8069    ) -> Result<Option<Resolved>, SourceError> {
8070        match own.iter().find(|item| item.id == *id) {
8071            Some(item) => Ok(Some(item.clone())),
8072            None => self.item_by_id(id).await,
8073        }
8074    }
8075
8076    /// The candidates for a task query carrying a text, metadata or origin predicate, read
8077    /// without enumerating the board — or `None` for a query carrying none of the three, which
8078    /// keeps the reads it always had.
8079    ///
8080    /// An origin is answered by [`Self::origin_candidates`], whatever else the query carries,
8081    /// because it names at most a handful of items. Text and metadata are answered by one
8082    /// board-scoped issue search carrying every term — see [`narrowing_qualifiers`] — narrowed
8083    /// further by `updated:>=` when the query also asks for comment activity, since both
8084    /// qualifiers must hold of an issue the answer keeps. Every candidate is confirmed in
8085    /// process afterwards by the same predicates [`task_matches`] applies to every read.
8086    ///
8087    /// Completed with what this process wrote, its own record winning over the index's copy
8088    /// of the same item: see [`Self::with_own_writes`].
8089    async fn narrowed(&self, query: &TaskQuery) -> Result<Option<Vec<Resolved>>, SourceError> {
8090        self.send_pending_origins(None).await?;
8091        let asked = match (&query.origin, narrowing_qualifiers(query)) {
8092            (Some(origin), _) => Narrowing::Origin(origin.clone()),
8093            (None, Some(qualifiers)) => Narrowing::Search(match query.commented_since {
8094                Some(since) => format!("{} {qualifiers}", updated_qualifier(since)),
8095                None => qualifiers,
8096            }),
8097            (None, None) => return Ok(None),
8098        };
8099        // A question about comment activity is asked afresh every time, as it always was: it
8100        // is the one a caller polls from one source while waiting for the index, and an
8101        // answer held from the first poll would be the answer to every later one.
8102        let key = query.commented_since.is_none().then(|| asked.key());
8103        let cached = match &key {
8104            Some(key) => self.narrowed_cache()?.get(key).cloned(),
8105            None => None,
8106        };
8107        let found = match cached {
8108            Some(found) => found,
8109            None => {
8110                let found = match &asked {
8111                    Narrowing::Origin(origin) => self.origin_candidates(origin).await?,
8112                    Narrowing::Search(also) => self.searched(also).await?,
8113                };
8114                if let Some(key) = key {
8115                    self.narrowed_cache()?.insert(key, found.clone());
8116                }
8117                found
8118            }
8119        };
8120        self.with_own_writes(found).map(Some)
8121    }
8122
8123    /// The candidates for a project or unscoped document query carrying a searchable text,
8124    /// read without enumerating the board — or `None` for a query with no text or a blank one,
8125    /// which keeps the read it always had.
8126    ///
8127    /// The text is sent as the very phrase a task query's text is — see [`text_qualifiers`] —
8128    /// in one board-scoped issue search walked to its end at [`SEARCH_PAGE_SIZE`], so what it
8129    /// costs is the issues that match and never the board. Its answer is held for the command
8130    /// under the same key [`Self::narrowed`] holds that search under, so a walk of the caller's
8131    /// pages asks GitHub once. Every candidate is confirmed afterwards by its kind and by the
8132    /// substring rule, exactly as an item of the wider read was, and is completed with what this
8133    /// process wrote: see [`Self::with_own_writes`].
8134    async fn text_searched(
8135        &self,
8136        text: Option<&TextQuery>,
8137    ) -> Result<Option<Vec<Resolved>>, SourceError> {
8138        let Some(also) = text_qualifiers(text) else {
8139            return Ok(None);
8140        };
8141        let key = Narrowing::Search(also.clone()).key();
8142        let cached = self.narrowed_cache()?.get(&key).cloned();
8143        let found = match cached {
8144            Some(found) => found,
8145            None => {
8146                let found = self.searched(&also).await?;
8147                self.narrowed_cache()?.insert(key, found.clone());
8148                found
8149            }
8150        };
8151        self.with_own_writes(found).map(Some)
8152    }
8153
8154    /// Every `kind` item of this board whose own origin is exactly `origin`: the candidates
8155    /// [`Self::narrowed`] reads for a task query carrying that origin — one
8156    /// [`graphql::ORIGIN_LOOKUP`] walk, held for the command under the same key, completed with
8157    /// what this process wrote — each confirmed against its own origin entry.
8158    ///
8159    /// What answers a project or document listing by origin, so finding every copy of one plan
8160    /// costs the items that carry its origin and never a page of the board.
8161    async fn copied_from(
8162        &self,
8163        origin: &str,
8164        kind: BoardKind,
8165    ) -> Result<Vec<Resolved>, SourceError> {
8166        let wanted = TaskQuery {
8167            origin: Some(origin.to_owned()),
8168            ..TaskQuery::default()
8169        };
8170        Ok(self
8171            .narrowed(&wanted)
8172            .await?
8173            .unwrap_or_default()
8174            .into_iter()
8175            .filter(|item| item.kind == kind && wanted.origin_matches(&item.metadata()))
8176            .collect())
8177    }
8178
8179    /// Every item of this board that may carry `origin` — a superset of those that do — found
8180    /// by [`graphql::ORIGIN_LOOKUP`] and never by enumerating the board.
8181    ///
8182    /// The union of the board's own field filter over the `onetaskgraph.origin` text field —
8183    /// which reads the field every carrier holds, whichever release wrote it — and the
8184    /// board-scoped issue search for the same id as a phrase in the body, where this source
8185    /// mirrors it. The caller adds the third read, this process's own writes. Candidates are
8186    /// returned unconfirmed; [`task_matches`] compares each one's own origin field with the
8187    /// query's, exactly.
8188    ///
8189    /// Both connections are walked to exhaustion, each from its own cursor. One that has
8190    /// already ended is sent its last cursor again, which answers an empty page, so the one
8191    /// document serves every page of either. What the two leave is stated in the module
8192    /// documentation: a carrier another process added within the last second or two, before
8193    /// either index has it.
8194    async fn origin_candidates(&self, origin: &str) -> Result<Vec<Resolved>, SourceError> {
8195        let filter = format!("{ORIGIN_FIELD}:{}", quoted(origin));
8196        let search = self.board_search(Some(&format!("in:body {}", quoted(&as_stored(origin)))));
8197        let mut items_after: Option<String> = None;
8198        let mut search_after: Option<String> = None;
8199        let mut found: Vec<Resolved> = Vec::new();
8200        let keep = |resolved: Resolved, found: &mut Vec<Resolved>| {
8201            if !found.iter().any(|held| held.id == resolved.id) {
8202                found.push(resolved);
8203            }
8204        };
8205        loop {
8206            let data = self
8207                .graphql(
8208                    graphql::ORIGIN_LOOKUP,
8209                    json!({"owner":self.owner,"number":self.project_number,"filter":filter,
8210                           "search":search,"type":"ISSUE","originFirst":ORIGIN_PAGE_SIZE,
8211                           "itemsAfter":items_after,"searchAfter":search_after,
8212                           "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
8213                           "duplicates":true}),
8214                )
8215                .await?;
8216            let items = data
8217                .pointer("/originItems/projectV2/items")
8218                .filter(|value| !value.is_null())
8219                .ok_or_else(|| SourceError::Refused {
8220                    message: format!(
8221                        "GitHub project {}/{} was not found or is not visible to the token",
8222                        self.owner, self.project_number
8223                    ),
8224                })?;
8225            for item in optional_nodes(Some(items), "project items")?
8226                .into_iter()
8227                .flatten()
8228            {
8229                // The board's own items list its drafts too, and a draft is not an issue: no
8230                // narrowed read answers with one, whatever its origin field holds.
8231                if let Some(resolved) = self.resolve(item)?
8232                    && resolved.content_kind == ContentKind::Issue
8233                {
8234                    keep(resolved, &mut found);
8235                }
8236            }
8237            let searched = data.get("search").ok_or_else(|| SourceError::Malformed {
8238                message: "GitHub search response has no search connection".into(),
8239            })?;
8240            for node in optional_nodes(Some(searched), "search")?
8241                .into_iter()
8242                .flatten()
8243            {
8244                if let Some(resolved) = self.resolve_issue(node).await? {
8245                    keep(resolved, &mut found);
8246                }
8247            }
8248            let items_next = resumed(items, items_after.as_deref())?;
8249            let search_next = resumed(searched, search_after.as_deref())?;
8250            if !items_next.has_more() && !search_next.has_more() {
8251                return Ok(found);
8252            }
8253            items_after = items_next.cursor();
8254            search_after = search_next.cursor();
8255        }
8256    }
8257
8258    /// `found`, with every item this process created or wrote in its place, and every one of
8259    /// them the read did not report added.
8260    ///
8261    /// This process's own record wins over the read's copy of the same item, because a read
8262    /// of an item written moments ago can still be behind what was written onto it — the
8263    /// origin field included, which is the one a narrowed read is confirmed against — and a
8264    /// read that still names an item under a predicate this process's write moved it out of
8265    /// must not return it. The one thing the read knows that the record cannot is when GitHub
8266    /// last saw the item change, which is what a comment-activity read rules a candidate out
8267    /// by, so the read's `updatedAt` is kept when the record has none of its own. See
8268    /// [`Self::created`] and [`Self::updated`](GitHubProjectsSource::updated).
8269    fn with_own_writes(&self, mut found: Vec<Resolved>) -> Result<Vec<Resolved>, SourceError> {
8270        // A board draft is not an issue, so no narrowed read returns one, and this process
8271        // having written one does not make it an answer either.
8272        let own: Vec<Resolved> = self
8273            .created()?
8274            .iter()
8275            .chain(self.updated()?.iter())
8276            .filter(|own| own.content_kind == ContentKind::Issue)
8277            .cloned()
8278            .collect();
8279        for mut own in own {
8280            self.resolved_cache()?.insert(own.id.clone(), own.clone());
8281            match found.iter_mut().find(|read| read.id == own.id) {
8282                Some(read) => {
8283                    own.updated_at = own.updated_at.max(read.updated_at);
8284                    *read = own;
8285                }
8286                None => found.push(own),
8287            }
8288        }
8289        Ok(found)
8290    }
8291
8292    /// Whether `item` has a comment created or last edited at or after `since` — always, when
8293    /// there is no instant to hold it to.
8294    ///
8295    /// The candidate's own `updatedAt` is read first, because a comment written or edited at
8296    /// or after the instant moved it there: an issue not updated since holds no such comment,
8297    /// and its comments are never asked for — unless this process commented on it in this
8298    /// command, when the `updatedAt` held may predate that comment; see [`Self::commented`]. Otherwise its comments are walked, oldest first,
8299    /// only as far as the first that matches. A board draft is not an issue and has no
8300    /// comments, so it never matches.
8301    async fn commented_since(
8302        &self,
8303        item: &Resolved,
8304        since: Option<DateTime<Utc>>,
8305    ) -> Result<bool, SourceError> {
8306        let Some(since) = since else {
8307            return Ok(true);
8308        };
8309        if item.content_kind == ContentKind::DraftIssue {
8310            return Ok(false);
8311        }
8312        // An `updatedAt` this process's own record or a lagging index holds can predate a
8313        // comment this process wrote since, so only an issue it did not comment on is ruled
8314        // out by one.
8315        if item.updated_at.is_some_and(|updated| updated < since)
8316            && !self.commented()?.contains(&item.id)
8317        {
8318            return Ok(false);
8319        }
8320        let query = TaskQuery {
8321            commented_since: Some(since),
8322            ..TaskQuery::default()
8323        };
8324        let mut after: Option<String> = None;
8325        // A first page read beside its fellow candidates answers as this read's own would.
8326        let held = self.held_comments()?.get(&item.id).cloned();
8327        if let Some(first) = held {
8328            if query.comments_match(&first.items) {
8329                return Ok(true);
8330            }
8331            match first.next {
8332                Some(next) => after = Some(next.0),
8333                None => return Ok(false),
8334            }
8335        }
8336        loop {
8337            let data = self
8338                .graphql(
8339                    graphql::ISSUE_COMMENTS,
8340                    json!({"id":item.id.0,"first":MAX_PAGE_SIZE,"after":after}),
8341                )
8342                .await?;
8343            let Some(connection) = data
8344                .get("node")
8345                .filter(|value| !value.is_null())
8346                .and_then(|node| node.get("comments"))
8347                .filter(|value| !value.is_null())
8348            else {
8349                // Removed since the search reported it: no longer an issue with comments.
8350                return Ok(false);
8351            };
8352            let comments = optional_nodes(Some(connection), "issue comments")?
8353                .into_iter()
8354                .flatten()
8355                .map(comment_from)
8356                .collect::<Result<Vec<_>, _>>()?;
8357            if query.comments_match(&comments) {
8358                return Ok(true);
8359            }
8360            match next_cursor(connection)? {
8361                Some(next) => {
8362                    validate_cursor_progress(after.as_deref(), &next.0)?;
8363                    after = Some(next.0);
8364                }
8365                None => return Ok(false),
8366            }
8367        }
8368    }
8369
8370    /// Every item on the board: the union of both enumerations GitHub offers of one.
8371    ///
8372    /// Neither contains the other, so neither is dropped — only `ProjectV2.items` lists a
8373    /// board **draft** and reads the board's own fields beside its items, and only the search
8374    /// reports an item that connection is behind on. The module documentation is where the lag and the
8375    /// measurements behind it are written down.
8376    ///
8377    /// A search result is admitted on the same terms as any other issue this source reaches
8378    /// directly — [`Self::resolve_issue`] keeps it only if that issue's own `projectItems`
8379    /// names *this* board — so an issue the index still believes is here after it was taken
8380    /// off is refused rather than reported.
8381    ///
8382    /// See [`Self::board_cache`]. Both completions happen on every call rather than once,
8383    /// which is what the cache could otherwise have broken.
8384    async fn board(&self) -> Result<Board, SourceError> {
8385        self.board_completed_by(None).await
8386    }
8387
8388    /// [`Self::board`], its search half narrowed by `also` when it is given — which an issue
8389    /// that half could add is then answered only if it holds.
8390    async fn board_completed_by(&self, also: Option<&str>) -> Result<Board, SourceError> {
8391        let cached = self.board_cache()?.clone();
8392        let mut board = match cached {
8393            Some(board) => board,
8394            None => {
8395                let read = self.read_board().await?;
8396                *self.board_cache()? = Some(read.clone());
8397                read
8398            }
8399        };
8400        let searched = match also {
8401            None => self.searched_issues().await?,
8402            Some(also) => self.searched_narrowly(also).await?,
8403        };
8404        // A complete sweep asks for every page of this view. Reconcile ids once per
8405        // view, rather than scanning the board for every search result on every page.
8406        let mut ids: std::collections::HashSet<_> =
8407            board.items.iter().map(|item| item.id.clone()).collect();
8408        for held in searched {
8409            if ids.insert(held.id.clone()) {
8410                board.items.push(held);
8411            }
8412        }
8413        for own in self.created()?.iter() {
8414            if ids.insert(own.id.clone()) {
8415                board.items.push(own.clone());
8416            }
8417        }
8418        Ok(board)
8419    }
8420
8421    /// Every open item of this board, drafts included, read through the board's own `is:open`
8422    /// filter page by page — never its unfiltered `items`, and with no issue search beside it —
8423    /// held for the command under [`OPEN_ITEMS_KEY`] on the terms every narrowed answer is
8424    /// held on, and completed with this process's own writes each time it is given.
8425    ///
8426    /// What a task listing whose every status category is open reads: an item is open exactly
8427    /// when GitHub's filter answers it, so the categories are still confirmed in process from
8428    /// each item's own node, and the answer is the whole board's filtered to the same
8429    /// categories — an open issue under a terminal card read as its card, a draft and an item
8430    /// under an option no mapping names included.
8431    async fn open_items(&self) -> Result<Vec<Resolved>, SourceError> {
8432        let key = OPEN_ITEMS_KEY.to_owned();
8433        let cached = self.narrowed_cache()?.get(&key).cloned();
8434        let mut found = match cached {
8435            Some(found) => found,
8436            None => {
8437                let found = self.read_open_items().await?;
8438                self.narrowed_cache()?.insert(key, found.clone());
8439                found
8440            }
8441        };
8442        // Every item this process wrote, drafts included: the filter answers drafts, so an
8443        // own draft is as much an answer as an own issue. Its category is confirmed below like
8444        // any other's, so one this process closed is left out there.
8445        let own: Vec<Resolved> = self
8446            .created()?
8447            .iter()
8448            .chain(self.updated()?.iter())
8449            .cloned()
8450            .collect();
8451        for own in own {
8452            match found.iter_mut().find(|read| read.id == own.id) {
8453                Some(read) => *read = own,
8454                None => found.push(own),
8455            }
8456        }
8457        Ok(found)
8458    }
8459
8460    /// Every page of [`graphql::OPEN_ITEMS`], resolved; the board's own fields are held for
8461    /// the writes that follow, as a reconcile holds them.
8462    async fn read_open_items(&self) -> Result<Vec<Resolved>, SourceError> {
8463        let mut after: Option<String> = None;
8464        let mut found = Vec::new();
8465        loop {
8466            let data = self
8467                .graphql(
8468                    graphql::OPEN_ITEMS,
8469                    json!({"owner":self.owner,"number":self.project_number,
8470                           "first":MAX_PAGE_SIZE,"after":after,"filter":OPEN_QUALIFIER,
8471                           "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
8472                )
8473                .await?;
8474            let board = data
8475                .pointer("/openItems/projectV2")
8476                .filter(|value| !value.is_null())
8477                .ok_or_else(|| SourceError::Refused {
8478                    message: format!(
8479                        "GitHub project {}/{} was not found or is not visible to the token",
8480                        self.owner, self.project_number
8481                    ),
8482                })?;
8483            *self.fields_cache()? = Some(BoardFields {
8484                id: BoardId::parse(required_str(board, "id")?)?,
8485                fields: board.get("fields").cloned().unwrap_or(Value::Null),
8486            });
8487            let items = board.get("items").ok_or_else(|| SourceError::Malformed {
8488                message: "GitHub project open items are missing".into(),
8489            })?;
8490            for item in items
8491                .get("nodes")
8492                .and_then(Value::as_array)
8493                .ok_or_else(|| SourceError::Malformed {
8494                    message: "GitHub project items.nodes is not an array".into(),
8495                })?
8496            {
8497                if let Some(resolved) = self.resolve(item)? {
8498                    found.push(resolved);
8499                }
8500            }
8501            let info = items
8502                .get("pageInfo")
8503                .ok_or_else(|| SourceError::Malformed {
8504                    message: "GitHub project items have no pageInfo".into(),
8505                })?;
8506            if !required_bool(info, "hasNextPage")? {
8507                return Ok(found);
8508            }
8509            let next = required_str(info, "endCursor")?;
8510            validate_cursor_progress(after.as_deref(), next)?;
8511            after = Some(next.to_owned());
8512        }
8513    }
8514
8515    /// This process's own view of the board, or the refusal a poisoned lock is.
8516    fn board_cache(&self) -> Result<std::sync::MutexGuard<'_, Option<Board>>, SourceError> {
8517        self.board_cache
8518            .lock()
8519            .map_err(|_| SourceError::Unavailable {
8520                message: "this source's view of the board was left inconsistent by an earlier \
8521                      failure; next: run the command again"
8522                    .into(),
8523            })
8524    }
8525
8526    /// Bring this process's own view of the board up to an item it has just written.
8527    ///
8528    /// A created item goes to `created`, which is what completes a board read GitHub's own
8529    /// eventual consistency has left behind. An item that was already there is replaced
8530    /// where it sits, so a second write of it in the same command reads its real parent
8531    /// rather than the one it had before the first write.
8532    ///
8533    /// "Where it sits" is three places, and missing an earlier one leaves a stale record
8534    /// that wins: an item this same run created is held in `created` and not in the cached
8535    /// board, and `board` completes the cached board *from* `created`, so replacing only
8536    /// the cached copy of such an item replaces nothing and the read still reports the
8537    /// title it was created with. The search is the third, and it is the one an item the
8538    /// board's own projection is behind on sits in *alone* — which is exactly the item this
8539    /// source is least able to re-read, so leaving it out would put the stale title back on
8540    /// the only items the completion in [`Self::board`] exists for.
8541    fn remember_written(&self, item: Resolved, created: bool) -> Result<(), SourceError> {
8542        self.resolved_cache()?.insert(item.id.clone(), item.clone());
8543        if created {
8544            self.created()?.push(item);
8545            return Ok(());
8546        }
8547        {
8548            let mut own = self.created()?;
8549            if let Some(held) = own.iter_mut().find(|held| held.id == item.id) {
8550                *held = item;
8551                return Ok(());
8552            }
8553        }
8554        {
8555            let mut own = self.updated()?;
8556            match own.iter_mut().find(|held| held.id == item.id) {
8557                Some(held) => *held = item.clone(),
8558                None => own.push(item.clone()),
8559            }
8560        }
8561        if let Some(board) = self.board_cache()?.as_mut()
8562            && let Some(held) = board.items.iter_mut().find(|held| held.id == item.id)
8563        {
8564            *held = item.clone();
8565        }
8566        if let Some(found) = self.search_cache()?.as_mut()
8567            && let Some(held) = found.iter_mut().find(|held| held.id == item.id)
8568        {
8569            *held = item.clone();
8570        }
8571        for found in self.narrowed_cache()?.values_mut() {
8572            if let Some(held) = found.iter_mut().find(|held| held.id == item.id) {
8573                *held = item.clone();
8574            }
8575        }
8576        for (_, found) in self.children_cache()?.values_mut() {
8577            if let Some(held) = found.iter_mut().find(|held| held.id == item.id) {
8578                *held = item.clone();
8579            }
8580        }
8581        Ok(())
8582    }
8583
8584    /// Forget one item this process has just deleted, from every half of its own view.
8585    fn forget(&self, id: &NativeId) -> Result<(), SourceError> {
8586        if let Some(Deferred::Held { created, .. }) = self.deferred()?.as_mut() {
8587            created.retain(|held| held.content != *id);
8588        }
8589        self.resolved_cache()?.remove(id);
8590        self.read_ahead()?.remove(id);
8591        self.carried()?.remove(id);
8592        self.created()?.retain(|own| own.id != *id);
8593        self.updated()?.retain(|own| own.id != *id);
8594        self.commented()?.retain(|own| own != id);
8595        if let Some(board) = self.board_cache()?.as_mut() {
8596            board.items.retain(|item| item.id != *id);
8597        }
8598        if let Some(found) = self.search_cache()?.as_mut() {
8599            found.retain(|item| item.id != *id);
8600        }
8601        for found in self.narrowed_cache()?.values_mut() {
8602            found.retain(|item| item.id != *id);
8603        }
8604        for (_, found) in self.children_cache()?.values_mut() {
8605            found.retain(|item| item.id != *id);
8606        }
8607        Ok(())
8608    }
8609
8610    /// This process's own record of each narrowed answer, or the refusal a poisoned lock is.
8611    fn narrowed_cache(
8612        &self,
8613    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<String, Vec<Resolved>>>, SourceError> {
8614        self.narrowed_cache
8615            .lock()
8616            .map_err(|_| SourceError::Unavailable {
8617                message: "this source's view of a narrowed read was left inconsistent by an \
8618                      earlier failure; next: run the command again"
8619                    .into(),
8620            })
8621    }
8622
8623    /// This process's own record of each project's sub-issues, or the refusal a poisoned lock
8624    /// is.
8625    /// The tasks `project` holds, as a copy's batched read found them this command, when it did.
8626    fn held_task_children(&self, project: &NativeId) -> Result<Option<Vec<Resolved>>, SourceError> {
8627        Ok(self.task_children()?.get(project).cloned())
8628    }
8629
8630    fn task_children(
8631        &self,
8632    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Vec<Resolved>>>, SourceError> {
8633        self.task_children
8634            .lock()
8635            .map_err(|_| SourceError::Unavailable {
8636                message: "this source's record of a project's tasks was left inconsistent by an \
8637                          earlier failure; next: run the command again"
8638                    .into(),
8639            })
8640    }
8641
8642    fn children_cache(&self) -> Result<std::sync::MutexGuard<'_, ProjectChildren>, SourceError> {
8643        self.children_cache
8644            .lock()
8645            .map_err(|_| SourceError::Unavailable {
8646                message: "this source's view of a project's tasks was left inconsistent by an \
8647                      earlier failure; next: run the command again"
8648                    .into(),
8649            })
8650    }
8651
8652    /// Every page of the board, read from GitHub.
8653    async fn read_board(&self) -> Result<Board, SourceError> {
8654        let mut after: Option<String> = None;
8655        let mut items = Vec::new();
8656        let mut board;
8657        loop {
8658            let page = self.board_page(after.as_deref(), MAX_PAGE_SIZE).await?;
8659            for item in page
8660                .pointer("/items/nodes")
8661                .and_then(Value::as_array)
8662                .ok_or_else(|| SourceError::Malformed {
8663                    message: "GitHub project items.nodes is not an array".into(),
8664                })?
8665            {
8666                if let Some(resolved) = self.resolve(item)? {
8667                    items.push(resolved);
8668                }
8669            }
8670            let info = page
8671                .pointer("/items/pageInfo")
8672                .ok_or_else(|| SourceError::Malformed {
8673                    message: "GitHub project items have no pageInfo".into(),
8674                })?;
8675            let has_next = required_bool(info, "hasNextPage")?;
8676            let next = has_next
8677                .then(|| required_str(info, "endCursor"))
8678                .transpose()?;
8679            board = page.clone();
8680            match next {
8681                Some(next) => {
8682                    validate_cursor_progress(after.as_deref(), next)?;
8683                    after = Some(next.to_owned());
8684                }
8685                None => break,
8686            }
8687        }
8688        Ok(Board {
8689            id: required_str(&board, "id")?.to_owned(),
8690            fields: board.get("fields").cloned().unwrap_or(Value::Null),
8691            items,
8692        })
8693    }
8694
8695    /// The existing items this source has written, for completing a narrowed read that is
8696    /// behind; see [`Self::updated`](GitHubProjectsSource::updated).
8697    fn updated(&self) -> Result<std::sync::MutexGuard<'_, Vec<Resolved>>, SourceError> {
8698        self.updated.lock().map_err(|_| SourceError::Unavailable {
8699            message: "this source's record of what it wrote in this run was left inconsistent \
8700                      by an earlier failure; next: run the command again"
8701                .into(),
8702        })
8703    }
8704
8705    /// The issues this source has commented on in this command; see
8706    /// [`Self::commented`](GitHubProjectsSource::commented).
8707    fn commented(&self) -> Result<std::sync::MutexGuard<'_, Vec<NativeId>>, SourceError> {
8708        self.commented.lock().map_err(|_| SourceError::Unavailable {
8709            message: "this source's record of what it commented on in this run was left \
8710                      inconsistent by an earlier failure; next: run the command again"
8711                .into(),
8712        })
8713    }
8714
8715    /// Called only once GitHub has answered the comment write, so an issue whose comment
8716    /// failed is never made a candidate a later read would pay a node read for.
8717    fn remember_commented(&self, issue: &NativeId) -> Result<(), SourceError> {
8718        // A comment page held for this command is no longer what the issue holds.
8719        self.held_comments()?.remove(issue);
8720        let mut commented = self.commented()?;
8721        if !commented.contains(issue) {
8722            commented.push(issue.clone());
8723        }
8724        Ok(())
8725    }
8726
8727    /// The items this source has created, for completing a board read that is behind.
8728    fn created(&self) -> Result<std::sync::MutexGuard<'_, Vec<Resolved>>, SourceError> {
8729        self.created.lock().map_err(|_| SourceError::Unavailable {
8730            message: "this source's record of what it created in this run was left \
8731                      inconsistent by an earlier failure; next: run the command again"
8732                .into(),
8733        })
8734    }
8735
8736    /// One board item as this source reports it, or `None` for content it ignores.
8737    ///
8738    /// A pull request is neither a project nor a task — it is somebody's change, not a
8739    /// unit of plan — and an item whose content the token cannot see has nothing to
8740    /// report at all.
8741    fn resolve(&self, item: &Value) -> Result<Option<Resolved>, SourceError> {
8742        let resolved = self.resolve_unremembered(item)?;
8743        if let Some(resolved) = &resolved {
8744            self.resolved_cache()?
8745                .insert(resolved.id.clone(), resolved.clone());
8746        }
8747        Ok(resolved)
8748    }
8749
8750    /// [`Self::resolve`], without remembering the item it resolves: what reading a token off a
8751    /// write's own response needs, which says nothing this process should answer a later read
8752    /// with.
8753    fn resolve_unremembered(&self, item: &Value) -> Result<Option<Resolved>, SourceError> {
8754        let content = item.get("content").ok_or_else(|| SourceError::Malformed {
8755            message: "GitHub project item is missing content".into(),
8756        })?;
8757        if content.is_null() {
8758            return Ok(None);
8759        }
8760        let content_kind = match required_str(content, "__typename")? {
8761            "Issue" => ContentKind::Issue,
8762            "DraftIssue" => ContentKind::DraftIssue,
8763            _ => return Ok(None),
8764        };
8765        let field_values = item
8766            .get("fieldValues")
8767            .ok_or_else(|| SourceError::Malformed {
8768                message: "GitHub project item is missing fieldValues".into(),
8769            })?;
8770        complete_connection(field_values, "project item field values", NESTED_PAGE_SIZE)?;
8771        let nodes = field_values
8772            .get("nodes")
8773            .and_then(Value::as_array)
8774            .ok_or_else(|| SourceError::Malformed {
8775                message: "GitHub project item fieldValues.nodes is not an array".into(),
8776            })?;
8777        if let Some(labels) = content.get("labels") {
8778            complete_connection(labels, "content labels", NESTED_PAGE_SIZE)?;
8779        }
8780        let raw_body = optional_str(content, "body")?.map(str::to_owned);
8781        let (body, slot) = self.visible(raw_body.clone())?;
8782        let parent = optional_str(content.get("parent").unwrap_or(&Value::Null), "id")?
8783            .map(|id| NativeId(id.to_owned()));
8784        // A draft has no sub-issues to summarise, and GitHub's schema gives it no field
8785        // to read one from; it is a task, and never a project.
8786        let sub_issues = match content_kind {
8787            ContentKind::Issue => sub_issue_total(content)?,
8788            ContentKind::DraftIssue => 0,
8789        };
8790        let content_id = required_str(content, "id")?;
8791        let marked = ItemKind::from_metadata(&slot).map_err(|message| SourceError::Malformed {
8792            message: format!("GitHub issue {content_id}: {message}"),
8793        })?;
8794        let raw_title = required_str(content, "title")?;
8795        // Read as children, a sub-issue is filed under no project and nothing is a project: the
8796        // GitHub parent is the parent relation instead.
8797        let (kind, parent, issue_parent) = match self.sub_issues {
8798            SubIssues::Project => (
8799                BoardKind::of(raw_title, parent.is_some(), sub_issues, marked),
8800                parent,
8801                None,
8802            ),
8803            SubIssues::Parent => (
8804                if raw_title.starts_with(DESIGN_TITLE_PREFIX) {
8805                    BoardKind::Document
8806                } else {
8807                    BoardKind::Work(ItemKind::Task)
8808                },
8809                None,
8810                parent,
8811            ),
8812        };
8813        // The title a person wrote, which for a document is the one without the prefix —
8814        // the same way `content` above is the body without this source's metadata slot.
8815        let title = match kind {
8816            BoardKind::Document => raw_title[DESIGN_TITLE_PREFIX.len()..].to_owned(),
8817            BoardKind::Work(_) => raw_title.to_owned(),
8818        };
8819        let own_repository = content
8820            .pointer("/repository/nameWithOwner")
8821            .and_then(Value::as_str)
8822            .map(|origin| Repository::try_from(format!("{}/{origin}", RepositoryTarget::HOST)))
8823            .transpose()
8824            .map_err(|message| SourceError::Malformed { message })?;
8825        let repositories = if slot.contains_key(Repository::METADATA_KEY) {
8826            Repository::from_metadata(&slot)
8827                .map_err(|message| SourceError::Malformed { message })?
8828        } else {
8829            own_repository.clone().into_iter().collect()
8830        };
8831        let classification = Classification::from_metadata(&slot)
8832            .map_err(|message| SourceError::Malformed { message })?;
8833        let id = NativeId(content_id.to_owned());
8834        // Read only for a task, because only a task has either list: a project or a
8835        // document holding one of these keys holds nothing this source reports, and the
8836        // keys are left out of its caller-visible metadata all the same.
8837        let (delivers, delivered_by) = if kind == BoardKind::Work(ItemKind::Task) {
8838            let listed = |key: &str| {
8839                TaskRef::from_value(key, &id, Some(&self.name), slot.get(key))
8840                    .map_err(|message| SourceError::Malformed { message })
8841            };
8842            (
8843                listed(TaskRef::DELIVERS_KEY)?,
8844                listed(TaskRef::DELIVERED_BY_KEY)?,
8845            )
8846        } else {
8847            (Vec::new(), Vec::new())
8848        };
8849        let (option, closed, reason) = Self::status_parts(nodes, content)?;
8850        let priority = self.held_priority(nodes)?;
8851        let item_labels = labels(content)?;
8852        // Present when the item was reached through its own issue, whose board entry
8853        // names the board; a read of the board's own items has the board already. An
8854        // empty id names nothing a field write could address, so it is read as absent and
8855        // the write goes back to reading the board.
8856        let board_id = item
8857            .pointer("/project/id")
8858            .and_then(Value::as_str)
8859            .filter(|id| !id.is_empty());
8860        let resolved = Resolved {
8861            item_id: required_str(item, "id")?.to_owned(),
8862            id,
8863            content_kind,
8864            kind,
8865            title,
8866            body: body.filter(|value| !value.is_empty()),
8867            raw_body,
8868            status: self
8869                .statuses
8870                .status(kind.status_kind(), option, closed, reason),
8871            option: option.map(str::to_owned),
8872            priority,
8873            closed,
8874            reason: closed.then(|| reason.map(str::to_owned)).flatten(),
8875            delivers,
8876            delivered_by,
8877            labels: item_labels.clone(),
8878            parent,
8879            issue_parent,
8880            origin: text_field(nodes, ORIGIN_FIELD)?.filter(|value| !value.is_empty()),
8881            projected: self.held_projections(nodes)?,
8882            number: match content_kind {
8883                ContentKind::Issue => Some(issue_number(content)?),
8884                // A draft is filed in no repository, so nothing ever numbered it:
8885                // `DraftIssue` declares no `number` at all, exactly as it declares no
8886                // `subIssuesSummary` the branch above reads.
8887                ContentKind::DraftIssue => None,
8888            },
8889            url: optional_str(content, "url")?.map(str::to_owned),
8890            created_at: optional_time(content, "createdAt")?,
8891            updated_at: optional_time(content, "updatedAt")?,
8892            item_updated_at: optional_time(item, "updatedAt")?,
8893            comment_count: content
8894                .pointer("/commentCount/totalCount")
8895                .and_then(Value::as_u64),
8896            relationship_events: content
8897                .pointer("/relationshipEvents/totalCount")
8898                .and_then(Value::as_u64),
8899            // The issue node is stamped wherever it was read; a board item a read of the issue
8900            // put together from its memberships is not.
8901            served_at: match optional_time(content, SERVED_AT)? {
8902                Some(served) => Some(served),
8903                None => optional_time(item, SERVED_AT)?,
8904            },
8905            // Both connections were read to their end above — one reporting a further page is
8906            // refused — so these are every field value and every label the item holds. A
8907            // response that did not select the labels at all says nothing of them, and gives
8908            // no facets.
8909            facets: content.get("labels").is_some().then(|| {
8910                change_token::Facets::new(kind.facet(), facet_fields(nodes), &item_labels).digest()
8911            }),
8912            own_repository,
8913            repositories,
8914            classification,
8915            slot,
8916            board_id: board_id.map(str::to_owned),
8917            fields: field_definitions(nodes),
8918            board_fields: Self::carried_board_fields(content, board_id)?,
8919            blocked_by: carried_blocked_by(content)?,
8920            assignees: if self.assignees {
8921                Some(assignees::assignee_logins(content)?)
8922            } else {
8923                None
8924            },
8925        };
8926        Ok(Some(resolved))
8927    }
8928
8929    /// The field definitions of the board `board_id` names — the project this issue's own
8930    /// board item is on — off the `boards` page a read of an issue by its own id carries, or
8931    /// `None` when the read carried none, carried no entry for that board, or the board item
8932    /// named no board, which a write then answers by reading the board's fields itself.
8933    ///
8934    /// Matched by the board's node id and never by its number alone: a project number is
8935    /// unique only within its owner, so another owner's board numbered alike can sit on the
8936    /// same page, and its field and option ids address nothing on this one.
8937    fn carried_board_fields(
8938        content: &Value,
8939        board_id: Option<&str>,
8940    ) -> Result<Option<Value>, SourceError> {
8941        let (Some(nodes), Some(board_id)) = (
8942            content.pointer("/boards/nodes").and_then(Value::as_array),
8943            board_id,
8944        ) else {
8945            return Ok(None);
8946        };
8947        let Some(board) = nodes.iter().find_map(|node| {
8948            let project = node.get("project")?;
8949            (project.get("id").and_then(Value::as_str) == Some(board_id)).then_some(project)
8950        }) else {
8951            return Ok(None);
8952        };
8953        let Some(fields) = board.get("fields").filter(|fields| !fields.is_null()) else {
8954            return Ok(None);
8955        };
8956        complete_connection(fields, "board fields", NESTED_PAGE_SIZE)?;
8957        Ok(Some(fields.clone()))
8958    }
8959
8960    /// What one board item's `Priority` field says, through this instance's mapping.
8961    ///
8962    /// An instance with no mapping holds no priority, so every item reads as `none` whatever
8963    /// its board holds. With one, no value is `none`, a mapped option is its level, and an
8964    /// option the mapping does not name is kept as itself — never read as a level or as
8965    /// `none` — for a read of the task to report by name.
8966    fn held_priority(&self, field_values: &[Value]) -> Result<HeldPriority, SourceError> {
8967        let Some(mapping) = &self.priorities else {
8968            return Ok(HeldPriority::Read(Priority::None));
8969        };
8970        // A value of the field that names no option — a text field someone called `Priority` —
8971        // is malformed rather than `none`: reading it as no priority would let the next copy
8972        // clear one a person set.
8973        let Some(option) = field_values
8974            .iter()
8975            .find(|value| {
8976                value.pointer("/field/name").and_then(Value::as_str) == Some(PRIORITY_FIELD)
8977            })
8978            .map(|value| required_str(value, "name"))
8979            .transpose()?
8980        else {
8981            return Ok(HeldPriority::Read(Priority::None));
8982        };
8983        Ok(mapping.priority_of(option).map_or_else(
8984            || HeldPriority::Unmapped(option.to_owned()),
8985            HeldPriority::Read,
8986        ))
8987    }
8988
8989    /// What each projected metadata field holds for one board item, by field name — every text
8990    /// value GitHub answers, an empty one included.
8991    fn held_projections(
8992        &self,
8993        field_values: &[Value],
8994    ) -> Result<BTreeMap<String, String>, SourceError> {
8995        let mut held = BTreeMap::new();
8996        for projection in &self.metadata_fields {
8997            if let Some(text) = text_field(field_values, &projection.field)? {
8998                held.insert(projection.field.to_string(), text);
8999            }
9000        }
9001        Ok(held)
9002    }
9003
9004    /// What one board item's status is read from: its `Status` option, whether its issue
9005    /// is closed, and the reason it was closed with. [`BoardStatuses::status`] turns the
9006    /// three into the status it reports.
9007    fn status_parts<'a>(
9008        field_values: &'a [Value],
9009        content: &'a Value,
9010    ) -> Result<(Option<&'a str>, bool, Option<&'a str>), SourceError> {
9011        let option = field_values
9012            .iter()
9013            .find(|value| value.pointer("/field/name").and_then(Value::as_str) == Some("Status"))
9014            .map(|value| required_str(value, "name"))
9015            .transpose()?;
9016        let closed = optional_str(content, "state")? == Some("CLOSED");
9017        Ok((option, closed, optional_str(content, "stateReason")?))
9018    }
9019
9020    /// The board Status option this write selects, or the refusal that says why not.
9021    ///
9022    /// The mapped option is required for both open and terminal targets. A terminal write
9023    /// validates it before changing either representation, so it can never fall back to
9024    /// closing an issue whose board cannot display the matching status.
9025    ///
9026    /// Answers the field's id, the option's id, and the option's name as the board spells
9027    /// it — which is the name a read of the item reports once it sits there.
9028    fn column_for(
9029        &self,
9030        fields: &Value,
9031        kind: ItemKind,
9032        category: StatusCategory,
9033        target: &StatusTarget,
9034    ) -> Result<Option<(String, String, String)>, SourceError> {
9035        let Some(wanted) = target.option() else {
9036            return Ok(None);
9037        };
9038        let missing = |detail: &str| SourceError::Refused {
9039            message: format!(
9040                "{} status {} of source {} needs the board Status option {wanted:?}, and \
9041                 {detail}; next: add that option to the board, which `onetaskgraph sources \
9042                 fields {} --apply` does, or point status_mapping.{}.{} of this source at one \
9043                 it has",
9044                kind.marker(),
9045                category_name(category),
9046                self.name,
9047                self.name,
9048                category_name(category),
9049                kind.marker()
9050            ),
9051        };
9052        let Some(field) = Board::field(fields, "Status")? else {
9053            return Err(missing("this board has no Status field"));
9054        };
9055        if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
9056            return Err(missing(
9057                "this board's Status field is not a single-select field",
9058            ));
9059        }
9060        let option = field
9061            .get("options")
9062            .and_then(Value::as_array)
9063            .and_then(|options| {
9064                options.iter().find(|option| {
9065                    option
9066                        .get("name")
9067                        .and_then(Value::as_str)
9068                        .is_some_and(|name| name.eq_ignore_ascii_case(wanted))
9069                })
9070            });
9071        match option {
9072            None => Err(missing("this board does not have it")),
9073            Some(option) => Ok(Some((
9074                required_str(field, "id")?.to_owned(),
9075                required_str(option, "id")?.to_owned(),
9076                required_str(option, "name")?.to_owned(),
9077            ))),
9078        }
9079    }
9080
9081    /// The refusal a status that closes an issue is answered with over a board draft.
9082    fn closes_a_draft(&self, category: StatusCategory) -> SourceError {
9083        SourceError::Refused {
9084            message: format!(
9085                "status {} of source {} closes the item's issue, and GitHub draft items have \
9086                 no open or closed state",
9087                category_name(category),
9088                self.name
9089            ),
9090        }
9091    }
9092
9093    /// What a status write to one item needs of the board: the board's id and the
9094    /// definition of its `Status` field, read off the item when the item says both.
9095    ///
9096    /// The same reasoning as [`Self::fields_for`]: a node read of the item names its board,
9097    /// and its `Status` value carries that field's definition, options and all. An item that
9098    /// does not say — no board id, or no `Status` value to read the field off — takes them
9099    /// from [`Self::board_fields`], which reads no item.
9100    async fn status_board(&self, item: &Resolved) -> Result<BoardFields, SourceError> {
9101        if let Some(board) = item.carried_board() {
9102            return Ok(board);
9103        }
9104        if item.defines("Status")
9105            && let Some(board_id) = item.named_board()
9106        {
9107            return Ok(BoardFields {
9108                id: board_id,
9109                fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
9110            });
9111        }
9112        self.board_fields().await
9113    }
9114
9115    /// Set one task's or one project's status and nothing else; see
9116    /// [`TaskSource::set_task_status`] and [`TaskSource::set_project_status`].
9117    async fn set_status(
9118        &self,
9119        id: &NativeId,
9120        kind: ItemKind,
9121        category: StatusCategory,
9122    ) -> Result<Option<Status>, SourceError> {
9123        // Refused before anything is read, in the words a write of the same status is.
9124        let target = self.resolved_target(kind, category)?;
9125        // An item read by issue reference carries only what this write needs, so what it
9126        // becomes is never remembered for a later read to be answered from.
9127        let held = self.take_held(id)?;
9128        let by_reference = held.is_some();
9129        let bound = match held {
9130            Some(item) => Some(item),
9131            None => self.bound_item(id).await?,
9132        };
9133        let Some(mut item) = bound.filter(|item| item.kind == BoardKind::Work(kind)) else {
9134            return Ok(None);
9135        };
9136        let board = self.status_board(&item).await?;
9137        let (field, option, name) = self
9138            .column_for(&board.fields, kind, category, &target)?
9139            .ok_or_else(|| SourceError::Malformed {
9140                message: format!(
9141                    "status {} of source {} names no board Status option",
9142                    category_name(category),
9143                    self.name
9144                ),
9145            })?;
9146        // The card already shows the target's option. That alone is not the status: an open
9147        // issue under a terminal card reads that card's category while GitHub, its
9148        // notifications and a search of open issues all say the work is not finished, and a
9149        // closed issue under an open column's card reads as its closure. So the write is no
9150        // write only where the issue's open or closed state is also what the target needs —
9151        // closed, for a reason reading this category, for a terminal one; open for a column.
9152        let at_option = item
9153            .option
9154            .as_deref()
9155            .is_some_and(|held| held.eq_ignore_ascii_case(&name));
9156        let issue = item.content_kind == ContentKind::Issue;
9157        let state_holds = match &target {
9158            StatusTarget::Terminal(_, _) => {
9159                !issue || (item.closed && closed_category(item.reason.as_deref()) == category)
9160            }
9161            _ => !issue || !item.closed,
9162        };
9163        if item.status.category == category && at_option && state_holds {
9164            return Ok(Some(item.status));
9165        }
9166        match &target {
9167            StatusTarget::Terminal(_, reason) => {
9168                if item.content_kind == ContentKind::DraftIssue {
9169                    return Err(self.closes_a_draft(category));
9170                }
9171                // The option first, so a refused selection leaves an open issue open rather
9172                // than closed behind a card that still reads open. A card already showing it
9173                // is sent nothing: only the issue's state is out of line.
9174                if !at_option {
9175                    self.set_item_field(
9176                        board.id.as_str(),
9177                        &item.item_id,
9178                        &field,
9179                        json!({"singleSelectOptionId": option}),
9180                    )
9181                    .await?;
9182                }
9183                // An issue already closed in a way that reads as this category keeps its state
9184                // and its reason: only its card was out of line, and closing it again would
9185                // overwrite a reason — a duplicate's — that says more than this write does.
9186                let already = item.closed && item.status.category == category;
9187                if !already {
9188                    self.update_content(
9189                        ContentKind::Issue,
9190                        &item.id,
9191                        json!({"stateInput": state_input(Some(&target))}),
9192                    )
9193                    .await?;
9194                }
9195                let reason = if already {
9196                    item.reason.clone()
9197                } else {
9198                    Some(reason.reason().to_owned())
9199                };
9200                item.closed = true;
9201                item.status = self
9202                    .statuses
9203                    .status(kind, Some(&name), true, reason.as_deref());
9204                item.option = Some(name);
9205                item.reason = reason;
9206            }
9207            StatusTarget::Column(_) => {
9208                // An option is what an open item's status is, so a closed issue is reopened
9209                // first — sitting closed in the column, it would read back as closed. A draft has
9210                // no state to reopen.
9211                if item.content_kind == ContentKind::Issue && item.closed {
9212                    self.update_content(
9213                        ContentKind::Issue,
9214                        &item.id,
9215                        json!({"stateInput": state_input(Some(&target))}),
9216                    )
9217                    .await?;
9218                    item.closed = false;
9219                }
9220                if !at_option {
9221                    self.set_item_field(
9222                        board.id.as_str(),
9223                        &item.item_id,
9224                        &field,
9225                        json!({"singleSelectOptionId": option}),
9226                    )
9227                    .await?;
9228                }
9229                item.status = self.statuses.status(kind, Some(&name), false, None);
9230                item.option = Some(name);
9231            }
9232            StatusTarget::Disabled(_) => {
9233                unreachable!("resolved_target refused a disabled status")
9234            }
9235        }
9236        let status = item.status.clone();
9237        if !by_reference {
9238            self.remember_written(item, false)?;
9239        }
9240        Ok(Some(status))
9241    }
9242
9243    /// Replace one task's `delivered_by` and nothing else; see
9244    /// [`TaskSource::set_delivered_by`].
9245    ///
9246    /// One update of the body, which differs from the body GitHub holds only inside the
9247    /// metadata slot — see [`with_slot`]. A body that would not change is not sent at all.
9248    async fn replace_delivered_by(
9249        &self,
9250        id: &NativeId,
9251        delivered_by: &[TaskRef],
9252    ) -> Result<Option<()>, SourceError> {
9253        let entries = TaskRef::listed(
9254            TaskRef::DELIVERED_BY_KEY,
9255            id,
9256            Some(&self.name),
9257            delivered_by.to_vec(),
9258        )
9259        .map_err(|message| SourceError::Refused { message })?;
9260        let Some(mut item) = self
9261            .bound_item(id)
9262            .await?
9263            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9264        else {
9265            return Ok(None);
9266        };
9267        let mut slot = item.slot.clone();
9268        set_task_list(&mut slot, TaskRef::DELIVERED_BY_KEY, &entries);
9269        self.write_slot(&mut item, &slot).await?;
9270        item.delivered_by = entries;
9271        self.remember_written(item, false)?;
9272        Ok(Some(()))
9273    }
9274
9275    /// Set one caller key of the metadata slot of one issue of `kind`, and nothing else;
9276    /// see [`TaskSource::set_task_metadata`].
9277    ///
9278    /// `None` when this board holds no item by that id, or holds one of another kind. The
9279    /// answer is the item as this source now reads it, so what a caller is told the key
9280    /// holds is what the slot holds.
9281    ///
9282    /// A key already holding the value is answered without a write, compared as JSON rather
9283    /// than as the body's bytes: a slot a person spelled with other whitespace would
9284    /// otherwise be re-encoded, which is a write that changes nothing the caller asked for.
9285    async fn set_slot_key(
9286        &self,
9287        id: &NativeId,
9288        kind: BoardKind,
9289        key: &MetadataKey,
9290        value: &Value,
9291    ) -> Result<Option<Resolved>, SourceError> {
9292        let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
9293            return Ok(None);
9294        };
9295        if item.slot.get(key.as_str()) == Some(value) {
9296            return Ok(Some(item));
9297        }
9298        let mut slot = item.slot.clone();
9299        slot.insert(key.as_str().to_owned(), value.clone());
9300        // A key a board text field projects moves that field first, so the body — the value's
9301        // one authoritative home — is written last, as every write of an existing item is.
9302        if self
9303            .metadata_fields
9304            .iter()
9305            .any(|projection| &*projection.key == key.as_str())
9306        {
9307            let board = self.projection_board(&item).await?;
9308            let (writes, projected) = self.projection_writes(
9309                &board.fields,
9310                Some(&item.projected),
9311                &slot,
9312                Some(&[key.as_str()]),
9313            )?;
9314            let (mut values, mut clears) = (Vec::new(), Vec::new());
9315            for write in &writes {
9316                write.join(&mut values, &mut clears);
9317            }
9318            self.set_item_fields(board.id.as_str(), &item.item_id, &values, &clears)
9319                .await?;
9320            item.projected = projected;
9321        }
9322        self.write_slot(&mut item, &slot).await?;
9323        self.remember_written(item.clone(), false)?;
9324        Ok(Some(item))
9325    }
9326
9327    /// What a projection write to `item` needs of the board, read off the item when it says
9328    /// enough, as [`Self::fields_for`] reads it.
9329    async fn projection_board(&self, item: &Resolved) -> Result<BoardFields, SourceError> {
9330        if let Some(board) = item.carried_board() {
9331            return Ok(board);
9332        }
9333        if let Some(board_id) = item.named_board()
9334            && self
9335                .metadata_fields
9336                .iter()
9337                .all(|projection| item.defines(&projection.field))
9338        {
9339            return Ok(BoardFields {
9340                id: board_id,
9341                fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
9342            });
9343        }
9344        self.board_fields().await
9345    }
9346
9347    /// Put `slot` in one item's metadata slot with a single update of its body, and bring
9348    /// `item` up to what that write left.
9349    ///
9350    /// The body sent differs from the body GitHub holds only inside the slot — see
9351    /// [`with_slot`] — and a body that would not change is not sent at all. It goes through
9352    /// the mutation the item's content takes, so a board draft's body is written with
9353    /// `updateProjectV2DraftIssue` exactly as an issue's is with `updateIssue`.
9354    async fn write_slot(
9355        &self,
9356        item: &mut Resolved,
9357        slot: &BTreeMap<String, Value>,
9358    ) -> Result<(), SourceError> {
9359        let held = item.raw_body.clone().unwrap_or_default();
9360        let body = with_slot(&held, slot)?;
9361        if body != held {
9362            self.update_content(item.content_kind, &item.id, json!({"body": body}))
9363                .await?;
9364        }
9365        let (visible, slot) = self.visible(Some(body.clone()))?;
9366        item.body = visible.filter(|value| !value.is_empty());
9367        item.raw_body = Some(body);
9368        item.slot = slot;
9369        Ok(())
9370    }
9371
9372    /// This instance's target for a category written to an item of `kind`, refusing one
9373    /// that kind has no option for — before anything is read or written.
9374    ///
9375    /// Nothing here mutates the board's option set to make room for a status. GitHub
9376    /// documents `UpdateProjectV2FieldInput.singleSelectOptions` as *"provided values
9377    /// overwrite existing options"*, so no addition is additive and a mistake destroys the
9378    /// field and every item's status.
9379    fn resolved_target(
9380        &self,
9381        kind: ItemKind,
9382        category: StatusCategory,
9383    ) -> Result<StatusTarget, SourceError> {
9384        let target = self.statuses.target(kind, category).clone();
9385        let StatusTarget::Disabled(why) = target else {
9386            return Ok(target);
9387        };
9388        let refusal = why.refusal(&self.name, category, kind);
9389        // Why there is no shipped default, which is the question a person meeting this
9390        // refusal on a source that never mentioned the category asks.
9391        let shipped_none = match category {
9392            StatusCategory::Draft => Some(
9393                "draft has no shipped default because GitHub draft issues cannot have \
9394                 sub-issues, and this source stores a project's tasks as its issue's sub-issues",
9395            ),
9396            StatusCategory::Unknown => Some(
9397                "unknown has no shipped default because this board keeps no open-ended status \
9398                 word: every word classified unknown is written to the one board Status option \
9399                 status_mapping.unknown names",
9400            ),
9401            _ => None,
9402        };
9403        Err(match (refusal, shipped_none, why) {
9404            (SourceError::Refused { message }, Some(note), UnmappedStatus::Unconfigured) => {
9405                SourceError::Refused {
9406                    message: format!("{message}; {note}"),
9407                }
9408            }
9409            (refusal, _, _) => refusal,
9410        })
9411    }
9412
9413    /// What writing `priority` does to one item's `Priority` field on this board, or the
9414    /// refusal naming what the board lacks.
9415    ///
9416    /// `none` is no value, so it clears the field — and asks nothing of an item that holds
9417    /// none already, or of an item not created yet. Every other priority selects the option
9418    /// the mapping names, matched case-insensitively; a board with no `Priority` field, or
9419    /// without that option, is refused rather than given one: reads and writes never create
9420    /// a field or an option.
9421    fn priority_write(
9422        &self,
9423        fields: &Value,
9424        existing: Option<&Resolved>,
9425        priority: Priority,
9426    ) -> Result<Option<PriorityWrite>, SourceError> {
9427        let Some(mapping) = &self.priorities else {
9428            return Err(self.holds_no_priority());
9429        };
9430        let Some(wanted) = mapping.option(priority) else {
9431            if !existing.is_some_and(Resolved::holds_priority) {
9432                return Ok(None);
9433            }
9434            let field =
9435                Board::field(fields, PRIORITY_FIELD)?.ok_or_else(|| SourceError::Malformed {
9436                    message: format!(
9437                        "an item holding a {PRIORITY_FIELD} value was read without that field"
9438                    ),
9439                })?;
9440            return Ok(Some(PriorityWrite::Clear {
9441                field: required_str(field, "id")?.to_owned(),
9442            }));
9443        };
9444        let missing = |detail: &str| SourceError::Refused {
9445            message: format!(
9446                "priority {priority} of source {} needs the board {PRIORITY_FIELD} option \
9447                 {wanted:?}, and {detail}; run `onetaskgraph sources fields {} --apply` to add \
9448                 it, or point priority_mapping.{priority} of this source at an option the board \
9449                 has",
9450                self.name, self.name
9451            ),
9452        };
9453        let Some(field) = Board::field(fields, PRIORITY_FIELD)? else {
9454            return Err(missing(&format!(
9455                "this board has no {PRIORITY_FIELD} field"
9456            )));
9457        };
9458        if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
9459            return Err(missing(&format!(
9460                "this board's {PRIORITY_FIELD} field is not a single-select field"
9461            )));
9462        }
9463        // An options list that is absent or not a list is an answer this source cannot read,
9464        // not a board lacking the option: `sources fields --apply` is no remedy for it.
9465        let option = field
9466            .get("options")
9467            .and_then(Value::as_array)
9468            .ok_or_else(|| SourceError::Malformed {
9469                message: format!("GitHub {PRIORITY_FIELD} field options is not an array"),
9470            })?
9471            .iter()
9472            .find(|option| {
9473                option
9474                    .get("name")
9475                    .and_then(Value::as_str)
9476                    .is_some_and(|name| name.eq_ignore_ascii_case(wanted))
9477            })
9478            .ok_or_else(|| missing("this board does not have it"))?;
9479        Ok(Some(PriorityWrite::Select {
9480            field: required_str(field, "id")?.to_owned(),
9481            option: required_str(option, "id")?.to_owned(),
9482        }))
9483    }
9484
9485    /// What writing `metadata` does to each projected text field of one item, and what those
9486    /// fields hold after it — or the refusal, before anything is sent.
9487    ///
9488    /// `held` is what the item's fields hold now, `None` for an item not created yet. `keys`
9489    /// narrows the work to the entries projecting one of those metadata keys, for a write that
9490    /// touches only them; `None` is every entry. A string the field already holds, and nothing
9491    /// for a field holding nothing, sends nothing. A value no text field can hold is refused,
9492    /// and so is a board without the field, or with a field of that name that is not a text
9493    /// field: reads and writes never create a field.
9494    fn projection_writes(
9495        &self,
9496        fields: &Value,
9497        held: Option<&BTreeMap<String, String>>,
9498        metadata: &BTreeMap<String, Value>,
9499        keys: Option<&[&str]>,
9500    ) -> Result<(Vec<ProjectionWrite>, BTreeMap<String, String>), SourceError> {
9501        let mut projected = held.cloned().unwrap_or_default();
9502        let mut writes = Vec::new();
9503        for projection in self
9504            .metadata_fields
9505            .iter()
9506            .filter(|projection| keys.is_none_or(|keys| keys.contains(&&*projection.key)))
9507        {
9508            let wanted = projection.projected(metadata, &self.name)?;
9509            let field = self.projection_field(fields, projection)?;
9510            let holding = projected.get(&*projection.field);
9511            match wanted {
9512                Projected::Text(text) if holding != Some(&text) => {
9513                    writes.push(ProjectionWrite::Set {
9514                        field,
9515                        text: text.clone(),
9516                    });
9517                    projected.insert(projection.field.to_string(), text);
9518                }
9519                Projected::Nothing if holding.is_some() => {
9520                    writes.push(ProjectionWrite::Clear { field });
9521                    projected.remove(&*projection.field);
9522                }
9523                Projected::Text(_) | Projected::Nothing => {}
9524            }
9525        }
9526        Ok((writes, projected))
9527    }
9528
9529    /// The id of the board text field one projection writes, or the refusal naming what the
9530    /// board has instead.
9531    fn projection_field(
9532        &self,
9533        fields: &Value,
9534        projection: &MetadataField,
9535    ) -> Result<String, SourceError> {
9536        let refuse = |detail: String| SourceError::Refused {
9537            message: format!(
9538                "source {} projects metadata key {:?} onto the board text field {:?}, and \
9539                 {detail}; next: run `onetaskgraph sources fields {} --apply` to create it as a \
9540                 text field, or name another field in metadata_fields",
9541                self.name, &*projection.key, &*projection.field, self.name
9542            ),
9543        };
9544        let Some(field) = Board::field(fields, &projection.field)? else {
9545            return Err(refuse("this board has no field of that name".to_owned()));
9546        };
9547        let typename = optional_str(field, "__typename")?.unwrap_or("field of another type");
9548        let data_type = optional_str(field, "dataType")?;
9549        if typename != "ProjectV2Field" || data_type != Some("TEXT") {
9550            return Err(refuse(format!(
9551                "this board's field of that name is not a text field (it is a {}), so it is \
9552                 left as it is; rename or remove that field first",
9553                data_type.unwrap_or(typename)
9554            )));
9555        }
9556        Ok(required_str(field, "id")?.to_owned())
9557    }
9558
9559    /// Apply one priority write to one board item.
9560    async fn write_priority(
9561        &self,
9562        board_id: &str,
9563        item_id: &str,
9564        write: &PriorityWrite,
9565    ) -> Result<(), SourceError> {
9566        match write {
9567            PriorityWrite::Select { field, option } => {
9568                self.set_item_field(
9569                    board_id,
9570                    item_id,
9571                    field,
9572                    json!({"singleSelectOptionId": option}),
9573                )
9574                .await
9575            }
9576            PriorityWrite::Clear { field } => {
9577                let data = self
9578                    .graphql(
9579                        graphql::CLEAR_FIELD,
9580                        json!({"input":{"projectId":board_id,"itemId":item_id,"fieldId":field},
9581                            "readPriority":false,"priorityName":PRIORITY_FIELD}),
9582                    )
9583                    .await?;
9584                let returned = data
9585                    .pointer("/clearProjectV2ItemFieldValue/projectV2Item")
9586                    .ok_or_else(|| SourceError::Malformed {
9587                        message: "GitHub field clear returned no project item".into(),
9588                    })?;
9589                if required_str(returned, "id")? != item_id {
9590                    return Err(SourceError::Malformed {
9591                        message: "GitHub field clear returned the wrong project item".into(),
9592                    });
9593                }
9594                Ok(())
9595            }
9596        }
9597    }
9598
9599    /// The refusal a priority is answered with by an instance configured with no
9600    /// `priority_mapping`, which holds none.
9601    fn holds_no_priority(&self) -> SourceError {
9602        SourceError::Refused {
9603            message: format!(
9604                "source {} holds no task priority: its configuration sets no priority_mapping; \
9605                 next: set priority_mapping on this source, then run `onetaskgraph sources \
9606                 fields {} --apply` to set its board up",
9607                self.name, self.name
9608            ),
9609        }
9610    }
9611
9612    /// Set one task's priority and nothing else; see [`TaskSource::set_task_priority`].
9613    ///
9614    /// One field write — a select, or a clear for `none` — and no title, body, label, state
9615    /// or `Status` request. Clearing a priority an item does not hold sends nothing.
9616    async fn set_priority(
9617        &self,
9618        id: &NativeId,
9619        priority: Priority,
9620    ) -> Result<Option<Priority>, SourceError> {
9621        if self.priorities.is_none() {
9622            return Err(self.holds_no_priority());
9623        }
9624        let Some(mut item) = self
9625            .bound_item(id)
9626            .await?
9627            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9628        else {
9629            return Ok(None);
9630        };
9631        if priority == Priority::None && !item.holds_priority() {
9632            return Ok(Some(priority));
9633        }
9634        // The item's own read carries the field's definition whenever it holds a value of
9635        // it, which a clear always does; a select onto an item holding none reads the board.
9636        let board = match (item.carried_board(), item.named_board()) {
9637            (Some(board), _) => board,
9638            (None, Some(id)) if item.defines(PRIORITY_FIELD) => BoardFields {
9639                id,
9640                fields: json!({"nodes": item.fields.clone(), "pageInfo": {"hasNextPage": false}}),
9641            },
9642            _ => self.board_fields().await?,
9643        };
9644        let Some(write) = self.priority_write(&board.fields, Some(&item), priority)? else {
9645            return Ok(Some(priority));
9646        };
9647        let (document, root, input) = match write {
9648            PriorityWrite::Select { field, option } => (
9649                graphql::UPDATE_FIELD,
9650                "updateProjectV2ItemFieldValue",
9651                json!({"projectId":board.id.as_str(),"itemId":item.item_id,"fieldId":field,"value":{"singleSelectOptionId":option}}),
9652            ),
9653            PriorityWrite::Clear { field } => (
9654                graphql::CLEAR_FIELD,
9655                "clearProjectV2ItemFieldValue",
9656                json!({"projectId":board.id.as_str(),"itemId":item.item_id,"fieldId":field}),
9657            ),
9658        };
9659        let data = self
9660            .graphql(
9661                document,
9662                json!({"input":input,"readPriority":true,"priorityName":PRIORITY_FIELD}),
9663            )
9664            .await?;
9665        let returned = data
9666            .get(root)
9667            .and_then(|value| value.get("projectV2Item"))
9668            .ok_or_else(|| SourceError::Malformed {
9669                message: "GitHub priority write returned no project item".into(),
9670            })?;
9671        if required_str(returned, "id")? != item.item_id {
9672            return Err(SourceError::Malformed {
9673                message: "GitHub priority write returned the wrong project item".into(),
9674            });
9675        }
9676        let value = returned
9677            .get("fieldValueByName")
9678            .ok_or_else(|| SourceError::Malformed {
9679                message: "GitHub priority write returned no priority read-back".into(),
9680            })?;
9681        if !value.is_null()
9682            && value.pointer("/field/name").and_then(Value::as_str) != Some(PRIORITY_FIELD)
9683        {
9684            return Err(SourceError::Malformed {
9685                message: "GitHub priority read-back is not a Priority field value".into(),
9686            });
9687        }
9688        let values = if value.is_null() {
9689            Vec::new()
9690        } else {
9691            vec![value.clone()]
9692        };
9693        item.priority = self.held_priority(&values)?;
9694        let answer = item.task()?.priority;
9695        self.remember_written(item, false)?;
9696        Ok(Some(answer))
9697    }
9698
9699    /// Replace one task's visible body and nothing else; see
9700    /// [`TaskSource::set_task_content`].
9701    ///
9702    /// One update of the body, which differs from the body GitHub holds only outside the
9703    /// metadata slot — the slot is kept byte for byte, so every caller key and every list
9704    /// this source keeps there reads back as it was. A body that would not change is not
9705    /// sent at all.
9706    async fn replace_content(
9707        &self,
9708        id: &NativeId,
9709        content: &str,
9710    ) -> Result<Option<()>, SourceError> {
9711        let Some(mut item) = self
9712            .bound_item(id)
9713            .await?
9714            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9715        else {
9716            return Ok(None);
9717        };
9718        let held = item.raw_body.clone().unwrap_or_default();
9719        // The task's `## Links` section, re-rendered from the links it holds, stays with it.
9720        let content = &onetaskgraph_plugin_api::relinked(content, item.body.as_deref(), &item.slot);
9721        let body = with_content(&held, &self.marked(content))?;
9722        // Checked before anything is sent: content ending in what this source reads as its own
9723        // metadata slot would read back as metadata rather than as the content it was.
9724        let (visible, slot) = self.visible(Some(body.clone()))?;
9725        if visible.as_deref().unwrap_or_default() != content || slot != item.slot {
9726            return Err(SourceError::Refused {
9727                message: format!(
9728                    "this content ends in what source {} reads as its own metadata slot \
9729                     ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
9730                     as content; next: remove that trailing block from the content",
9731                    self.name
9732                ),
9733            });
9734        }
9735        if body != held {
9736            self.update_content(item.content_kind, &item.id, json!({"body": body}))
9737                .await?;
9738        }
9739        item.body = visible.filter(|value| !value.is_empty());
9740        item.raw_body = Some(body);
9741        item.slot = slot;
9742        self.remember_written(item, false)?;
9743        Ok(Some(()))
9744    }
9745
9746    /// Apply one targeted update to one task; see [`TaskSource::update_task`].
9747    ///
9748    /// One read of the item — which carries the board's field definitions and the issue's
9749    /// `blockedBy`, so neither is read again — and then only what differs from it: the
9750    /// `Status` option and the `Priority` field together in one request, the `blockedBy`
9751    /// additions and removals the named edges differ by, and last one `updateIssue` carrying
9752    /// the title, the body — visible content and metadata slot together — and a state change.
9753    /// So an update naming any of title, body, metadata, status and priority is one read and
9754    /// at most two writes. The body goes last so that a write refused part-way leaves it, and
9755    /// the metadata in it, as it stood. A terminal status selects its option and then closes,
9756    /// as a whole write does; an open one selects its option and then reopens. The origin
9757    /// field is never written: an update is of an item that already exists, whose origin is
9758    /// what it is.
9759    ///
9760    /// The task answered is the item as those writes left it, built from the read and what was
9761    /// sent rather than read again — the same record a later read in this run answers from.
9762    ///
9763    /// Its `version` is the one the task holds after the writes: the change token the last
9764    /// mutation's own response spells — each sent as the twin selecting the whole issue, at
9765    /// the price of the plain document — or, where that mutation shows no whole issue (several
9766    /// board fields written together, or `blockedBy` alone), the token one read right after
9767    /// the writes spells. Never the token the item was read at before them. Against GitHub
9768    /// itself that token has not settled yet (`change_token::SETTLED`), so a read gives none
9769    /// until it has, and a write held to it before then is refused rather than let through;
9770    /// once settled, a read gives exactly this token unless the task changed again.
9771    async fn targeted_update(
9772        &self,
9773        id: &NativeId,
9774        update: &TaskUpdate,
9775    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
9776        Box::pin(SPELLING.scope(
9777            std::ptr::from_ref(self) as usize,
9778            self.composed_update(id, update),
9779        ))
9780        .await
9781    }
9782
9783    /// [`Self::targeted_update`], inside the scope that has its mutations answer whole.
9784    async fn composed_update(
9785        &self,
9786        id: &NativeId,
9787        update: &TaskUpdate,
9788    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
9789        // Everything this source can refuse without reading the item is refused first, in the
9790        // words a whole write of the same fields is refused with.
9791        update.consistent()?;
9792        // A duplicate close is the `cancelled` it implies where it names no status.
9793        let closing = update.duplicate_of.as_ref().map(|_| TaskUpdate {
9794            status: update.effective_status(),
9795            ..update.clone()
9796        });
9797        let update = closing.as_ref().unwrap_or(update);
9798        if update.assignees.is_some() && !self.assignees {
9799            return Err(onetaskgraph_plugin_api::unwritable_field(KIND, "assignees"));
9800        }
9801        if update
9802            .title
9803            .as_deref()
9804            .is_some_and(|title| title.starts_with(DESIGN_TITLE_PREFIX))
9805        {
9806            return Err(SourceError::Refused {
9807                message: format!(
9808                    "the title of this task begins {DESIGN_TITLE_PREFIX:?}, which is how source {} \
9809                     spells a document, so it would read back as one rather than as a task; \
9810                     retitle it",
9811                    self.name
9812                ),
9813            });
9814        }
9815        if let Some(delivers) = &update.delivers {
9816            TaskRef::listed(
9817                TaskRef::DELIVERS_KEY,
9818                id,
9819                Some(&self.name),
9820                delivers.clone(),
9821            )
9822            .map_err(|message| SourceError::Refused { message })?;
9823        }
9824        if self.priorities.is_none()
9825            && update
9826                .priority
9827                .is_some_and(|priority| priority != Priority::None)
9828        {
9829            return Err(self.holds_no_priority());
9830        }
9831        let target = update
9832            .status
9833            .as_ref()
9834            .map(|status| self.resolved_target(ItemKind::Task, status.category))
9835            .transpose()?;
9836        let Some(mut item) = self
9837            .bound_item(id)
9838            .await?
9839            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9840        else {
9841            return Ok(None);
9842        };
9843        let before = item.task()?;
9844        // The issue a duplicate close names as its survivor, refused naming both before anything
9845        // is written when it is not an issue of this board's own.
9846        let survivor = match &update.duplicate_of {
9847            Some(survivor) => Some(self.duplicate_survivor(id, &item, survivor).await?),
9848            None => None,
9849        };
9850        // The people it is to be assigned to, by node id, when they are not exactly whom it
9851        // holds: looked up — unless this process already has — and refused for a login GitHub
9852        // does not know, before anything is sent.
9853        let assignee_ids = match &update.assignees {
9854            Some(people)
9855                if item
9856                    .assignees
9857                    .as_deref()
9858                    .is_none_or(|held| !assignees::same_people(held, people)) =>
9859            {
9860                if item.content_kind == ContentKind::DraftIssue {
9861                    return Err(self.assigns_a_draft());
9862                }
9863                self.resolve_people(people).await?;
9864                Some(self.people_ids(people, &item.written_name())?)
9865            }
9866            _ => None,
9867        };
9868
9869        let mut status_move = None;
9870        if let (Some(status), Some(target)) = (&update.status, target) {
9871            let board = self.status_board(&item).await?;
9872            let (field, option, name) = self
9873                .column_for(&board.fields, ItemKind::Task, status.category, &target)?
9874                .ok_or_else(|| SourceError::Malformed {
9875                    message: format!(
9876                        "status {} of source {} names no board Status option",
9877                        category_name(status.category),
9878                        self.name
9879                    ),
9880                })?;
9881            let terminal = matches!(target, StatusTarget::Terminal(_, _));
9882            if terminal && item.content_kind == ContentKind::DraftIssue {
9883                return Err(self.closes_a_draft(status.category));
9884            }
9885            // A duplicate close lands closed as `DUPLICATE`, which reads `cancelled` as not
9886            // planned does; an issue already closed as one is not closed again.
9887            let reason = match (&target, &survivor) {
9888                (StatusTarget::Terminal(_, _), Some(_)) => Some(DUPLICATE_REASON),
9889                (StatusTarget::Terminal(_, reason), None) => Some(reason.reason()),
9890                _ => None,
9891            };
9892            let landed = self
9893                .statuses
9894                .status(ItemKind::Task, Some(&name), terminal, reason);
9895            let option_moves = item
9896                .option
9897                .as_deref()
9898                .is_none_or(|held| !held.eq_ignore_ascii_case(&name));
9899            let state_moves = item.content_kind == ContentKind::Issue
9900                && (item.closed != terminal
9901                    || (terminal && item.status != landed)
9902                    || (survivor.is_some() && item.reason.as_deref() != Some(DUPLICATE_REASON)));
9903            if let Some(moves) = Moves::of(option_moves, state_moves) {
9904                status_move = Some(StatusMove {
9905                    board: board.id,
9906                    field,
9907                    option,
9908                    name,
9909                    target,
9910                    landed,
9911                    moves,
9912                });
9913            }
9914        }
9915
9916        let mut priority_move = None;
9917        if let Some(priority) = update.priority
9918            && self.priorities.is_some()
9919            && item.priority != HeldPriority::Read(priority)
9920        {
9921            let board = match (item.carried_board(), item.named_board()) {
9922                (Some(board), _) => board,
9923                (None, Some(board)) if item.defines(PRIORITY_FIELD) => BoardFields {
9924                    id: board,
9925                    fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
9926                },
9927                _ => self.board_fields().await?,
9928            };
9929            if let Some(write) = self.priority_write(&board.fields, Some(&item), priority)? {
9930                priority_move = Some((board.id, write, priority));
9931            }
9932        }
9933
9934        // The metadata keys this update names that a board text field projects, and what
9935        // that does to those fields — refused, as a whole write refuses it, before anything
9936        // is sent.
9937        let touched: Vec<&str> = update
9938            .metadata_set
9939            .keys()
9940            .chain(update.metadata_remove.iter())
9941            .map(MetadataKey::as_str)
9942            .collect();
9943        let mut projection_move = None;
9944        if self
9945            .metadata_fields
9946            .iter()
9947            .any(|projection| touched.contains(&&*projection.key))
9948        {
9949            let mut metadata = item.slot.clone();
9950            for (key, value) in &update.metadata_set {
9951                metadata.insert(key.as_str().to_owned(), value.clone());
9952            }
9953            for key in &update.metadata_remove {
9954                metadata.remove(key.as_str());
9955            }
9956            let board = self.projection_board(&item).await?;
9957            let (writes, projected) = self.projection_writes(
9958                &board.fields,
9959                Some(&item.projected),
9960                &metadata,
9961                Some(&touched),
9962            )?;
9963            projection_move = Some((board.id, writes, projected));
9964        }
9965
9966        // Resolved before the body is composed, because a far end `blockedBy` cannot name is
9967        // recorded in the slot, and the slot travels in the one body update below.
9968        let edges = match &update.depends_on {
9969            Some(edges) => Some(
9970                self.partition_edges(
9971                    BoardKind::Work(ItemKind::Task),
9972                    item.content_kind,
9973                    item.blocked_by.as_deref(),
9974                    edges,
9975                )
9976                .await?,
9977            ),
9978            None => None,
9979        };
9980
9981        // A record primed from what a producer wrote holds no body anybody read, so an update
9982        // changing the body reads it first: by the `Status` write's own answer when the update
9983        // moves the option — the mutation answering with the issue whole — and otherwise by
9984        // reading the issue. The body is then composed against what GitHub holds now.
9985        let mut option_selected = false;
9986        // The mark stays until a read lands, so an update that writes no body, or one whose
9987        // read fails, leaves the next update of it to read the body too.
9988        if (update.content.is_some()
9989            || !update.metadata_set.is_empty()
9990            || !update.metadata_remove.is_empty()
9991            || update.delivers.is_some()
9992            || update.repositories.is_some()
9993            || edges.is_some())
9994            && self.is_unread(id)
9995        {
9996            let live = match status_move.as_ref().filter(|moving| moving.moves.option()) {
9997                Some(moving) => {
9998                    option_selected = true;
9999                    Some(
10000                        self.select_reading_body(
10001                            moving.board.as_str(),
10002                            &item.item_id,
10003                            &moving.field,
10004                            &moving.option,
10005                        )
10006                        .await?,
10007                    )
10008                }
10009                None => {
10010                    self.forget(id)?;
10011                    let Some(read) = self.item_by_id(id).await? else {
10012                        return Ok(None);
10013                    };
10014                    read.raw_body
10015                }
10016            };
10017            let (visible, read_slot) = self.visible(live.clone())?;
10018            self.mark_read(id);
10019            item.raw_body = live;
10020            item.body = visible;
10021            item.slot = read_slot;
10022        }
10023
10024        let mut slot = item.slot.clone();
10025        for (key, value) in &update.metadata_set {
10026            slot.insert(key.as_str().to_owned(), value.clone());
10027        }
10028        for key in &update.metadata_remove {
10029            slot.remove(key.as_str());
10030        }
10031        if let Some(delivers) = &update.delivers {
10032            set_task_list(&mut slot, TaskRef::DELIVERS_KEY, delivers);
10033        }
10034        // The list a whole write records, by the same rule: none when it is exactly the issue's
10035        // own repository, or empty with no issue repository to derive, and otherwise the list.
10036        if let Some(repositories) = &update.repositories {
10037            let derivable = item
10038                .own_repository
10039                .as_ref()
10040                .map_or(repositories.is_empty(), |own| {
10041                    repositories.as_slice() == std::slice::from_ref(own)
10042                });
10043            if derivable {
10044                slot.remove(Repository::METADATA_KEY);
10045            } else {
10046                slot.insert(
10047                    Repository::METADATA_KEY.to_owned(),
10048                    Value::Array(
10049                        repositories
10050                            .iter()
10051                            .map(|repository| Value::String(repository.as_str().to_owned()))
10052                            .collect(),
10053                    ),
10054                );
10055            }
10056        }
10057        if let Some((_, recorded)) = &edges {
10058            record_edges(&mut slot, recorded);
10059        }
10060        let held = item.raw_body.clone().unwrap_or_default();
10061        // A content write keeps the task's `## Links` section, re-rendered from the links the
10062        // slot holds once written.
10063        let relinked = update
10064            .content
10065            .as_deref()
10066            .map(|content| onetaskgraph_plugin_api::relinked(content, item.body.as_deref(), &slot));
10067        let content = match &relinked {
10068            Some(content) => with_content(&held, &self.marked(content))?,
10069            None => held.clone(),
10070        };
10071        // A slot holding what it held is kept byte for byte, compared as JSON rather than as
10072        // the body's bytes, as a metadata write compares it: a slot a person spelled with
10073        // other whitespace would otherwise be re-encoded, which is a write nobody asked for.
10074        let body = if slot == item.slot {
10075            content
10076        } else {
10077            with_slot(&content, &slot)?
10078        };
10079        // Checked before anything is sent, as a content write checks it: content ending in
10080        // what this source reads as its own slot would read back as metadata.
10081        let (visible, read) = self.visible(Some(body.clone()))?;
10082        let wanted = relinked.as_deref().or(item.body.as_deref());
10083        if visible.as_deref().unwrap_or_default() != wanted.unwrap_or_default() || read != slot {
10084            return Err(SourceError::Refused {
10085                message: format!(
10086                    "this content ends in what source {} reads as its own metadata slot \
10087                     ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
10088                     as content; next: remove that trailing block from the content",
10089                    self.name
10090                ),
10091            });
10092        }
10093        let recorded_moves =
10094            slot.get(DependencyEdge::RECORDED_KEY) != item.slot.get(DependencyEdge::RECORDED_KEY);
10095
10096        // One `updateIssue` carries all three, because every mutation spends the secondary
10097        // limiter and the title, body and state are one mutation's inputs.
10098        let mut fields = serde_json::Map::new();
10099        if let Some(title) = update.title.as_ref().filter(|title| **title != item.title) {
10100            fields.insert("title".to_owned(), json!(title));
10101        }
10102        if body != held {
10103            fields.insert("body".to_owned(), json!(body));
10104        }
10105        // A duplicate's closure is `closeIssue`'s, sent after this update: `stateInput` names
10106        // no survivor.
10107        if let Some(moving) = status_move
10108            .as_ref()
10109            .filter(|moving| moving.moves.state() && survivor.is_none())
10110        {
10111            fields.insert("stateInput".to_owned(), state_input(Some(&moving.target)));
10112        }
10113        let closes_as_duplicate = status_move
10114            .as_ref()
10115            .is_some_and(|moving| moving.moves.state())
10116            && survivor.is_some();
10117        // The assignees ride the same mutation: replacing whoever the issue holds, in the one
10118        // `updateIssue` this update already ends with — or as the one it sends for them alone.
10119        if let Some(ids) = &assignee_ids {
10120            fields.insert("assigneeIds".to_owned(), json!(ids));
10121        }
10122        // **The body is written last, and that is the guarantee a refusal part-way keeps.**
10123        // GitHub runs no two requests as one, and runs one document's mutation fields in order
10124        // without undoing an earlier field when a later one fails — so a body written before a
10125        // board field the board then refused would be left changed. Written after every other
10126        // write has landed, a refusal anywhere leaves the item's body, and every metadata key
10127        // it carries, exactly as they stood. So the `Status` option and the `Priority` field go
10128        // first, together in one request — a terminal option selected before the issue
10129        // closes, as a whole write does — then the `blockedBy` difference, then the body.
10130        let mut board_writes: Vec<(&BoardId, (String, Value))> = Vec::new();
10131        let mut clears: Vec<(&BoardId, &str)> = Vec::new();
10132        if let Some(moving) = status_move
10133            .as_ref()
10134            .filter(|moving| moving.moves.option() && !option_selected)
10135        {
10136            board_writes.push((
10137                &moving.board,
10138                (
10139                    moving.field.clone(),
10140                    json!({"singleSelectOptionId": moving.option}),
10141                ),
10142            ));
10143        }
10144        match &priority_move {
10145            Some((board, PriorityWrite::Select { field, option }, _)) => board_writes.push((
10146                board,
10147                (field.clone(), json!({"singleSelectOptionId": option})),
10148            )),
10149            Some((board, PriorityWrite::Clear { field }, _)) => clears.push((board, field)),
10150            None => {}
10151        }
10152        if let Some((board, writes, _)) = &projection_move {
10153            for write in writes {
10154                let (mut values, mut cleared) = (Vec::new(), Vec::new());
10155                write.join(&mut values, &mut cleared);
10156                board_writes.extend(values.into_iter().map(|value| (board, value)));
10157                clears.extend(cleared.into_iter().map(|field| (board, field)));
10158            }
10159        }
10160        let mut boards: Vec<&BoardId> = board_writes.iter().map(|(board, _)| *board).collect();
10161        boards.extend(clears.iter().map(|(board, _)| *board));
10162        boards.dedup_by(|one, other| one.as_str() == other.as_str());
10163        for board in boards {
10164            let writes = board_writes
10165                .iter()
10166                .filter(|(on, _)| on.as_str() == board.as_str())
10167                .map(|(_, write)| write.clone())
10168                .collect::<Vec<_>>();
10169            let cleared = clears
10170                .iter()
10171                .filter(|(on, _)| on.as_str() == board.as_str())
10172                .map(|(_, field)| *field)
10173                .collect::<Vec<_>>();
10174            self.set_item_fields(board.as_str(), &item.item_id, &writes, &cleared)
10175                .await?;
10176        }
10177        // Whether anything is sent: what the version answered has to come after.
10178        let sends = option_selected
10179            || !board_writes.is_empty()
10180            || !clears.is_empty()
10181            || !fields.is_empty()
10182            || closes_as_duplicate;
10183        let mut blocked_by_moved = false;
10184        if let Some((native, _)) = &edges
10185            && item.content_kind == ContentKind::Issue
10186        {
10187            blocked_by_moved = self
10188                .reconcile_blocked_by(
10189                    &item.id,
10190                    native,
10191                    Issue::Existing(item.blocked_by.as_deref()),
10192                )
10193                .await?;
10194        }
10195        if !fields.is_empty() {
10196            self.update_content(item.content_kind, &item.id, Value::Object(fields))
10197                .await?;
10198        }
10199        // Last, the duplicate's closure, with the survivor GitHub links it to: the card already
10200        // shows the `cancelled` option, so a refusal here leaves an open issue at a terminal
10201        // card, which the next write of the same status closes.
10202        if let (true, Some(survivor)) = (closes_as_duplicate, &survivor) {
10203            self.graphql(
10204                graphql::CLOSE_ISSUE,
10205                json!({"input":{"issueId":item.id.0,"stateReason":DUPLICATE_REASON,
10206                                "duplicateIssueId":survivor.0}}),
10207            )
10208            .await?;
10209        }
10210
10211        // The `blockedBy` this item was read with is what the write just changed, so it is no
10212        // answer any more: a later write in this command would reconcile against it — re-adding
10213        // what it kept and never removing what it dropped — and a forward-edge read would
10214        // answer with it. Left unknown, each asks GitHub instead.
10215        if blocked_by_moved {
10216            item.blocked_by = None;
10217        }
10218        if let Some(title) = &update.title {
10219            item.title.clone_from(title);
10220        }
10221        item.body = visible.filter(|value| !value.is_empty());
10222        item.raw_body = (!body.is_empty() || item.raw_body.is_some()).then_some(body);
10223        item.slot = slot;
10224        if let Some(delivers) = &update.delivers {
10225            item.delivers.clone_from(delivers);
10226        }
10227        if let Some(repositories) = &update.repositories {
10228            item.repositories.clone_from(repositories);
10229        }
10230        if let Some(moving) = status_move {
10231            item.closed = matches!(moving.target, StatusTarget::Terminal(_, _))
10232                && item.content_kind == ContentKind::Issue;
10233            if moving.moves.state() {
10234                item.reason = match &moving.target {
10235                    StatusTarget::Terminal(_, _) if survivor.is_some() => {
10236                        Some(DUPLICATE_REASON.to_owned())
10237                    }
10238                    StatusTarget::Terminal(_, reason) => Some(reason.reason().to_owned()),
10239                    _ => None,
10240                };
10241            }
10242            item.status = moving.landed;
10243            item.option = Some(moving.name);
10244        }
10245        if let Some((_, _, priority)) = priority_move {
10246            item.priority = HeldPriority::Read(priority);
10247        }
10248        if let Some((_, _, projected)) = projection_move {
10249            item.projected = projected;
10250        }
10251        // Only a write that assigned anyone moves whom the item holds, and they are who GitHub
10252        // says they are; one naming the people it already holds leaves its read as it was.
10253        if let (Some(people), Some(_)) = (&update.assignees, &assignee_ids) {
10254            item.assignees = Some(self.spelled(people));
10255        }
10256        let mut task = item.task()?;
10257        let mut written = update.changed(&before, &task);
10258        if blocked_by_moved || recorded_moves {
10259            written.insert(UpdatedField::DependsOn);
10260        }
10261        if closes_as_duplicate {
10262            written.insert(UpdatedField::DuplicateOf);
10263        }
10264        if sends || blocked_by_moved {
10265            // The token the item was read at is not the one it holds now. A batch of updates
10266            // holding this one's writes back reads every task it wrote once they are sent.
10267            task.version = if self.holding_writes_of(id) {
10268                None
10269            } else {
10270                self.version_after_write(id).await
10271            };
10272        }
10273        self.remember_written(item, false)?;
10274        Ok(Some(TaskUpdateOutcome {
10275            task,
10276            written,
10277            delivers_before: before.delivers,
10278        }))
10279    }
10280
10281    /// The issue `survivor` names, the one a duplicate close of `id` links GitHub's closure to:
10282    /// refused, naming both, when it is not an issue of this board's own source — a task of
10283    /// another source, a board draft, an item this board does not hold — or is `id` itself.
10284    async fn duplicate_survivor(
10285        &self,
10286        id: &NativeId,
10287        item: &Resolved,
10288        survivor: &TaskRef,
10289    ) -> Result<NativeId, SourceError> {
10290        let refused = |why: String| SourceError::Refused {
10291            message: format!(
10292                "{} cannot be closed as a duplicate of {survivor}: {why}; next: name an issue of \
10293                 source {} as the survivor",
10294                TaskRef::qualified(&self.name, id),
10295                self.name
10296            ),
10297        };
10298        let (source, native) = survivor.parts(self.name.as_str());
10299        if source != self.name.as_str() {
10300            return Err(refused(format!(
10301                "it is not a GitHub issue of source {}, which GitHub links a duplicate to",
10302                self.name
10303            )));
10304        }
10305        let native = NativeId(native.to_owned());
10306        if native == *id || native == item.id {
10307            return Err(refused("a task cannot be a duplicate of itself".to_owned()));
10308        }
10309        match self.bound_item(&native).await? {
10310            Some(held) if held.content_kind == ContentKind::Issue => Ok(held.id),
10311            Some(_) => Err(refused(
10312                "it is a board draft, which is no issue GitHub can link a duplicate to".to_owned(),
10313            )),
10314            None => Err(refused(format!("source {} holds no such issue", self.name))),
10315        }
10316    }
10317
10318    /// The change token the task `id` holds after the writes a targeted update just sent: the
10319    /// one the last mutation's own response showed, or, where none showed the whole issue, the
10320    /// one a read made now spells. `None` when that read cannot say — never the token the
10321    /// task was read at before the writes.
10322    async fn version_after_write(&self, id: &NativeId) -> Option<String> {
10323        // A response that showed the issue whole answers, a token or none: a read made now
10324        // would read the same parts.
10325        if let Some(answered) = self.written_answer(id) {
10326            return answered;
10327        }
10328        // An item this command created is answered from its own record, not read.
10329        if self.created().ok()?.iter().any(|own| own.id == *id) {
10330            return None;
10331        }
10332        let read = self.item_by_id(id).await.ok()??;
10333        let token = read.written_version()?;
10334        self.remember_written_token(&read, token.clone());
10335        Some(token)
10336    }
10337
10338    /// Replace one issue's visible body and its [`MetadataKey::TEMPLATE_KEY`] slot entry
10339    /// together, and nothing else; see [`TaskSource::set_task_rendering`].
10340    ///
10341    /// One update of the body: the content outside the slot, and inside it that one entry,
10342    /// every other entry kept as it was. This source keeps no template answers — an issue has
10343    /// no room beside itself that is not its body, and answers written there would duplicate
10344    /// what the content already says and count against GitHub's body limit — so `answers`
10345    /// reaches nothing here. A body that would not change is not sent at all.
10346    async fn replace_rendering(
10347        &self,
10348        id: &NativeId,
10349        kind: BoardKind,
10350        content: &str,
10351        provenance: &Value,
10352        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
10353    ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
10354        let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
10355            return Ok(None);
10356        };
10357        let held = item.raw_body.clone().unwrap_or_default();
10358        let mut slot = item.slot.clone();
10359        slot.insert(MetadataKey::TEMPLATE_KEY.to_owned(), provenance.clone());
10360        let rewritten;
10361        let content = if let Some(assets) = assets {
10362            let uploads = self
10363                .upload_assets(item.own_repository.as_ref(), assets)
10364                .await?;
10365            rewritten =
10366                onetaskgraph_plugin_api::serve_asset_references(content, &mut slot, &uploads);
10367            rewritten.as_str()
10368        } else {
10369            content
10370        };
10371        let relinked = onetaskgraph_plugin_api::relinked(content, item.body.as_deref(), &slot);
10372        let content = relinked.as_str();
10373        let body = with_slot(&with_content(&held, &self.marked(content))?, &slot)?;
10374        // Checked before anything is sent, as a content write checks it.
10375        let (visible, read) = self.visible(Some(body.clone()))?;
10376        if visible.as_deref().unwrap_or_default() != content || read != slot {
10377            return Err(SourceError::Refused {
10378                message: format!(
10379                    "this content ends in what source {} reads as its own metadata slot \
10380                     ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
10381                     as content; next: remove that trailing block from the template",
10382                    self.name
10383                ),
10384            });
10385        }
10386        if body != held {
10387            self.update_content(item.content_kind, &item.id, json!({"body": body}))
10388                .await?;
10389        }
10390        item.body = visible.filter(|value| !value.is_empty());
10391        item.raw_body = Some(body);
10392        // The content as a read answers it: without the `## Links` section of a linked task.
10393        let answered = onetaskgraph_plugin_api::read_content(Some(content.to_owned()), &read);
10394        item.slot = read;
10395        self.remember_written(item, false)?;
10396        Ok(Some(onetaskgraph_plugin_api::AssetsWritten {
10397            id: id.clone(),
10398            content: answered,
10399        }))
10400    }
10401
10402    async fn set_item_field(
10403        &self,
10404        board_id: &str,
10405        item_id: &str,
10406        field_id: &str,
10407        value: Value,
10408    ) -> Result<(), SourceError> {
10409        let data = self
10410            .graphql(
10411                graphql::UPDATE_FIELD,
10412                json!({"input":{
10413                    "projectId":board_id,"itemId":item_id,"fieldId":field_id,"value":value
10414                },"readPriority":false,"priorityName":PRIORITY_FIELD}),
10415            )
10416            .await?;
10417        field_update_item(&data, item_id).map(|_| ())
10418    }
10419
10420    /// GitHub accepts one value per field mutation; aliases combine those mutations in
10421    /// one request — writes in the order given, then clears. A lone write is
10422    /// [`graphql::UPDATE_FIELD`] and a lone clear [`graphql::CLEAR_FIELD`]; more than one
10423    /// request's slots hold go in further requests of the same document, in order. Every
10424    /// returned item id is checked, including optional aliases.
10425    async fn set_item_fields(
10426        &self,
10427        board: &str,
10428        item: &str,
10429        fields: &[(String, Value)],
10430        clears: &[&str],
10431    ) -> Result<(), SourceError> {
10432        if !(fields.is_empty() && clears.is_empty())
10433            && self.hold_fields(board, item, fields, clears)?
10434        {
10435            return Ok(());
10436        }
10437        match (fields, clears) {
10438            ([], []) => return Ok(()),
10439            ([(field, value)], []) => {
10440                return self.set_item_field(board, item, field, value.clone()).await;
10441            }
10442            ([], [field]) => {
10443                return self
10444                    .write_priority(
10445                        board,
10446                        item,
10447                        &PriorityWrite::Clear {
10448                            field: (*field).to_owned(),
10449                        },
10450                    )
10451                    .await;
10452            }
10453            _ => {}
10454        }
10455        // Any field of the request stands in for an input a slot leaves out, which GitHub
10456        // still requires to be well formed although it never runs it.
10457        let filler = fields
10458            .first()
10459            .map_or_else(|| clears[0], |(field, _)| field.as_str());
10460        let mut writes = fields.iter();
10461        let mut cleared = clears.iter();
10462        loop {
10463            let batch: Vec<&(String, Value)> =
10464                writes.by_ref().take(FIELD_WRITE_SLOTS.len()).collect();
10465            let batch_clears: Vec<&&str> = cleared.by_ref().take(FIELD_CLEAR_SLOTS.len()).collect();
10466            if batch.is_empty() && batch_clears.is_empty() {
10467                return Ok(());
10468            }
10469            let mut variables = serde_json::Map::new();
10470            for (index, slot) in FIELD_WRITE_SLOTS.iter().enumerate() {
10471                let input = match batch.get(index) {
10472                    Some((field, value)) => {
10473                        json!({"projectId":board,"itemId":item,"fieldId":field,"value":value})
10474                    }
10475                    None => json!({"projectId":board,"itemId":item,"fieldId":filler,
10476                                   "value":{"text":""}}),
10477                };
10478                variables.insert(slot.variable.to_owned(), input);
10479                variables.insert(slot.include.to_owned(), json!(index < batch.len()));
10480            }
10481            for (index, slot) in FIELD_CLEAR_SLOTS.iter().enumerate() {
10482                let field = batch_clears.get(index).map_or(filler, |field| **field);
10483                variables.insert(
10484                    slot.variable.to_owned(),
10485                    json!({"projectId":board,"itemId":item,"fieldId":field}),
10486                );
10487                variables.insert(slot.include.to_owned(), json!(index < batch_clears.len()));
10488            }
10489            let data = self
10490                .graphql(graphql::UPDATE_FIELDS, Value::Object(variables))
10491                .await?;
10492            let sent = FIELD_WRITE_SLOTS[..batch.len()]
10493                .iter()
10494                .chain(&FIELD_CLEAR_SLOTS[..batch_clears.len()]);
10495            for slot in sent {
10496                let alias = slot.alias;
10497                let returned = data
10498                    .get(alias)
10499                    .and_then(|value| value.get("projectV2Item"))
10500                    .ok_or_else(|| SourceError::Malformed {
10501                        message: format!("GitHub field update {alias} returned no project item"),
10502                    })?;
10503                if required_str(returned, "id")? != item {
10504                    return Err(SourceError::Malformed {
10505                        message: format!(
10506                            "GitHub field update {alias} returned the wrong project item"
10507                        ),
10508                    });
10509                }
10510            }
10511        }
10512    }
10513
10514    async fn native_dependency_ids(&self, id: &NativeId) -> Result<Vec<String>, SourceError> {
10515        let mut after: Option<String> = None;
10516        let mut ids = Vec::new();
10517        loop {
10518            let data = self
10519                .graphql(
10520                    graphql::ISSUE_DEPENDENCIES,
10521                    json!({"id":id.0,"first":MAX_PAGE_SIZE,"after":after}),
10522                )
10523                .await?;
10524            let connection =
10525                data.pointer("/node/blockedBy")
10526                    .ok_or_else(|| SourceError::Malformed {
10527                        message: "GitHub dependency response has no blockedBy connection".into(),
10528                    })?;
10529            ids.extend(
10530                connection
10531                    .get("nodes")
10532                    .and_then(Value::as_array)
10533                    .ok_or_else(|| SourceError::Malformed {
10534                        message: "GitHub dependency response nodes is not an array".into(),
10535                    })?
10536                    .iter()
10537                    .map(|value| required_str(value, "id").map(str::to_owned))
10538                    .collect::<Result<Vec<_>, _>>()?,
10539            );
10540            let next = next_cursor(connection)?;
10541            if let Some(next) = &next {
10542                validate_cursor_progress(after.as_deref(), &next.0)?;
10543            }
10544            after = next.map(|cursor| cursor.0);
10545            if after.is_none() {
10546                return Ok(ids);
10547            }
10548        }
10549    }
10550
10551    async fn dependencies(
10552        &self,
10553        id: &NativeId,
10554        near_kind: ItemKind,
10555        direction: Direction,
10556        page: &PageRequest,
10557    ) -> Result<Page<DependencyEdge>, SourceError> {
10558        validate_page(page)?;
10559        let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
10560        let cursor = page.cursor.as_ref().map(|c| c.0.as_str());
10561        let recorded = recorded_offset(cursor, direction)?;
10562        // What this issue is blocked by, when a read of it by its own id in this command
10563        // already carried the whole connection — a copy reads the item it writes before it
10564        // reads its edges — and the page asked for is the whole of it, or the recorded tail
10565        // after it. Answered from that read, in the shape the dependency read answers in;
10566        // anything else is asked of GitHub.
10567        let carried = match direction {
10568            Direction::DependsOn => self
10569                .resolved_cache()?
10570                .get(id)
10571                .filter(|item| item.content_kind == ContentKind::Issue)
10572                .and_then(|item| Some((item.blocked_by.clone()?, item.raw_body.clone()))),
10573            Direction::DependedOnBy => None,
10574        }
10575        .filter(|(nodes, _)| recorded.is_some() || (cursor.is_none() && nodes.len() <= limit));
10576        // Asked for even in the recorded phase, whose page reads nothing from the
10577        // connection: `__typename` is what says whether this item has a native
10578        // relationship at all, and that is what decides which far ends the reserved key is
10579        // allowed to hold.
10580        let data = match carried {
10581            Some((nodes, body)) => json!({"node":{"__typename":"Issue","body":body,
10582                "blockedBy":{"nodes":nodes,"pageInfo":{"hasNextPage":false,"endCursor":null}}}}),
10583            None => {
10584                let after = if recorded.is_some() { None } else { cursor };
10585                let first = page.limit.min(MAX_PAGE_SIZE);
10586                match direction {
10587                    Direction::DependsOn => {
10588                        self.graphql(
10589                            graphql::ISSUE_DEPENDS_ON,
10590                            json!({"id":id.0,"first":first,"after":after,"owner":self.owner,
10591                                   "number":self.project_number,
10592                                   "boardItems":BOARD_ITEMS_PAGE_SIZE}),
10593                        )
10594                        .await?
10595                    }
10596                    Direction::DependedOnBy => {
10597                        self.graphql(
10598                            graphql::ISSUE_DEPENDED_ON_BY,
10599                            json!({"id":id.0,"first":first,"after":after}),
10600                        )
10601                        .await?
10602                    }
10603                }
10604            }
10605        };
10606        let draft_slot = draft_slot(&data, id, self.project_number)?;
10607        let node =
10608            data.get("node")
10609                .filter(|v| !v.is_null())
10610                .ok_or_else(|| SourceError::Refused {
10611                    message: format!(
10612                        "GitHub item {} was not found or does not support dependencies",
10613                        id.0
10614                    ),
10615                })?;
10616        let connection_name = match direction {
10617            Direction::DependsOn => "blockedBy",
10618            Direction::DependedOnBy => "blocking",
10619        };
10620        // A draft has neither `blockedBy` nor `blocking`, so nothing it depends on can be
10621        // named natively and the reserved key may hold any far end. An issue's connections
10622        // hold issues, and this source reads them at the near item's own level.
10623        let natively_names = (required_str(node, "__typename")? == "Issue").then_some(near_kind);
10624        if let Some(offset) = recorded {
10625            return Ok(recorded_page(
10626                self.recorded_edges(
10627                    id,
10628                    near_kind,
10629                    direction,
10630                    natively_names,
10631                    node,
10632                    draft_slot.as_ref(),
10633                )
10634                .await?,
10635                offset,
10636                limit,
10637            ));
10638        }
10639        if natively_names.is_none() {
10640            return Ok(recorded_page(
10641                self.recorded_edges(
10642                    id,
10643                    near_kind,
10644                    direction,
10645                    natively_names,
10646                    node,
10647                    draft_slot.as_ref(),
10648                )
10649                .await?,
10650                0,
10651                limit,
10652            ));
10653        }
10654        let connection = node
10655            .get(connection_name)
10656            .ok_or_else(|| SourceError::Malformed {
10657                message: "GitHub dependency response is missing its connection".into(),
10658            })?;
10659        let nodes = connection
10660            .get("nodes")
10661            .and_then(Value::as_array)
10662            .ok_or_else(|| SourceError::Malformed {
10663                message: "GitHub dependency response nodes is not an array".into(),
10664            })?;
10665        // `from` depends on `to`, always. GitHub spells the same relationship from either
10666        // end — `blockedBy` lists what this item waits on, `blocking` lists what waits on
10667        // it — so the near item is `from` in one direction and `to` in the other.
10668        let items = nodes
10669            .iter()
10670            .map(|value| {
10671                let related = NativeId(required_str(value, "id")?.into());
10672                let related_kind = related_kind(value, self.sub_issues)?;
10673                let (from, to) = match direction {
10674                    Direction::DependsOn => (
10675                        DependencyEndpoint::from_native(id.clone(), near_kind),
10676                        DependencyEndpoint::from_native(related, related_kind),
10677                    ),
10678                    Direction::DependedOnBy => (
10679                        DependencyEndpoint::from_native(related, related_kind),
10680                        DependencyEndpoint::from_native(id.clone(), near_kind),
10681                    ),
10682                };
10683                Ok(DependencyEdge {
10684                    from,
10685                    to,
10686                    kind: DependencyKind::Blocks,
10687                })
10688            })
10689            .collect::<Result<Vec<_>, SourceError>>()?;
10690        let mut next = next_cursor(connection)?;
10691        if let Some(next) = &next {
10692            validate_cursor_progress(cursor, &next.0)?;
10693        }
10694        // The recorded far ends ride on the last page of `blockedBy`, whose answer carried the
10695        // body they are recorded in, as far as the page has room — so they cost no request of
10696        // their own — and only what does not fit is resumed by a cursor.
10697        let mut items = items;
10698        if next.is_none() {
10699            let recorded = self
10700                .recorded_edges(
10701                    id,
10702                    near_kind,
10703                    direction,
10704                    natively_names,
10705                    node,
10706                    draft_slot.as_ref(),
10707                )
10708                .await?;
10709            let room = limit.saturating_sub(items.len());
10710            let total = recorded.len();
10711            items.extend(recorded.into_iter().take(room));
10712            if total > room {
10713                next = Some(Cursor(format!("{RECORDED_CURSOR}{room}")));
10714            }
10715        }
10716        Ok(Page { items, next })
10717    }
10718
10719    /// The edges this item records under [`DependencyEdge::RECORDED_KEY`], which is where
10720    /// a far end in another source has to live: no GitHub issue relationship can name one.
10721    ///
10722    /// Only forwards. The reverse of a recorded edge is derived from the far end, and this
10723    /// source never writes one down.
10724    ///
10725    /// The metadata lives in the item's own body slot, and `node` is the dependency read's
10726    /// own answer, which carries an issue's body — so an issue's recorded edges cost no
10727    /// request beyond the read already made, and reading the board for them would be a
10728    /// walk of every item for one field of one. A draft has no body in that answer, because
10729    /// a draft is not an issue, so a draft's are read off its own read by id — never off a
10730    /// listing of the board, which can be behind on the very item asked about.
10731    async fn recorded_edges(
10732        &self,
10733        id: &NativeId,
10734        near_kind: ItemKind,
10735        direction: Direction,
10736        natively_names: Option<ItemKind>,
10737        node: &Value,
10738        draft_slot: Option<&Option<BTreeMap<String, Value>>>,
10739    ) -> Result<Vec<DependencyEdge>, SourceError> {
10740        if direction != Direction::DependsOn {
10741            return Ok(Vec::new());
10742        }
10743        let slot = match (node.get("body"), draft_slot) {
10744            (Some(body), _) if natively_names.is_some() => {
10745                metadata_body(body.as_str().map(str::to_owned))?.1
10746            }
10747            // A draft the dependency read itself answered: this board's, or none of its.
10748            (_, Some(Some(slot))) => slot.clone(),
10749            (_, Some(None)) => return Ok(Vec::new()),
10750            _ => {
10751                let Some(item) = self.bound_item(id).await? else {
10752                    return Ok(Vec::new());
10753                };
10754                item.slot
10755            }
10756        };
10757        DependencyEdge::recorded(&slot, id, near_kind, &self.name, natively_names)
10758            .map_err(|message| SourceError::Malformed { message })
10759    }
10760
10761    /// Why `creation_owners` refuses a create filed in `target`, or `None` when it allows it —
10762    /// every create when the list is empty.
10763    fn owner_refusal(&self, target: &RepositoryTarget) -> Option<String> {
10764        if self.creation_owners.is_empty()
10765            || self
10766                .creation_owners
10767                .iter()
10768                .any(|owner| owner.eq_ignore_ascii_case(&target.owner))
10769        {
10770            return None;
10771        }
10772        Some(format!(
10773            "source {} would create the issue in repository {}, owned by {}, and its \
10774             creation_owners allows only repositories of {}",
10775            self.name,
10776            target.slug(),
10777            target.owner,
10778            self.creation_owners.join(", ")
10779        ))
10780    }
10781
10782    fn configured_repository(&self) -> Result<&RepositoryTarget, SourceError> {
10783        self.repository
10784            .as_ref()
10785            .ok_or_else(|| SourceError::Refused {
10786                message: format!(
10787                    "source {} has no repository configured, and a GitHub Projects board has no \
10788                 repository of its own to create an issue in; set repository: owner/name on \
10789                 this source",
10790                    self.name
10791                ),
10792            })
10793    }
10794
10795    /// The repository one new issue is created in, under the rule [`RepositoryTarget`]
10796    /// states.
10797    ///
10798    /// The fallback is demanded first, whichever arm answers: a write without a configured
10799    /// repository is refused naming the field exactly as it was before the rule existed,
10800    /// so a source that could not write before cannot write now, rather than writing for
10801    /// the one item whose own field happens to decide it.
10802    ///
10803    /// Everything this refuses is refused before `createIssue`, so a refusal leaves no
10804    /// issue behind: an entry that is not a repository on [`RepositoryTarget::HOST`], an
10805    /// entry owned by someone other than the owner of the parent issue's repository —
10806    /// GitHub accepts a sub-issue from another repository of the same owner and from no
10807    /// other, so `addSubIssue` would refuse it after the issue existed — a parent the
10808    /// board does not hold, and a parent that is a draft, which GitHub gives no sub-issues,
10809    /// both of which `addSubIssue` would likewise refuse too late. Whether the entry exists
10810    /// and is visible to the token is checked where its node id is resolved, still before
10811    /// `createIssue`. The parent is read by its own id through [`Self::item_by_id`] — never
10812    /// looked up in a listing of the board, which can be minutes behind an issue its own
10813    /// `projectItems` already places on it — and that read answers first from this process's
10814    /// own record, so a project created moments ago in this command answers though GitHub
10815    /// has not caught up.
10816    async fn creation_target(
10817        &self,
10818        incoming: &Incoming<'_>,
10819    ) -> Result<RepositoryTarget, SourceError> {
10820        let what = format!(
10821            "{} {:?}",
10822            incoming.written.kind().describes(),
10823            incoming.title
10824        );
10825        let target = self
10826            .creation_rule(incoming.repositories, incoming.parent, &what)
10827            .await?;
10828        // The engine asks `creation_refusal` before anything of a copy is written; this holds
10829        // every other create to the same restriction, before `createIssue`.
10830        match self.owner_refusal(&target) {
10831            Some(message) => Err(SourceError::Refused { message }),
10832            None => Ok(target),
10833        }
10834    }
10835
10836    /// [`Self::creation_target`]'s rule over what it reads of the item — its `repositories`
10837    /// and the project issue it is filed under — with `what` naming the item in a refusal: the
10838    /// one place the rule is, so the create, [`TaskSource::creation_repository`] and the
10839    /// write-time read of who can read the issue ([`TaskSource::visibility`]) cannot answer
10840    /// differently.
10841    ///
10842    /// On a source declared private, an item's one named repository is read for its
10843    /// visibility first — once per engine hold, see the `visibility` module — and one that
10844    /// does not read private decides nothing: the issue is created in the parent's
10845    /// repository, else the configured one. A read that cannot be answered refuses.
10846    async fn creation_rule(
10847        &self,
10848        repositories: &[Repository],
10849        parent: Option<&NativeId>,
10850        what: &str,
10851    ) -> Result<RepositoryTarget, SourceError> {
10852        let parent = match parent {
10853            Some(parent) => Some(self.bound_item(parent).await?.ok_or_else(|| {
10854                SourceError::Refused {
10855                    message: format!(
10856                        "GitHub project issue {} was not found on the board of source {}, so {} \
10857                         cannot be filed under it",
10858                        parent.0, self.name, what
10859                    ),
10860                }
10861            })?),
10862            None => None,
10863        };
10864        let parents_repository = parent
10865            .as_ref()
10866            .map(|parent| {
10867                // A draft is on the board and so is found, but it has no repository to
10868                // place a task in and GitHub gives it no sub-issues, so `addSubIssue`
10869                // would refuse the task only once `createIssue` had made it.
10870                if parent.content_kind == ContentKind::DraftIssue {
10871                    return Err(SourceError::Refused {
10872                        message: format!(
10873                            "GitHub project item {} on the board of source {} is a draft, \
10874                             which cannot have sub-issues, so {} cannot be filed under it",
10875                            parent.id.0, self.name, what
10876                        ),
10877                    });
10878                }
10879                // An issue's repository is where a sub-issue is placed and whose owner it
10880                // is compared against, so a parent whose repository this source cannot
10881                // spell as `owner/name` — GitHub's login grammar is wider than this
10882                // source's floor — is one nothing can be filed under.
10883                parent
10884                    .own_repository
10885                    .as_ref()
10886                    .and_then(|origin| RepositoryTarget::from_origin(origin).ok())
10887                    .ok_or_else(|| SourceError::Malformed {
10888                        message: format!(
10889                            "GitHub project issue {} on the board of source {} is in {}, which \
10890                             is not a {}/owner/name repository this source can place {} in",
10891                            parent.id.0,
10892                            self.name,
10893                            parent
10894                                .own_repository
10895                                .as_ref()
10896                                .map_or("no repository", Repository::as_str),
10897                            RepositoryTarget::HOST,
10898                            what
10899                        ),
10900                    })
10901            })
10902            .transpose()?;
10903        self.creation_rule_in_repository(repositories, parents_repository, what)
10904            .await
10905    }
10906
10907    async fn creation_rule_in_repository(
10908        &self,
10909        repositories: &[Repository],
10910        parents_repository: Option<RepositoryTarget>,
10911        what: &str,
10912    ) -> Result<RepositoryTarget, SourceError> {
10913        let fallback = self.configured_repository()?;
10914        match repositories {
10915            [named] => {
10916                let target =
10917                    RepositoryTarget::from_origin(named).map_err(|_| SourceError::Refused {
10918                        message: format!(
10919                            "{} names repository {}, which is not a {}/owner/name repository \
10920                             source {} can create an issue in; name one that is, or name none",
10921                            what,
10922                            named.as_str(),
10923                            RepositoryTarget::HOST,
10924                            self.name
10925                        ),
10926                    })?;
10927                // On a source declared private, an issue whose one named repository does not
10928                // read private is created where an item naming none is: the item still names
10929                // that repository in its metadata slot, and its issue stays private.
10930                if self.is_declared_private()
10931                    && self.repository_visibility(&target).await?
10932                        != onetaskgraph_plugin_api::Visibility::Private
10933                {
10934                    return Ok(parents_repository.unwrap_or_else(|| fallback.clone()));
10935                }
10936                if let Some(parents) = &parents_repository
10937                    && parents.owner != target.owner
10938                {
10939                    return Err(SourceError::Refused {
10940                        message: format!(
10941                            "{} names repository {}, owned by {}, but its project's issue is in \
10942                             {}, owned by {}, and GitHub files a sub-issue only in a repository \
10943                             of the same owner as its parent issue; name a repository of {}, or \
10944                             name none",
10945                            what,
10946                            target.slug(),
10947                            target.owner,
10948                            parents.slug(),
10949                            parents.owner,
10950                            parents.owner
10951                        ),
10952                    });
10953                }
10954                Ok(target)
10955            }
10956            _ => Ok(parents_repository.unwrap_or_else(|| fallback.clone())),
10957        }
10958    }
10959
10960    /// The node id of the repository `incoming` is being created in, or the refusal naming
10961    /// the item and the repository the token cannot see.
10962    ///
10963    /// Resolved once per command per repository; see [`Self::repository_cache`].
10964    async fn repository_id(
10965        &self,
10966        repository: &RepositoryTarget,
10967        incoming: &Incoming<'_>,
10968    ) -> Result<String, SourceError> {
10969        if let Some(id) = self.repository_cache()?.get(repository).cloned() {
10970            return Ok(id);
10971        }
10972        let data = self
10973            .graphql(
10974                graphql::REPOSITORY,
10975                json!({"owner":repository.owner,"name":repository.name}),
10976            )
10977            .await?;
10978        self.repository_read(&data, repository, incoming)
10979    }
10980
10981    /// The repository's node id out of an answer carrying the `repository` root, held for
10982    /// the rest of this command, or the refusal naming the item that cannot be created in it.
10983    fn repository_read(
10984        &self,
10985        data: &Value,
10986        repository: &RepositoryTarget,
10987        incoming: &Incoming<'_>,
10988    ) -> Result<String, SourceError> {
10989        let node = data
10990            .get("repository")
10991            .filter(|value| !value.is_null())
10992            .ok_or_else(|| SourceError::Refused {
10993                message: format!(
10994                    "GitHub repository {} was not found or is not visible to the token, so {} \
10995                     {:?} cannot be created in it",
10996                    repository.slug(),
10997                    incoming.written.kind().describes(),
10998                    incoming.title
10999                ),
11000            })?;
11001        let id = required_str(node, "id")?.to_owned();
11002        self.repository_cache()?
11003            .insert(repository.clone(), id.clone());
11004        Ok(id)
11005    }
11006
11007    fn repository_cache(
11008        &self,
11009    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<RepositoryTarget, String>>, SourceError> {
11010        self.repository_cache
11011            .lock()
11012            .map_err(|_| SourceError::Unavailable {
11013                message: "this source's record of the destination repository was left \
11014                          inconsistent by an earlier failure; next: run the command again"
11015                    .into(),
11016            })
11017    }
11018
11019    /// Create or update one board item, whichever kind it is.
11020    async fn write_item(
11021        &self,
11022        incoming: &Incoming<'_>,
11023        target: Option<&NativeId>,
11024        depends_on: &[DependencyEdge],
11025    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
11026        let prepared = self.prepare_write(incoming, target, depends_on).await?;
11027        let landed = match &prepared.destination {
11028            // Its content is written last, by `complete_write`, once everything else has landed.
11029            WriteDestination::Existing(item) => Landed {
11030                content_id: item.id.clone(),
11031                item_id: Some(item.item_id.clone()),
11032                url: item.url.clone(),
11033                number: item.number,
11034            },
11035            WriteDestination::New(target) => {
11036                if self.deferring()? {
11037                    self.create_filed_issue(
11038                        prepared.board.id.as_str(),
11039                        target,
11040                        incoming,
11041                        &prepared.body,
11042                    )
11043                    .await?
11044                } else {
11045                    self.create_and_file_issue(
11046                        prepared.board.id.as_str(),
11047                        target,
11048                        incoming,
11049                        &prepared.body,
11050                    )
11051                    .await?
11052                }
11053            }
11054        };
11055        self.complete_write(incoming, prepared, landed).await
11056    }
11057
11058    /// Everything one write of `incoming` reads and decides before it sends anything: what is
11059    /// there now, where a new item is created, the board's fields, and every value refused while
11060    /// nothing has been written — the item's body included.
11061    async fn prepare_write(
11062        &self,
11063        incoming: &Incoming<'_>,
11064        target: Option<&NativeId>,
11065        depends_on: &[DependencyEdge],
11066    ) -> Result<Prepared, SourceError> {
11067        // Refused before anything is read or written: a task or a project titled the way
11068        // this board spells a document would land as an issue this same source reads back
11069        // as a document, so the field this destination cannot carry is named rather than
11070        // written and silently reclassified.
11071        if let Written::Work(kind, _) = incoming.written
11072            && incoming.title.starts_with(DESIGN_TITLE_PREFIX)
11073        {
11074            return Err(SourceError::Refused {
11075                message: format!(
11076                    "the title of this {} begins {DESIGN_TITLE_PREFIX:?}, which is how source {} \
11077                     spells a document, so it would read back as one rather than as a {}; \
11078                     retitle it, or copy it as a document",
11079                    kind.marker(),
11080                    self.name,
11081                    kind.marker()
11082                ),
11083            });
11084        }
11085        // The destination is read by its own id, and whether this board holds it is decided
11086        // by that read — its own `projectItems` — rather than by whether a listing of the
11087        // board happens to include it yet. See the module documentation.
11088        // An existing issue is never moved; a new one is created where the rule says — and
11089        // knowing where is what lets the board's fields and that repository's id be read
11090        // together, before anything below needs either.
11091        let destination = match target {
11092            Some(target) => {
11093                WriteDestination::Existing(Box::new(self.bound_item(target).await?.ok_or_else(
11094                    || SourceError::Refused {
11095                        message: format!("GitHub destination item {} was not found", target.0),
11096                    },
11097                )?))
11098            }
11099            None => {
11100                let target = self.creation_target(incoming).await?;
11101                self.creation_context(&target, incoming).await?;
11102                WriteDestination::New(target)
11103            }
11104        };
11105        let existing = destination.existing();
11106        let board = self
11107            .fields_for(
11108                existing,
11109                incoming.metadata.contains_key(ORIGIN_KEY),
11110                incoming.written.status().is_some(),
11111                incoming
11112                    .priority
11113                    .is_some_and(|priority| priority != Priority::None),
11114            )
11115            .await?;
11116        let status_target = incoming
11117            .written
11118            .work_status()
11119            .map(|(kind, status)| self.resolved_target(kind, status.category))
11120            .transpose()?;
11121        let column = match (incoming.written.work_status(), status_target.as_ref()) {
11122            (Some((kind, status)), Some(target)) => {
11123                self.column_for(&board.fields, kind, status.category, target)?
11124            }
11125            _ => None,
11126        };
11127        // Resolved before anything is created, for the reason the column above is: a
11128        // priority this board has no option for is refused while nothing has been written.
11129        let priority_write = match incoming.priority {
11130            Some(priority) => self.priority_write(&board.fields, existing, priority)?,
11131            None => None,
11132        };
11133        // And for the reason the priority is: a value no projected field can hold, or a board
11134        // that cannot hold the field, is refused while nothing has been written.
11135        let (projections, projected) = self.projection_writes(
11136            &board.fields,
11137            existing.map(|item| &item.projected),
11138            incoming.metadata,
11139            None,
11140        )?;
11141        let content_kind = existing.map_or(ContentKind::Issue, |item| item.content_kind);
11142        if content_kind == ContentKind::DraftIssue {
11143            if let (Some(StatusTarget::Terminal(_, _)), Some(status)) =
11144                (status_target.as_ref(), incoming.written.status())
11145            {
11146                return Err(self.closes_a_draft(status.category));
11147            }
11148            if incoming.parent.is_some() {
11149                return Err(SourceError::Refused {
11150                    message: "GitHub draft items cannot be a project's sub-issue".into(),
11151                });
11152            }
11153        }
11154        // The people it is to be assigned to are looked up — unless this process already has —
11155        // and a login GitHub does not know refused, while nothing has been written.
11156        if let Some(people) = incoming.assignees
11157            && existing.is_none_or(|item| {
11158                item.assignees
11159                    .as_deref()
11160                    .is_none_or(|held| !assignees::same_people(held, people))
11161            })
11162        {
11163            if content_kind == ContentKind::DraftIssue {
11164                return Err(self.assigns_a_draft());
11165            }
11166            self.resolve_people(people).await?;
11167            self.people_ids(
11168                people,
11169                &existing.map_or_else(
11170                    || format!("the new {}", incoming.title),
11171                    Resolved::written_name,
11172                ),
11173            )?;
11174        }
11175        match existing {
11176            Some(item) if content_kind == ContentKind::Issue => {
11177                if item.labels != incoming.labels {
11178                    return Err(SourceError::Refused {
11179                        message: "GitHub issue labels differ from the labels being written".into(),
11180                    });
11181                }
11182            }
11183            _ => {
11184                if !incoming.labels.is_empty() {
11185                    return Err(SourceError::Refused {
11186                        message: "GitHub items created by this destination carry no labels".into(),
11187                    });
11188                }
11189            }
11190        }
11191
11192        // The repository the issue really lives in is what the slot below is written against,
11193        // so a single entry that is where the issue is created travels as no key at all, and
11194        // the read side derives it back from the issue.
11195        let own_repository = match &destination {
11196            WriteDestination::Existing(item) => item.own_repository.clone(),
11197            WriteDestination::New(target) => Some(
11198                Repository::try_from(target.origin())
11199                    .map_err(|message| SourceError::Config { message })?,
11200            ),
11201        };
11202        let (native, fallback) = self
11203            .partition_edges(
11204                incoming.written.kind(),
11205                content_kind,
11206                existing.and_then(|item| item.blocked_by.as_deref()),
11207                depends_on,
11208            )
11209            .await?;
11210        let mut slot = slot_metadata(incoming, own_repository.as_ref(), &fallback);
11211        let content = match incoming.assets {
11212            Some(assets) => {
11213                let uploads = self.upload_assets(own_repository.as_ref(), assets).await?;
11214                let rewritten = onetaskgraph_plugin_api::serve_asset_references(
11215                    incoming.content.unwrap_or_default(),
11216                    &mut slot,
11217                    &uploads,
11218                );
11219                incoming.content.map(|_| rewritten)
11220            }
11221            None => incoming.content.map(str::to_owned),
11222        };
11223        // A write over an existing item keeps its `## Links` section, re-rendered from the
11224        // links it holds.
11225        let content = content.map(|content| {
11226            onetaskgraph_plugin_api::relinked(
11227                &content,
11228                existing.and_then(|item| item.body.as_deref()),
11229                incoming.metadata,
11230            )
11231        });
11232        let marked = content.as_deref().map(|content| self.marked(content));
11233        let body = compose_body(marked.as_deref(), &slot)?;
11234        // Read before anything is created, for the reason the field below is: a value
11235        // this destination cannot store has to refuse, and refusing after `createIssue`
11236        // would leave an issue behind that nothing asked for. The engine writes a
11237        // qualified id here; a caller handing this key anything else is told so rather
11238        // than having it silently stored as no origin at all.
11239        // 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.
11240        let origin = match incoming.metadata.get(ORIGIN_KEY) {
11241            None => "",
11242            Some(Value::String(origin)) => origin.as_str(),
11243            Some(other) => {
11244                return Err(SourceError::Refused {
11245                    message: format!(
11246                        "{ORIGIN_KEY} holds a qualified id spelled as a string, and this item's \
11247                         is {other}"
11248                    ),
11249                });
11250            }
11251        };
11252        // Resolved before anything is created: a board that cannot carry the copy origin
11253        // has to refuse the write, and refusing it after `createIssue` would leave an
11254        // issue behind that nothing asked for.
11255        let origin_field = match Board::field(&board.fields, ORIGIN_FIELD)? {
11256            Some(field) => {
11257                if required_str(field, "__typename")? != "ProjectV2Field" {
11258                    return Err(SourceError::Refused {
11259                        message: format!(
11260                            "GitHub board source-owned {ORIGIN_FIELD} field is not a text field"
11261                        ),
11262                    });
11263                }
11264                Some(required_str(field, "id")?.to_owned())
11265            }
11266            None if incoming.metadata.contains_key(ORIGIN_KEY) => {
11267                return Err(SourceError::Refused {
11268                    message: format!(
11269                        "GitHub board has no source-owned {ORIGIN_FIELD} text field, and the \
11270                         item carries {ORIGIN_KEY}; add a text field named {ORIGIN_FIELD} to \
11271                         the board"
11272                    ),
11273                });
11274            }
11275            None => None,
11276        };
11277
11278        Ok(Prepared {
11279            origin: origin.to_owned(),
11280            destination,
11281            board,
11282            status_target,
11283            column,
11284            priority_write,
11285            projections,
11286            projected,
11287            content_kind,
11288            own_repository,
11289            native,
11290            slot,
11291            content,
11292            body,
11293            origin_field,
11294        })
11295    }
11296
11297    /// Everything one write does once the item it writes exists: its board fields, its
11298    /// relationships and — for an item that was already there — its content last, then what this
11299    /// process remembers of it.
11300    ///
11301    /// While this source is holding writes back — see [`TaskSource::begin_deferred_writes`] — an
11302    /// item this command created has its fields, its closing and its edges held for
11303    /// [`TaskSource::finish_writes`] rather than sent here.
11304    async fn complete_write(
11305        &self,
11306        incoming: &Incoming<'_>,
11307        prepared: Prepared,
11308        landed: Landed,
11309    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
11310        let Prepared {
11311            destination,
11312            board,
11313            status_target,
11314            column,
11315            priority_write,
11316            projections,
11317            projected,
11318            content_kind,
11319            own_repository,
11320            native,
11321            slot,
11322            content,
11323            body,
11324            origin,
11325            origin_field,
11326        } = prepared;
11327        let existing = destination.existing();
11328        let origin = origin.as_str();
11329        let Landed {
11330            content_id,
11331            item_id,
11332            url,
11333            number,
11334        } = landed;
11335
11336        // Only what differs from the item as this write read it is sent: a priority the item
11337        // already holds is not, so an unchanged re-copy writes no field and a person's edit of
11338        // it since that read is left alone.
11339        let priority_write = priority_write.filter(|_| {
11340            !existing.is_some_and(|item| {
11341                incoming.priority.map(HeldPriority::Read) == Some(item.priority.clone())
11342            })
11343        });
11344        let written_option = column.as_ref().map(|(_, _, name)| name.clone());
11345        let column = column
11346            .filter(|(_, _, name)| existing.is_none_or(|item| item.option.as_ref() != Some(name)))
11347            .map(|(field, option, _)| (field, option));
11348        // Creating an item here is several calls — `createIssue`, which files it on the
11349        // board, then its board fields, the parent and the dependencies — and GitHub can fail
11350        // at any of them. Everything this source can refuse *before* the first of those is
11351        // already checked above, so what is left is GitHub itself failing part way. When it
11352        // does over an item this call created, the issue is taken back: a write that
11353        // refused must not leave an item behind that nobody asked for, and one that does
11354        // makes the retry create a second.
11355        // Whether the board-field write carrying a moved origin was answered as landing whole.
11356        // When it was refused, GitHub does not say which of its fields ran before the one that
11357        // failed, so the origin may or may not have moved.
11358        let mut origin_landed = false;
11359        // An item this command created while writes are held back has every part that can land
11360        // later held for `finish_writes` — its own create filed it on the board and under its
11361        // project already — and so does a later write of it in the same command.
11362        let holding = (existing.is_none() && self.deferring()?) || self.holds_back(&content_id)?;
11363        let landed = if holding {
11364            self.hold_back(
11365                &board.id,
11366                &content_id,
11367                existing,
11368                origin_field.as_deref(),
11369                origin,
11370                column,
11371                status_target.as_ref(),
11372                priority_write.as_ref(),
11373                &projections,
11374                &native,
11375            )
11376        } else if let Some(item_id) = item_id.as_deref() {
11377            self.finish_write(
11378                board.id.as_str(),
11379                incoming,
11380                &content_id,
11381                item_id,
11382                content_kind,
11383                existing,
11384                origin_field.as_deref(),
11385                origin,
11386                column,
11387                status_target.as_ref(),
11388                priority_write.as_ref(),
11389                &projections,
11390                &native,
11391                &mut origin_landed,
11392            )
11393            .await
11394        } else {
11395            // An issue a create filed on the board itself has no board item this process
11396            // knows until `finish_writes` reads it, so nothing but a held-back write may land
11397            // on it before then.
11398            Err(SourceError::Malformed {
11399                message: format!(
11400                    "issue {} was written before the board item GitHub filed it as was read",
11401                    content_id.0
11402                ),
11403            })
11404        };
11405        // An existing item's title, body and state go last, in one `updateIssue`, once its board
11406        // fields and its relationships have landed: a refusal of any of those then leaves its
11407        // body — and the metadata slot inside it — exactly as it stood.
11408        let landed = match (landed, existing) {
11409            (Ok(()), Some(item)) => {
11410                self.update_existing(item, incoming, &body, status_target.as_ref())
11411                    .await
11412            }
11413            (landed, _) => landed,
11414        };
11415        if let Err(error) = landed {
11416            match existing {
11417                // Best effort, and the write's own failure is what the caller is told: a
11418                // refusal naming the tidy-up would hide why the write failed at all.
11419                None => {
11420                    let _ = self.delete_issue(&content_id).await;
11421                }
11422                // The origin field is the one piece of an existing item's metadata written
11423                // before its body, so a write refused after it puts it back as it was. When
11424                // that is refused too, the write's own failure is still what the caller is
11425                // told — with what it left behind added, because the item's metadata is then
11426                // not as it stood and a caller retrying has to know which key moved.
11427                Some(item) => {
11428                    let before = item.origin.as_deref().unwrap_or("");
11429                    if let Some(field) = origin_field.as_deref()
11430                        && before != origin
11431                        && let Err(restore) = self
11432                            .set_item_field(
11433                                board.id.as_str(),
11434                                &item.item_id,
11435                                field,
11436                                json!({"text": before}),
11437                            )
11438                            .await
11439                    {
11440                        let left = if origin_landed {
11441                            format!(
11442                                "its {ORIGIN_KEY} was moved to {origin:?} before that and could \
11443                                 not be put back to {before:?} ({restore}), so item {} still \
11444                                 holds {origin:?} there",
11445                                item.id.0
11446                            )
11447                        } else {
11448                            format!(
11449                                "the refused write carried its {ORIGIN_KEY} from {before:?} to \
11450                                 {origin:?}, GitHub does not say whether that part of it ran, \
11451                                 and putting it back to {before:?} was refused ({restore}), so \
11452                                 item {} holds {origin:?} or {before:?} there",
11453                                item.id.0
11454                            )
11455                        };
11456                        return Err(noting(
11457                            error,
11458                            &format!(
11459                                "; {left}; next: set {ORIGIN_KEY} on it back to {before:?}, or \
11460                                 run the write again"
11461                            ),
11462                        ));
11463                    }
11464                }
11465            }
11466            return Err(error);
11467        }
11468
11469        let written_status = match (incoming.written.work_status(), status_target.as_ref()) {
11470            (Some((kind, _)), Some(StatusTarget::Terminal(_, reason))) => {
11471                self.statuses
11472                    .status(kind, written_option.as_deref(), true, Some(reason.reason()))
11473            }
11474            (Some((kind, _)), Some(StatusTarget::Column(_))) => {
11475                self.statuses
11476                    .status(kind, written_option.as_deref(), false, None)
11477            }
11478            (Some((_, status)), _) => status.clone(),
11479            (None, _) => Status {
11480                category: StatusCategory::Unknown,
11481                name: "Open".to_owned(),
11482            },
11483        };
11484
11485        // So the rest of this command reads what it just did rather than what the board
11486        // said before it. See `remember_written` for which half takes it.
11487        let remembered = Resolved {
11488            // Empty for an issue whose board item is not read yet: `finish_writes` reads it
11489            // and `learn_item` puts it here.
11490            // 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.
11491            item_id: item_id.unwrap_or_default(),
11492            id: content_id.clone(),
11493            content_kind,
11494            kind: incoming.written.kind(),
11495            title: incoming.title.to_owned(),
11496            // The visible half of the body this write composed, split back off it the
11497            // way a read splits it — so what this record reports is what a read of the
11498            // same issue reports, rather than the person's text with the metadata slot
11499            // still on the end of it.
11500            body: self.visible(body.clone())?.0,
11501            raw_body: body.clone(),
11502            // A document has no status of its own; what it reads back as is whatever
11503            // the issue's own state says, which is what a re-read reports.
11504            status: written_status,
11505            option: written_option.or_else(|| existing.and_then(|item| item.option.clone())),
11506            priority: match incoming.priority {
11507                Some(priority) => HeldPriority::Read(priority),
11508                None => existing.map_or(HeldPriority::Read(Priority::None), |item| {
11509                    item.priority.clone()
11510                }),
11511            },
11512            // What `state_input` asked for: closed for a terminal target, open for any other
11513            // status, and the issue's own state left as it was by a document write.
11514            closed: content_kind == ContentKind::Issue
11515                && match status_target.as_ref() {
11516                    Some(StatusTarget::Terminal(_, _)) => true,
11517                    Some(_) => false,
11518                    None => existing.is_some_and(|item| item.closed),
11519                },
11520            reason: match status_target.as_ref() {
11521                Some(StatusTarget::Terminal(_, reason)) if content_kind == ContentKind::Issue => {
11522                    Some(reason.reason().to_owned())
11523                }
11524                Some(_) => None,
11525                None => existing.and_then(|item| item.reason.clone()),
11526            },
11527            delivers: incoming.delivers.to_vec(),
11528            delivered_by: incoming.delivered_by.to_vec(),
11529            labels: incoming.labels.to_vec(),
11530            parent: incoming.parent.cloned(),
11531            issue_parent: None,
11532            origin: (!origin.is_empty()).then(|| origin.to_owned()),
11533            projected,
11534            number,
11535            // In the update path this is the item's own url, read off `existing` where the
11536            // record above was bound, so one expression serves both halves.
11537            url,
11538            created_at: existing.and_then(|item| item.created_at),
11539            updated_at: existing.and_then(|item| item.updated_at),
11540            // What this write moved is GitHub's to say, so a record of it gives no token until
11541            // it is read again.
11542            item_updated_at: None,
11543            comment_count: None,
11544            relationship_events: None,
11545            served_at: None,
11546            facets: None,
11547            own_repository,
11548            repositories: incoming.repositories.to_vec(),
11549            classification: incoming.classification,
11550            slot,
11551            board_id: Some(board.id.as_str().to_owned()),
11552            fields: board
11553                .fields
11554                .get("nodes")
11555                .and_then(Value::as_array)
11556                .cloned()
11557                .unwrap_or_default(),
11558            board_fields: Some(board.fields.clone()),
11559            // What this write left the relationship holding is known by id alone, and a
11560            // later read of its edges needs each far end's kind, so it reads them again.
11561            blocked_by: None,
11562            // The people it named, which its own answer was held to; none named keeps the
11563            // item's, and creates a task of an opted-in source unassigned.
11564            assignees: match incoming.assignees {
11565                Some(people) => Some(people.to_vec()),
11566                None => match existing {
11567                    Some(item) => item.assignees.clone(),
11568                    None => (self.assignees
11569                        && matches!(incoming.written, Written::Work(ItemKind::Task, _)))
11570                    .then(Vec::new),
11571                },
11572            },
11573        };
11574        self.remember_written(remembered, existing.is_none())?;
11575        Ok(onetaskgraph_plugin_api::AssetsWritten {
11576            id: content_id,
11577            content,
11578        })
11579    }
11580
11581    /// Everything a write does after the item exists: its board fields, its parent, and
11582    /// its dependencies.
11583    ///
11584    /// Split out of `write_item` so there is one place a failure past the point of no
11585    /// return is caught, rather than a tidy-up repeated at each `?` above.
11586    // llmlint: ignore[suppressions_justified] This is the tail of `write_item` lifted out
11587    // so there is one place a failure past the point of no return is caught, and its
11588    // arguments are exactly the values that tail already had in scope. Bundling them into a
11589    // struct would describe no concept — it would be "the arguments of this function" — and
11590    // would put the whole of `write_item`'s locals behind one more indirection.
11591    #[allow(clippy::too_many_arguments)]
11592    async fn finish_write(
11593        &self,
11594        board_id: &str,
11595        incoming: &Incoming<'_>,
11596        content_id: &NativeId,
11597        item_id: &str,
11598        content_kind: ContentKind,
11599        existing: Option<&Resolved>,
11600        origin_field: Option<&str>,
11601        origin: &str,
11602        column: Option<(String, String)>,
11603        status_target: Option<&StatusTarget>,
11604        priority: Option<&PriorityWrite>,
11605        projections: &[ProjectionWrite],
11606        native: &[String],
11607        origin_landed: &mut bool,
11608    ) -> Result<(), SourceError> {
11609        let (fields, clears) = field_writes(
11610            existing,
11611            origin_field,
11612            origin,
11613            column,
11614            priority,
11615            projections,
11616        );
11617        self.set_item_fields(board_id, item_id, &fields, &clears)
11618            .await?;
11619        *origin_landed = true;
11620
11621        // An existing issue closes in the `updateIssue` its write ends with; one created just
11622        // now closes here, once its option is selected.
11623        if existing.is_none()
11624            && content_kind == ContentKind::Issue
11625            && matches!(status_target, Some(StatusTarget::Terminal(_, _)))
11626        {
11627            self.update_content(
11628                ContentKind::Issue,
11629                content_id,
11630                json!({"stateInput":state_input(status_target)}),
11631            )
11632            .await?;
11633        }
11634
11635        if content_kind == ContentKind::Issue {
11636            self.reparent(
11637                existing.and_then(|item| item.parent.clone()),
11638                content_id,
11639                incoming.parent,
11640            )
11641            .await?;
11642            // A document takes part in no dependency graph, so writing one neither reads
11643            // nor changes the issue's own `blockedBy` relationships. Reconciling them
11644            // against the empty list a document write carries would *delete* whatever
11645            // relationships a person had made on that issue, which is a write nobody
11646            // asked for.
11647            if incoming.written.kind() != BoardKind::Document {
11648                let issue = match existing {
11649                    Some(item) => Issue::Existing(item.blocked_by.as_deref()),
11650                    None => Issue::Created,
11651                };
11652                self.reconcile_blocked_by(content_id, native, issue).await?;
11653            }
11654        }
11655        Ok(())
11656    }
11657
11658    /// Whether this source is holding writes back — see [`TaskSource::begin_deferred_writes`].
11659    fn deferring(&self) -> Result<bool, SourceError> {
11660        Ok(self.deferred()?.is_some())
11661    }
11662
11663    /// Whether `content` is an item this command created whose parts are held back.
11664    fn holds_back(&self, content: &NativeId) -> Result<bool, SourceError> {
11665        Ok(self
11666            .deferred()?
11667            .as_ref()
11668            .is_some_and(|deferred| deferred.holds(content)))
11669    }
11670
11671    fn deferred(&self) -> Result<std::sync::MutexGuard<'_, Option<Deferred>>, SourceError> {
11672        self.deferred.lock().map_err(|_| SourceError::Unavailable {
11673            message: "this source's record of the writes it is holding back was left \
11674                      inconsistent by an earlier failure; next: run the command again"
11675                .into(),
11676        })
11677    }
11678
11679    /// Creates one issue filed on the board and under its project by the `createIssue` itself —
11680    /// `projectV2Ids` naming the board and `parentIssueId` the project — which is what a copy
11681    /// creates with: one request where adding it to the board and filing it under its project
11682    /// were two more. GitHub adds the board item after answering, so its id is not known here;
11683    /// [`TaskSource::finish_writes`] reads it.
11684    async fn create_filed_issue(
11685        &self,
11686        board_id: &str,
11687        repository: &RepositoryTarget,
11688        incoming: &Incoming<'_>,
11689        body: &Option<String>,
11690    ) -> Result<Landed, SourceError> {
11691        let repository_id = self.repository_id(repository, incoming).await?;
11692        let mut input = filed_input(&repository_id, board_id, incoming, body);
11693        self.assigning(&mut input, incoming)?;
11694        let data = match self
11695            .graphql(graphql::CREATE_ISSUE, json!({"input": &input}))
11696            .await
11697        {
11698            Ok(data) => data,
11699            Err(error) => return Err(self.refusing_people(&input, error)),
11700        };
11701        let created = data
11702            .pointer("/createIssue/issue")
11703            .filter(|value| !value.is_null())
11704            .ok_or_else(|| SourceError::Malformed {
11705                message: "GitHub issue creation returned no issue".into(),
11706            })?;
11707        let landed = self.created_landed(created).await?;
11708        // An issue GitHub created assigned otherwise than asked is refused and taken back; a
11709        // delete GitHub refuses too is answered beside the refusal, naming the issue left.
11710        if let Err(error) = self.assigned_as_asked(&input, Some(created)) {
11711            return Err(self.taken_back(&landed.content_id, created, error).await);
11712        }
11713        Ok(landed)
11714    }
11715
11716    /// Keep the address `createIssue` answered for the issue `content`, for
11717    /// [`TaskSource::written_location`].
11718    fn note_written(&self, content: &NativeId, url: Option<&str>) {
11719        if let Some(url) = url {
11720            self.written
11721                .lock()
11722                .unwrap_or_else(std::sync::PoisonError::into_inner)
11723                .insert(content.clone(), url.to_owned());
11724        }
11725    }
11726
11727    /// What one `createIssue` answered, as the item it created — or, when its number cannot be
11728    /// read, the refusal, after taking the issue back.
11729    async fn created_landed(&self, created: &Value) -> Result<Landed, SourceError> {
11730        let content_id = NativeId(required_nonblank_str(created, "id")?.to_owned());
11731        let url = optional_str(created, "url")?.map(str::to_owned);
11732        let number = match created_issue_number(created) {
11733            Ok(number) => number,
11734            Err(error) => {
11735                let _ = self.delete_issue(&content_id).await;
11736                return Err(error);
11737            }
11738        };
11739        self.note_written(&content_id, url.as_deref());
11740        Ok(Landed {
11741            content_id,
11742            item_id: None,
11743            url,
11744            number,
11745        })
11746    }
11747
11748    /// Hold back everything a write of the created item `content` would send after creating it,
11749    /// for [`TaskSource::finish_writes`]: the same field values, closing and edges
11750    /// `finish_write` sends, the parent excepted, which its create already named. A later write
11751    /// of the same item replaces what it changes.
11752    // 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.
11753    #[allow(clippy::too_many_arguments)]
11754    fn hold_back(
11755        &self,
11756        board_id: &BoardId,
11757        content: &NativeId,
11758        existing: Option<&Resolved>,
11759        origin_field: Option<&str>,
11760        origin: &str,
11761        column: Option<(String, String)>,
11762        status_target: Option<&StatusTarget>,
11763        priority: Option<&PriorityWrite>,
11764        projections: &[ProjectionWrite],
11765        native: &[String],
11766    ) -> Result<(), SourceError> {
11767        let status = column.map(|(field, option)| {
11768            let name = self
11769                .fields_cache()
11770                .ok()
11771                .and_then(|fields| {
11772                    fields.as_ref().and_then(|board| {
11773                        option_name(&board.fields, &field, &option).map(str::to_owned)
11774                    })
11775                })
11776                .unwrap_or_default();
11777            (field, option, name)
11778        });
11779        let (fields, clears) =
11780            field_writes(existing, origin_field, origin, None, priority, projections);
11781        let close = match status_target {
11782            Some(StatusTarget::Terminal(_, reason)) => Some(*reason),
11783            _ => None,
11784        };
11785        let mut deferred = self.deferred()?;
11786        let deferred = deferred.get_or_insert_with(Deferred::default);
11787        if let Deferred::Nothing = deferred {
11788            *deferred = Deferred::Held {
11789                board: board_id.clone(),
11790                created: Vec::new(),
11791            };
11792        }
11793        let Deferred::Held { created, .. } = deferred else {
11794            unreachable!("held back on the line above");
11795        };
11796        let held = match created.iter().position(|held| held.content == *content) {
11797            Some(at) => &mut created[at],
11798            None => {
11799                created.push(HeldBack {
11800                    content: content.clone(),
11801                    fields: Vec::new(),
11802                    status: None,
11803                    clears: Vec::new(),
11804                    close: None,
11805                    edges: Vec::new(),
11806                });
11807                created.last_mut().expect("just held")
11808            }
11809        };
11810        for (field, value) in fields {
11811            held.fields.retain(|(held, _)| *held != field);
11812            held.clears.retain(|held| *held != field);
11813            held.fields.push((field, value));
11814        }
11815        for field in clears {
11816            held.fields.retain(|(held, _)| held != field);
11817            if !held.clears.iter().any(|held| held == field) {
11818                held.clears.push(field.to_owned());
11819            }
11820        }
11821        if status.is_some() {
11822            held.status = status;
11823        }
11824        if close.is_some() {
11825            held.close = close;
11826        }
11827        // Nothing of an item created in this command has been sent but its create, so the edges
11828        // it is to have are exactly the ones its latest write names.
11829        held.edges = native.iter().map(|far| NativeId(far.clone())).collect();
11830        Ok(())
11831    }
11832
11833    /// Create every task of `writes`, together, filed on the board and under each one's
11834    /// project: [`graphql::CREATE_ISSUES`], [`MUTATION_BATCH`] to a request.
11835    ///
11836    /// Each is prepared as [`Self::write_item`] prepares one — every refusal a write owes made
11837    /// before the first request — then created, then completed with its parts held back. A
11838    /// request refused part way leaves the issues it did create, which are taken back, with the
11839    /// rest of this call's, before the refusal is answered.
11840    async fn create_together(
11841        &self,
11842        writes: &[ItemWrite<Task>],
11843    ) -> Result<Vec<NativeId>, SourceError> {
11844        let incomings: Vec<Incoming<'_>> = writes
11845            .iter()
11846            .map(|write| self.task_incoming(write, None))
11847            .collect::<Result<_, _>>()?;
11848        // Every person these creates assign, looked up together rather than one write at a time.
11849        let people: Vec<String> = writes
11850            .iter()
11851            .filter_map(|write| write.item.assignees.clone())
11852            .flatten()
11853            .collect();
11854        self.resolve_people(&people).await?;
11855        let mut prepared = Vec::with_capacity(writes.len());
11856        for (incoming, write) in incomings.iter().zip(writes) {
11857            if write.target.is_some() {
11858                return Err(SourceError::Malformed {
11859                    message: "a write naming its target was handed to a batch of creates".into(),
11860                });
11861            }
11862            prepared.push(
11863                self.prepare_write(incoming, None, &write.depends_on)
11864                    .await?,
11865            );
11866        }
11867        let mut inputs = Vec::with_capacity(prepared.len());
11868        for (incoming, prepared) in incomings.iter().zip(&prepared) {
11869            let WriteDestination::New(target) = &prepared.destination else {
11870                return Err(SourceError::Malformed {
11871                    message: "an update was decided for a write handed to a batch of creates"
11872                        .into(),
11873                });
11874            };
11875            let repository_id = self.repository_id(target, incoming).await?;
11876            let mut input = filed_input(
11877                &repository_id,
11878                prepared.board.id.as_str(),
11879                incoming,
11880                &prepared.body,
11881            );
11882            self.assigning(&mut input, incoming)?;
11883            inputs.push(input);
11884        }
11885        let mut landed: Vec<Landed> = Vec::with_capacity(inputs.len());
11886        let refused = 'create: {
11887            for chunk in inputs.chunks(MUTATION_BATCH) {
11888                let mut variables = serde_json::Map::new();
11889                for slot in 0..MUTATION_BATCH {
11890                    variables.insert(
11891                        format!("create{slot}"),
11892                        chunk.get(slot).cloned().unwrap_or_else(|| chunk[0].clone()),
11893                    );
11894                    variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
11895                }
11896                let data = match self
11897                    .graphql(graphql::CREATE_ISSUES, Value::Object(variables))
11898                    .await
11899                {
11900                    Ok(data) => data,
11901                    Err(error) => break 'create Some(error),
11902                };
11903                let mut refusal = data.get(ANSWER_ERRORS).map(|errors| {
11904                    let said: Vec<&str> = errors
11905                        .as_array()
11906                        .into_iter()
11907                        .flatten()
11908                        .filter_map(|error| error.get("message").and_then(Value::as_str))
11909                        .collect();
11910                    SourceError::Refused {
11911                        message: if said.is_empty() {
11912                            "GitHub returned GraphQL errors".to_owned()
11913                        } else {
11914                            said.join("; ")
11915                        },
11916                    }
11917                });
11918                for (slot, input) in chunk.iter().enumerate() {
11919                    match data
11920                        .pointer(&format!("/create{slot}/issue"))
11921                        .filter(|value| !value.is_null())
11922                    {
11923                        Some(created) => match self.created_landed(created).await {
11924                            Ok(landed_one) => {
11925                                landed.push(landed_one);
11926                                // Taken back with the rest, as any refusal here is.
11927                                if let Err(error) = self.assigned_as_asked(input, Some(created)) {
11928                                    refusal.get_or_insert(error);
11929                                }
11930                            }
11931                            Err(error) => {
11932                                refusal.get_or_insert(error);
11933                            }
11934                        },
11935                        // An alias GitHub refused answers nothing, and the refusal says why.
11936                        None => {
11937                            refusal.get_or_insert(SourceError::Malformed {
11938                                message: "GitHub issue creation returned no issue".into(),
11939                            });
11940                        }
11941                    }
11942                }
11943                if let Some(error) = refusal {
11944                    break 'create Some(error);
11945                }
11946            }
11947            None
11948        };
11949        if let Some(error) = refused {
11950            // None of these ids reaches the caller, so an issue GitHub will not take back is
11951            // named here or by nobody.
11952            let ids: Vec<&NativeId> = landed.iter().map(|created| &created.content_id).collect();
11953            let left = self.delete_issues(&ids).await;
11954            let left: Vec<&str> = left.iter().map(|id| id.0.as_str()).collect();
11955            return Err(left_behind(error, &left));
11956        }
11957        let created: Vec<NativeId> = landed
11958            .iter()
11959            .map(|landed| landed.content_id.clone())
11960            .collect();
11961        let mut ids = Vec::with_capacity(landed.len());
11962        for ((incoming, prepared), landed) in incomings.iter().zip(prepared).zip(landed) {
11963            match self.complete_write(incoming, prepared, landed).await {
11964                Ok(written) => ids.push(written.id),
11965                // 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.
11966                Err(error) => {
11967                    let ids: Vec<&NativeId> = created.iter().collect();
11968                    let left = self.delete_issues(&ids).await;
11969                    let left: Vec<&str> = left.iter().map(|id| id.0.as_str()).collect();
11970                    return Err(left_behind(error, &left));
11971                }
11972            }
11973        }
11974        Ok(ids)
11975    }
11976
11977    /// Hold back the update of the existing issue `issue` — `members`, what its own
11978    /// [`graphql::UPDATE_ISSUE`] would send beside its id — while writes are being held back — so the updates a copy makes one after
11979    /// another go to GitHub as one request. Whatever this source held of the issue is dropped
11980    /// as the mutation itself would drop it. Answers whether it was held: never while a write
11981    /// the store's cache expects runs, which records each mutation's own answer, and never for
11982    /// an issue an update is already held for, which that one is sent ahead of.
11983    fn hold_update(&self, issue: &NativeId, members: &Value) -> Result<bool, SourceError> {
11984        if self.expected.journaling() || self.deferred()?.is_none() {
11985            return Ok(false);
11986        }
11987        let mut held = self
11988            .held_updates
11989            .lock()
11990            .map_err(|_| SourceError::Unavailable {
11991                message: "issue updates held back were left inconsistent; run the command again"
11992                    .into(),
11993            })?;
11994        if held.iter().any(|earlier| earlier.issue == *issue) {
11995            return Ok(false);
11996        }
11997        let named = |value: &str| issue.0 == value;
11998        self.resolved_cache()?
11999            .retain(|id, item| !named(&id.0) && !named(&item.item_id));
12000        self.read_ahead()?.retain(|id, item| {
12001            !named(&id.0) && !item.as_ref().is_some_and(|item| named(&item.item_id))
12002        });
12003        self.carried()?
12004            .retain(|id, item| !named(&id.0) && !named(&item.item_id));
12005        held.push(HeldUpdate::new(issue, members));
12006        Ok(true)
12007    }
12008
12009    /// Send every update [`Self::hold_update`] held back: one alone as [`graphql::UPDATE_ISSUE`]
12010    /// sends it, several as aliased `updateIssue`s of [`graphql::UPDATE_ISSUES`],
12011    /// [`MUTATION_BATCH`] to a request. Each counts one write, as it would alone.
12012    async fn send_held_updates(&self) -> Result<(), SourceError> {
12013        let held = std::mem::take(&mut *self.held_updates.lock().map_err(|_| {
12014            SourceError::Unavailable {
12015                message: "issue updates held back were left inconsistent; run the command again"
12016                    .into(),
12017            }
12018        })?);
12019        if let [one] = held.as_slice() {
12020            return self
12021                .send_update(
12022                    graphql::UPDATE_ISSUE,
12023                    "/updateIssue/issue",
12024                    &one.issue,
12025                    one.input.clone(),
12026                )
12027                .await;
12028        }
12029        for chunk in held.chunks(MUTATION_BATCH) {
12030            let mut variables = serde_json::Map::new();
12031            for slot in 0..MUTATION_BATCH {
12032                variables.insert(
12033                    format!("update{slot}"),
12034                    chunk.get(slot).unwrap_or(&chunk[0]).input.clone(),
12035                );
12036                variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12037            }
12038            let data = match self
12039                .graphql(graphql::UPDATE_ISSUES, Value::Object(variables))
12040                .await
12041            {
12042                Ok(data) => data,
12043                Err(error) => {
12044                    for held in chunk {
12045                        self.forget_people(&held.input);
12046                    }
12047                    return Err(error);
12048                }
12049            };
12050            let inputs: Vec<&Value> = chunk.iter().map(|held| &held.input).collect();
12051            check_aliased_answers(
12052                graphql::UPDATE_ISSUES,
12053                &data,
12054                "update",
12055                &inputs,
12056                &[("issue", "id")],
12057            )?;
12058            for (slot, held) in chunk.iter().enumerate() {
12059                self.assigned_as_asked(&held.input, data.pointer(&format!("/update{slot}/issue")))?;
12060            }
12061        }
12062        Ok(())
12063    }
12064
12065    /// Send everything held back since [`TaskSource::begin_deferred_writes`]: one read of the
12066    /// created items' board items, then their field values and edges together in requests of
12067    /// [`WRITE_BATCH`], then their closes in requests of [`MUTATION_BATCH`]. Anything refused
12068    /// takes back every issue held, [`DELETE_BATCH`] to a request, and answers the refusal.
12069    async fn send_held_back(&self) -> Result<(), SourceError> {
12070        let Some(Deferred::Held { board, created }) = self.deferred()?.take() else {
12071            return Ok(());
12072        };
12073        if created.is_empty() {
12074            return Ok(());
12075        }
12076        let sent = self.send_deferred(board.as_str(), &created).await;
12077        if let Err(error) = sent {
12078            // Best effort, and the failure is what the caller is told, as a write of one item
12079            // that fails part way takes back what it created: the copy that held these back
12080            // journalled every one, so one this cannot take back its undo tries again, and says
12081            // so when it cannot either.
12082            let ids: Vec<&NativeId> = created.iter().map(|held| &held.content).collect();
12083            let _ = self.delete_issues(&ids).await;
12084            return Err(error);
12085        }
12086        Ok(())
12087    }
12088
12089    /// The requests [`Self::send_held_back`] makes.
12090    async fn send_deferred(&self, board: &str, created: &[HeldBack]) -> Result<(), SourceError> {
12091        let items = self.created_board_items(board, created).await?;
12092        let mut fields: Vec<Value> = Vec::new();
12093        let mut closes: Vec<Value> = Vec::new();
12094        let mut edges: Vec<Value> = Vec::new();
12095        for held in created {
12096            let (item, status) = &items[&held.content];
12097            let mut values = held.fields.clone();
12098            // A status the board already shows — set by a workflow a person turned on to file
12099            // new items at it — is not written again.
12100            if let Some((field, option, name)) = &held.status
12101                && status.as_deref() != Some(name.as_str())
12102            {
12103                values.insert(0, (field.clone(), json!({"singleSelectOptionId": option})));
12104            }
12105            for (field, value) in values {
12106                fields.push(json!({"projectId":board,"itemId":item,"fieldId":field,"value":value}));
12107            }
12108            if let Some(reason) = held.close {
12109                closes.push(json!({"id": held.content.0, "stateInput": closed_input(reason)}));
12110            }
12111            for far in &held.edges {
12112                edges.push(json!({"issueId": held.content.0, "blockingIssueId": far.0}));
12113            }
12114            if !held.clears.is_empty() {
12115                let clears: Vec<&str> = held.clears.iter().map(String::as_str).collect();
12116                self.set_item_fields(board, item, &[], &clears).await?;
12117            }
12118        }
12119        // Each alias answers with what it wrote, which is what its input named: the board item a
12120        // field value is set on, the issue closed, the issue blocked and the one blocking it.
12121        let field_answer: &[(&str, &str)] = &[("projectV2Item", "itemId")];
12122        let close_answer: &[(&str, &str)] = &[("issue", "id")];
12123        let block_answer: &[(&str, &str)] =
12124            &[("issue", "issueId"), ("blockingIssue", "blockingIssueId")];
12125        // Every field value, then every edge, as one ordered list sent `WRITE_BATCH` aliases to a
12126        // request: a request holding both kinds is the one document carrying both, so a plan's
12127        // values and edges cost one request where they fit in one.
12128        let writes: Vec<HeldWrite<'_>> = fields
12129            .iter()
12130            .map(HeldWrite::Field)
12131            .chain(edges.iter().map(HeldWrite::Edge))
12132            .collect();
12133        for chunk in writes.chunks(WRITE_BATCH) {
12134            let values: Vec<&Value> = chunk
12135                .iter()
12136                .filter_map(|write| match write {
12137                    HeldWrite::Field(input) => Some(*input),
12138                    HeldWrite::Edge(_) => None,
12139                })
12140                .collect();
12141            let blocks: Vec<&Value> = chunk
12142                .iter()
12143                .filter_map(|write| match write {
12144                    HeldWrite::Edge(input) => Some(*input),
12145                    HeldWrite::Field(_) => None,
12146                })
12147                .collect();
12148            let (document, sends) = match (values.is_empty(), blocks.is_empty()) {
12149                (false, false) => (graphql::WRITE_FIELDS_AND_EDGES, ["sendField", "sendBlock"]),
12150                (false, true) => (graphql::WRITE_FIELD_VALUES, ["send", "send"]),
12151                _ => (graphql::ADD_BLOCKED_BYS, ["send", "send"]),
12152            };
12153            let mut variables = serde_json::Map::new();
12154            let kinds = [
12155                ("field", &values, sends[0], field_answer),
12156                ("block", &blocks, sends[1], block_answer),
12157            ];
12158            for (prefix, inputs, send, _) in &kinds {
12159                if inputs.is_empty() {
12160                    continue;
12161                }
12162                for slot in 0..WRITE_BATCH {
12163                    variables.insert(
12164                        format!("{prefix}{slot}"),
12165                        (*inputs.get(slot).unwrap_or(&inputs[0])).clone(),
12166                    );
12167                    variables.insert(format!("{send}{slot}"), json!(slot < inputs.len()));
12168                }
12169            }
12170            let data = self.graphql(document, Value::Object(variables)).await?;
12171            for (prefix, inputs, _, answers) in kinds {
12172                check_aliased_answers(document, &data, prefix, inputs, answers)?;
12173            }
12174        }
12175        for chunk in closes.chunks(MUTATION_BATCH) {
12176            let mut variables = serde_json::Map::new();
12177            for slot in 0..MUTATION_BATCH {
12178                variables.insert(
12179                    format!("close{slot}"),
12180                    chunk.get(slot).cloned().unwrap_or_else(|| chunk[0].clone()),
12181                );
12182                variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12183            }
12184            let data = self
12185                .graphql(graphql::CLOSE_ISSUES, Value::Object(variables))
12186                .await?;
12187            let inputs: Vec<&Value> = chunk.iter().collect();
12188            check_aliased_answers(graphql::CLOSE_ISSUES, &data, "close", &inputs, close_answer)?;
12189        }
12190        for held in created {
12191            self.learn_item(&held.content, &items[&held.content].0)?;
12192        }
12193        Ok(())
12194    }
12195
12196    /// The board item each of `created` is on this board, with its `Status` as the board set it:
12197    /// [`graphql::CREATED_BOARD_ITEMS`], read again — after a wait of a second, then two, four,
12198    /// eight and sixteen — for only those GitHub has not filed yet.
12199    ///
12200    /// **Membership is never assumed.** `createIssue`'s `projectV2Ids` files an issue some time
12201    /// after GitHub answered the create — the feasibility spike saw 0.45 to 1.84 seconds, and no
12202    /// create answer carrying the item — so only a read says it is there. One still absent once
12203    /// those reads are spent is filed with [`graphql::ADD_TO_BOARD`], one write each; GitHub
12204    /// filing it meanwhile refuses that "Content already exists in this project", which says it
12205    /// is placed, and one more read finds the item rather than a second one being made.
12206    async fn created_board_items(
12207        &self,
12208        board: &str,
12209        created: &[HeldBack],
12210    ) -> Result<BTreeMap<NativeId, (String, Option<String>)>, SourceError> {
12211        let mut found: BTreeMap<NativeId, (String, Option<String>)> = BTreeMap::new();
12212        let unfiled = |found: &BTreeMap<NativeId, (String, Option<String>)>| -> Vec<NativeId> {
12213            created
12214                .iter()
12215                .map(|held| held.content.clone())
12216                .filter(|id| !found.contains_key(id))
12217                .collect()
12218        };
12219        let mut wait = Duration::from_secs(1);
12220        for attempt in 0..6 {
12221            let absent = unfiled(&found);
12222            if absent.is_empty() {
12223                return Ok(found);
12224            }
12225            if attempt > 0 {
12226                self.clock
12227                    .sleep_because(wait, pacing::cause::BOARD_FILING)
12228                    .await;
12229                wait = wait.saturating_mul(2);
12230            }
12231            self.read_created_items(board, &absent, &mut found).await?;
12232        }
12233        let mut placed_meanwhile = Vec::new();
12234        for id in unfiled(&found) {
12235            match self
12236                .graphql(
12237                    graphql::ADD_TO_BOARD,
12238                    json!({"input":{"projectId":board,"contentId":id.0}}),
12239                )
12240                .await
12241            {
12242                Ok(added) => {
12243                    let item = added
12244                        .pointer("/addProjectV2ItemById/item")
12245                        .filter(|value| !value.is_null())
12246                        .ok_or_else(|| SourceError::Malformed {
12247                            message: "GitHub board addition returned no project item".into(),
12248                        })?;
12249                    found.insert(id, (required_nonblank_str(item, "id")?.to_owned(), None));
12250                }
12251                Err(error) if already_on_the_board(&error) => placed_meanwhile.push(id),
12252                Err(error) => return Err(error),
12253            }
12254        }
12255        if !placed_meanwhile.is_empty() {
12256            self.read_created_items(board, &placed_meanwhile, &mut found)
12257                .await?;
12258        }
12259        let absent = unfiled(&found);
12260        if absent.is_empty() {
12261            return Ok(found);
12262        }
12263        let absent: Vec<&str> = absent.iter().map(|id| id.0.as_str()).collect();
12264        Err(SourceError::Unavailable {
12265            message: format!(
12266                "GitHub created {} filed on board {board} and, after 31 seconds and adding {} \
12267                 to it, still answers {} on no item of it: {}; next: run the copy again once \
12268                 GitHub has caught up",
12269                if absent.len() == 1 {
12270                    "an issue"
12271                } else {
12272                    "issues"
12273                },
12274                if absent.len() == 1 { "it" } else { "them" },
12275                if absent.len() == 1 { "it" } else { "them" },
12276                absent.join(", ")
12277            ),
12278        })
12279    }
12280
12281    /// One [`graphql::CREATED_BOARD_ITEMS`] read of each of `ids`, [`COPY_DETAIL_BATCH`] to a
12282    /// request, adding to `found` the board item of every one GitHub has filed on `board`.
12283    async fn read_created_items(
12284        &self,
12285        board: &str,
12286        ids: &[NativeId],
12287        found: &mut BTreeMap<NativeId, (String, Option<String>)>,
12288    ) -> Result<(), SourceError> {
12289        for chunk in ids.chunks(COPY_DETAIL_BATCH) {
12290            let mut variables = serde_json::Map::new();
12291            for slot in 0..COPY_DETAIL_BATCH {
12292                variables.insert(
12293                    format!("id{slot}"),
12294                    json!(chunk.get(slot).unwrap_or(&chunk[0]).0),
12295                );
12296                variables.insert(format!("read{slot}"), json!(slot < chunk.len()));
12297            }
12298            variables.insert("boardItems".into(), json!(BOARD_ITEMS_PAGE_SIZE));
12299            variables.insert("statusName".into(), json!(STATUS_FIELD));
12300            let data = self
12301                .graphql(graphql::CREATED_BOARD_ITEMS, Value::Object(variables))
12302                .await?;
12303            for (slot, id) in chunk.iter().enumerate() {
12304                // An answer for another issue than the one asked about says nothing of
12305                // where that one is filed, and its board item is not this one's.
12306                let node = data.get(format!("i{slot}")).filter(|node| !node.is_null());
12307                let named = node.map(|node| node.get("id").and_then(Value::as_str));
12308                if let Some(named) = named
12309                    && named != Some(id.0.as_str())
12310                {
12311                    return Err(SourceError::Malformed {
12312                        message: format!(
12313                            "GitHub answered the board items of {} when asked for those of {}",
12314                            named.unwrap_or("an issue it did not name"),
12315                            id.0
12316                        ),
12317                    });
12318                }
12319                // An issue GitHub does not answer yet is not filed yet; one it answers is
12320                // read whole, its connection, each board item's board and its status, and
12321                // any of them unreadable is refused rather than read as not filed.
12322                let Some(node) = node else { continue };
12323                let malformed = |what: &str| SourceError::Malformed {
12324                    message: format!("GitHub answered the board items of {} with {what}", id.0),
12325                };
12326                let nodes = node
12327                    .pointer("/projectItems/nodes")
12328                    .and_then(Value::as_array)
12329                    .ok_or_else(|| malformed("no list of board items"))?;
12330                let mut item = None;
12331                for node in nodes {
12332                    let on = node
12333                        .pointer("/project/id")
12334                        .and_then(Value::as_str)
12335                        .ok_or_else(|| malformed("a board item naming no board"))?;
12336                    if on == board {
12337                        item = Some(node);
12338                    }
12339                }
12340                if let Some(item) = item {
12341                    let status = match item.get("status") {
12342                        None | Some(Value::Null) => None,
12343                        Some(status) => Some(
12344                            status
12345                                .get("name")
12346                                .and_then(Value::as_str)
12347                                .ok_or_else(|| malformed("a status that names no option"))?
12348                                .to_owned(),
12349                        ),
12350                    };
12351                    found.insert(
12352                        id.clone(),
12353                        (required_nonblank_str(item, "id")?.to_owned(), status),
12354                    );
12355                }
12356            }
12357        }
12358        Ok(())
12359    }
12360
12361    /// The board item id of `content`, which this process created and remembered without one,
12362    /// in every half of its own view.
12363    fn learn_item(&self, content: &NativeId, item: &str) -> Result<(), SourceError> {
12364        if let Some(held) = self.resolved_cache()?.get_mut(content) {
12365            held.item_id = item.to_owned();
12366        }
12367        if let Some(held) = self.created()?.iter_mut().find(|held| held.id == *content) {
12368            held.item_id = item.to_owned();
12369        }
12370        Ok(())
12371    }
12372
12373    /// Ask together which items each of `origins` names, and what creating an item reads; see
12374    /// [`TaskSource::read_ahead_origins_for_copy`]. An origin whose answer runs past its first
12375    /// page is left to its own lookup.
12376    async fn origins_ahead(&self, origins: &[String]) -> Result<(), SourceError> {
12377        if self.repository.is_none() {
12378            return Ok(());
12379        }
12380        let unasked: Vec<&String> = {
12381            let held = self.narrowed_cache()?;
12382            let mut unasked: Vec<&String> = Vec::new();
12383            for origin in origins {
12384                if !held.contains_key(&Narrowing::Origin(origin.clone()).key())
12385                    && !unasked.contains(&origin)
12386                {
12387                    unasked.push(origin);
12388                }
12389            }
12390            unasked
12391        };
12392        if unasked.is_empty() {
12393            return Ok(());
12394        }
12395        // One batch is held back for the read ahead that follows, which may carry a project's
12396        // members beside it in the same request.
12397        if unasked.len() <= ORIGIN_BATCH {
12398            let mut pending =
12399                self.pending_origins
12400                    .lock()
12401                    .map_err(|_| SourceError::Unavailable {
12402                        message:
12403                            "origins held for a read ahead were left inconsistent; run the command \
12404                          again"
12405                                .into(),
12406                    })?;
12407            for origin in unasked {
12408                if !pending.contains(origin) {
12409                    pending.push(origin.clone());
12410                }
12411            }
12412            return Ok(());
12413        }
12414        let unasked: Vec<String> = unasked.into_iter().cloned().collect();
12415        self.send_origin_lookups(&unasked, None).await
12416    }
12417
12418    /// Hold, for [`TaskSource::member_classifications`] of `project`, each member's
12419    /// classification and repositories as the members page `data` carries them — when that page
12420    /// is every member, each one names `project` as its parent, and every record it holds is
12421    /// readable. Any other page holds nothing, so the members are read as they always were.
12422    fn hold_member_classes(&self, project: &NativeId, data: &Value) -> Result<(), SourceError> {
12423        let Some(page) = data
12424            .pointer("/members/subIssues")
12425            .filter(|page| !page.is_null())
12426        else {
12427            return Ok(());
12428        };
12429        if page
12430            .pointer("/pageInfo/hasNextPage")
12431            .and_then(Value::as_bool)
12432            != Some(false)
12433        {
12434            return Ok(());
12435        }
12436        let Some(nodes) = page.get("nodes").and_then(Value::as_array) else {
12437            return Ok(());
12438        };
12439        let mut members = Vec::with_capacity(nodes.len());
12440        for node in nodes {
12441            if node.pointer("/parent/id").and_then(Value::as_str) != Some(project.0.as_str()) {
12442                return Ok(());
12443            }
12444            let Some(body) = node.get("body").and_then(Value::as_str) else {
12445                return Ok(());
12446            };
12447            // Every node here is filed under `project`, which `BoardKind::of` reads as one of its
12448            // tasks whatever its marker says, so each is a member the full read would classify.
12449            let Ok((_, slot)) = metadata_body(Some(body.to_owned())) else {
12450                return Ok(());
12451            };
12452            let Ok(classification) = Classification::from_metadata(&slot) else {
12453                return Ok(());
12454            };
12455            let repositories = if slot.contains_key(Repository::METADATA_KEY) {
12456                let Ok(repositories) = Repository::from_metadata(&slot) else {
12457                    return Ok(());
12458                };
12459                repositories
12460            } else {
12461                let Some(origin) = node
12462                    .pointer("/repository/nameWithOwner")
12463                    .and_then(Value::as_str)
12464                else {
12465                    return Ok(());
12466                };
12467                let Ok(own) = Repository::try_from(format!("{}/{origin}", RepositoryTarget::HOST))
12468                else {
12469                    return Ok(());
12470                };
12471                vec![own]
12472            };
12473            members.push((classification, repositories));
12474        }
12475        self.member_classes
12476            .lock()
12477            .map_err(|_| SourceError::Unavailable {
12478                message: "a project's members held for its classification were left \
12479                          inconsistent; run the command again"
12480                    .into(),
12481            })?
12482            .insert(project.clone(), members);
12483        Ok(())
12484    }
12485
12486    /// Send every origin held back for the read ahead, beside the members of `members` when it
12487    /// names a project — or nothing, when none is held.
12488    async fn send_pending_origins(&self, members: Option<&NativeId>) -> Result<(), SourceError> {
12489        let pending = std::mem::take(&mut *self.pending_origins.lock().map_err(|_| {
12490            SourceError::Unavailable {
12491                message: "origins held for a read ahead were left inconsistent; run the command \
12492                          again"
12493                    .into(),
12494            }
12495        })?);
12496        if pending.is_empty() {
12497            return Ok(());
12498        }
12499        self.send_origin_lookups(&pending, members).await
12500    }
12501
12502    /// [`graphql::ORIGIN_LOOKUPS`] of `unasked`, [`ORIGIN_BATCH`] to a request — the first one
12503    /// [`graphql::ORIGIN_LOOKUPS_WITH_MEMBERS`], carrying the members of `members`, when it names
12504    /// a project — holding each origin's answer and, from a members page that is the whole of
12505    /// them, each member's classification.
12506    async fn send_origin_lookups(
12507        &self,
12508        unasked: &[String],
12509        members: Option<&NativeId>,
12510    ) -> Result<(), SourceError> {
12511        let Some(repository) = self.repository.clone() else {
12512            return Ok(());
12513        };
12514        let mut members = members;
12515        for chunk in unasked.chunks(ORIGIN_BATCH) {
12516            let mut variables = json!({"owner":self.owner,"number":self.project_number,
12517                "type":"ISSUE","lookupFirst":ORIGIN_LOOKUPS_PAGE_SIZE,"nestedFirst":NESTED_PAGE_SIZE,
12518                "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true,
12519                "repositoryOwner":repository.owner,"repositoryName":repository.name});
12520            for slot in 0..ORIGIN_BATCH {
12521                let origin = chunk.get(slot).unwrap_or(&chunk[0]);
12522                variables[format!("filter{slot}")] =
12523                    json!(format!("{ORIGIN_FIELD}:{}", quoted(origin)));
12524                variables[format!("search{slot}")] = json!(
12525                    self.board_search(Some(&format!("in:body {}", quoted(&as_stored(origin)))))
12526                );
12527                variables[format!("ask{slot}")] = json!(slot < chunk.len());
12528            }
12529            let project = members.take();
12530            let document = match project {
12531                Some(project) => {
12532                    variables["project"] = json!(project.0);
12533                    variables["memberFirst"] = json!(MEMBER_PAGE_SIZE);
12534                    graphql::ORIGIN_LOOKUPS_WITH_MEMBERS
12535                }
12536                None => graphql::ORIGIN_LOOKUPS,
12537            };
12538            let data = self.graphql(document, variables).await?;
12539            self.fields_read(&data)?;
12540            if let Some(project) = project {
12541                self.hold_member_classes(project, &data)?;
12542            }
12543            if let Some(node) = data.get("repository").filter(|value| !value.is_null()) {
12544                let id = required_nonblank_str(node, "id")?.to_owned();
12545                self.repository_cache()?.insert(repository.clone(), id);
12546                if let Some(numeric) = node
12547                    .get("databaseId")
12548                    .and_then(Value::as_u64)
12549                    .and_then(std::num::NonZeroU64::new)
12550                {
12551                    self.numeric_repositories
12552                        .lock()
12553                        .await
12554                        .insert(repository.clone(), numeric);
12555                }
12556            }
12557            for (slot, origin) in chunk.iter().enumerate() {
12558                let items = data
12559                    .pointer(&format!("/o{slot}/projectV2/items"))
12560                    .filter(|value| !value.is_null())
12561                    .ok_or_else(|| SourceError::Refused {
12562                        message: format!(
12563                            "GitHub project {}/{} was not found or is not visible to the token",
12564                            self.owner, self.project_number
12565                        ),
12566                    })?;
12567                let searched =
12568                    data.get(format!("s{slot}"))
12569                        .ok_or_else(|| SourceError::Malformed {
12570                            message: "GitHub search response has no search connection".into(),
12571                        })?;
12572                if resumed(items, None)?.has_more() || resumed(searched, None)?.has_more() {
12573                    continue;
12574                }
12575                let mut found: Vec<Resolved> = Vec::new();
12576                for item in optional_nodes(Some(items), "project items")?
12577                    .into_iter()
12578                    .flatten()
12579                {
12580                    if let Some(resolved) = self.resolve(item)?
12581                        && resolved.content_kind == ContentKind::Issue
12582                        && !found.iter().any(|held| held.id == resolved.id)
12583                    {
12584                        found.push(resolved);
12585                    }
12586                }
12587                for node in optional_nodes(Some(searched), "search")?
12588                    .into_iter()
12589                    .flatten()
12590                {
12591                    if let Some(resolved) = self.resolve_issue(node).await?
12592                        && !found.iter().any(|held| held.id == resolved.id)
12593                    {
12594                        found.push(resolved);
12595                    }
12596                }
12597                self.narrowed_cache()?
12598                    .insert(Narrowing::Origin((*origin).clone()).key(), found);
12599            }
12600        }
12601        Ok(())
12602    }
12603
12604    /// Delete every issue of `ids`, [`DELETE_BATCH`] to a request with
12605    /// [`graphql::DELETE_ISSUES`], and answer those still there: each a request's answer does not
12606    /// confirm, every one of a request refused whole included.
12607    async fn delete_issues(&self, ids: &[&NativeId]) -> Vec<NativeId> {
12608        let mut left = Vec::new();
12609        for chunk in ids.chunks(DELETE_BATCH) {
12610            let mut variables = serde_json::Map::new();
12611            for slot in 0..DELETE_BATCH {
12612                let id = chunk.get(slot).unwrap_or(&chunk[0]);
12613                variables.insert(format!("delete{slot}"), json!({"issueId": id.0}));
12614                variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12615            }
12616            let data = self
12617                .graphql(graphql::DELETE_ISSUES, Value::Object(variables))
12618                .await
12619                .unwrap_or(Value::Null);
12620            for (slot, id) in chunk.iter().enumerate() {
12621                // Confirmed only by the repository the deleted issue was in, named by a
12622                // non-blank id: anything else says nothing of whether the issue is gone.
12623                let confirmed = data
12624                    .pointer(&format!("/delete{slot}/repository/id"))
12625                    .and_then(Value::as_str)
12626                    .is_some_and(|id| !id.trim().is_empty());
12627                if !confirmed {
12628                    left.push((*id).clone());
12629                }
12630            }
12631        }
12632        left
12633    }
12634
12635    /// Delete one issue, which takes its board item with it.
12636    async fn delete_issue(&self, id: &NativeId) -> Result<(), SourceError> {
12637        let data = self
12638            .graphql(graphql::DELETE_ISSUE, json!({"input":{"issueId":id.0}}))
12639            .await?;
12640        data.pointer("/deleteIssue/repository")
12641            .filter(|value| !value.is_null())
12642            .ok_or_else(|| SourceError::Malformed {
12643                message: "GitHub issue deletion returned no repository".into(),
12644            })?;
12645        self.forget(id)?;
12646        Ok(())
12647    }
12648
12649    /// Remove one item this copy created, so a copy that could not finish leaves the board
12650    /// as it found it.
12651    ///
12652    /// Deleting the issue takes its board item with it, so there is no second mutation to
12653    /// keep in step. An id the board does not hold is not an error: the item is already
12654    /// gone, which is the state this asks for. Which that is, is decided by reading the item
12655    /// by its own id — a listing of the board can still be missing an item it holds, and
12656    /// reading that as *already gone* would leave behind the very item this was asked to
12657    /// take back.
12658    async fn delete_item(&self, id: &NativeId) -> Result<(), SourceError> {
12659        let Some(item) = self.bound_item(id).await? else {
12660            return Ok(());
12661        };
12662        if item.content_kind == ContentKind::DraftIssue {
12663            return Err(SourceError::Refused {
12664                message: format!(
12665                    "GitHub item {} is a draft, and this source removes an item by deleting \
12666                     its issue; next: remove it from the board by hand",
12667                    id.0
12668                ),
12669            });
12670        }
12671        let data = self
12672            .graphql(graphql::DELETE_ISSUE, json!({"input":{"issueId":id.0}}))
12673            .await?;
12674        data.pointer("/deleteIssue/repository")
12675            .filter(|value| !value.is_null())
12676            .ok_or_else(|| SourceError::Malformed {
12677                message: "GitHub issue deletion returned no repository".into(),
12678            })?;
12679        self.forget(id)?;
12680        Ok(())
12681    }
12682
12683    /// The issue a comment call on `task` is about, or `None` when this board holds no such
12684    /// task.
12685    ///
12686    /// Resolved exactly as [`TaskSource::get_task`] resolves it, so the comment verbs and a
12687    /// read of the task cannot disagree about which ids name one: a project or a document of
12688    /// this board is not a task here either.
12689    ///
12690    /// A **draft** is a task with nowhere to keep a comment, because GitHub keeps comments on
12691    /// issues and a draft is not one. It is refused rather than answered with an empty page,
12692    /// which would read as a task nobody has commented on yet.
12693    async fn commented_issue(&self, task: &NativeId) -> Result<Option<NativeId>, SourceError> {
12694        let cached = self.resolved_cache()?.get(task).cloned();
12695        let Some(item) = (match cached {
12696            Some(item) => Some(item),
12697            None => self.item_by_id(task).await?,
12698        })
12699        .filter(|item| item.kind == BoardKind::Work(ItemKind::Task)) else {
12700            return Ok(None);
12701        };
12702        if item.content_kind == ContentKind::DraftIssue {
12703            return Err(self.draft_has_no_comments(task));
12704        }
12705        Ok(Some(item.id))
12706    }
12707
12708    /// The refusal a comment call on a board draft is answered with: GitHub keeps comments on
12709    /// issues, and a draft is not one.
12710    fn draft_has_no_comments(&self, task: &NativeId) -> SourceError {
12711        SourceError::Refused {
12712            message: format!(
12713                "task {} of source {} is a draft item on the board, and GitHub keeps \
12714                 comments on issues alone, so a draft has none to read or write; next: \
12715                 convert the draft to an issue on the board, then comment on the issue it \
12716                 becomes",
12717                task.0, self.name
12718            ),
12719        }
12720    }
12721
12722    /// One task and a page of its comments, read with [`graphql::ISSUE_DETAIL`] in one
12723    /// request — or `None` when this board holds no task by that id.
12724    ///
12725    /// What `task show` and a comment listing read. A draft is a task with no comments, so it
12726    /// is answered with the draft and the refusal, at the price of the draft's own read.
12727    async fn issue_detail(
12728        &self,
12729        id: &NativeId,
12730        page: &PageRequest,
12731    ) -> Result<Option<TaskDetailRead>, SourceError> {
12732        let after = page.cursor.as_ref().map(|cursor| cursor.0.as_str());
12733        let asked = self
12734            .graphql(
12735                graphql::ISSUE_DETAIL,
12736                json!({"id":id.0,"first":page.limit.min(MAX_PAGE_SIZE),"after":after,
12737                       "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
12738                       "duplicates":true}),
12739            )
12740            .await;
12741        let data = match asked {
12742            Ok(data) => data,
12743            Err(error) if unresolvable_node(&error) => return Ok(None),
12744            Err(error) => return Err(error),
12745        };
12746        // `node` is null for an id that names nothing, and absent only from an answer this
12747        // source cannot read — never the same thing.
12748        let node = data.get("node").ok_or_else(|| SourceError::Malformed {
12749            message: format!("GitHub answered the read of {} with no node", id.0),
12750        })?;
12751        self.detail_of(id, node, true, after).await
12752    }
12753
12754    /// Several tasks, each with the first page of its comments when `comments` is set, read
12755    /// [`DETAIL_BATCH`] at a time with [`graphql::ISSUE_DETAILS`] — one answer per id, in
12756    /// order.
12757    ///
12758    /// A batch GitHub refuses because one of its ids resolves to no node at all is read again
12759    /// one item at a time, so that id is answered as missing and the others as themselves; any
12760    /// other refusal is every id of that batch's answer.
12761    async fn issue_details(
12762        &self,
12763        ids: &[NativeId],
12764        comments: Option<&PageRequest>,
12765    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
12766        let mut read = Vec::with_capacity(ids.len());
12767        for batch in ids.chunks(DETAIL_BATCH) {
12768            match self
12769                .graphql(graphql::ISSUE_DETAILS, detail_batch(batch, comments))
12770                .await
12771            {
12772                Ok(data) => {
12773                    for (slot, id) in batch.iter().enumerate() {
12774                        // Every alias asked for is answered, null for an id naming nothing;
12775                        // one missing is an answer this source cannot read.
12776                        let read_one = match data.get(format!("i{slot}")) {
12777                            Some(node) => self.detail_of(id, node, comments.is_some(), None).await,
12778                            None => Err(SourceError::Malformed {
12779                                message: format!(
12780                                    "GitHub answered a batch read with no item for {}",
12781                                    id.0
12782                                ),
12783                            }),
12784                        };
12785                        read.push(read_one);
12786                    }
12787                }
12788                Err(error) if unresolvable_node(&error) => {
12789                    for id in batch {
12790                        read.push(match comments {
12791                            Some(page) => self.issue_detail(id, page).await,
12792                            None => self.task_read(id).await,
12793                        });
12794                    }
12795                }
12796                Err(error) => read.extend(batch.iter().map(|_| Err(error.clone()))),
12797            }
12798        }
12799        read
12800    }
12801
12802    /// One task and nothing of its comments, as [`TaskSource::get_task`] reads it.
12803    async fn task_read(&self, id: &NativeId) -> Result<Option<TaskDetailRead>, SourceError> {
12804        Ok(self.get_task(id).await?.map(|task| TaskDetailRead {
12805            task,
12806            comments: None,
12807        }))
12808    }
12809
12810    /// What one node a detail read reached says: the task this board holds by `id`, with the
12811    /// page of comments the node carries when `commented` — or `None` for a node that is no
12812    /// task of this board.
12813    ///
12814    /// Resolved as [`Self::item_by_id`] resolves an item: a draft is read again as a draft,
12815    /// and an item this process created answers from this process's own record, which a node
12816    /// read taken moments after the write can still be behind.
12817    async fn detail_of(
12818        &self,
12819        id: &NativeId,
12820        node: &Value,
12821        commented: bool,
12822        after: Option<&str>,
12823    ) -> Result<Option<TaskDetailRead>, SourceError> {
12824        if node.is_null() {
12825            return Ok(None);
12826        }
12827        let draft = optional_str(node, "__typename")? == Some("DraftIssue");
12828        // An issue answered under one id is that id's, or the answer is not one this source
12829        // can report: reporting another issue's task and comments under the qualified id asked
12830        // for would be the one wrong answer here. A draft's own read checks the same.
12831        if !draft
12832            && optional_str(node, "__typename")? == Some("Issue")
12833            && required_str(node, "id")? != id.0
12834        {
12835            return Err(SourceError::Malformed {
12836                message: format!(
12837                    "GitHub answered the read of {} with issue {}",
12838                    id.0,
12839                    required_str(node, "id")?
12840                ),
12841            });
12842        }
12843        let item = if draft {
12844            self.draft_by_id(id).await?
12845        } else {
12846            self.resolve_issue(node).await?
12847        };
12848        // A read that carried the whole of what the issue is blocked by — a copy's — is kept
12849        // for this command, so the dependency read the copy makes next is answered from it.
12850        if let Some(read) = item.as_ref().filter(|item| item.blocked_by.is_some()) {
12851            self.resolved_cache()?.insert(read.id.clone(), read.clone());
12852        }
12853        let Some(item) = item.filter(|item| item.kind == BoardKind::Work(ItemKind::Task)) else {
12854            return Ok(None);
12855        };
12856        let own = self.created()?.iter().find(|own| own.id == *id).cloned();
12857        let task = own.unwrap_or(item).task()?;
12858        let comments = match (commented, draft) {
12859            (false, _) => None,
12860            (true, true) => Some(Err(self.draft_has_no_comments(id))),
12861            (true, false) => Some(comment_page(node, &id.0, after).map(Some)),
12862        };
12863        if commented && !draft && after.is_none() {
12864            self.expected.learn_comments(id, node);
12865        }
12866        Ok(Some(TaskDetailRead { task, comments }))
12867    }
12868
12869    /// Whether the comment `comment` is one of `issue`'s own.
12870    ///
12871    /// Read before an edit or a removal is sent, because GitHub's comment mutations take the
12872    /// comment's id and nothing else: a comment id given against the wrong task would
12873    /// otherwise change a comment on some other issue entirely. An id that names nothing, or
12874    /// names something that is not an issue comment, is a comment this task does not have —
12875    /// which is what GitHub refusing to resolve it means too.
12876    async fn comment_is_on(
12877        &self,
12878        issue: &NativeId,
12879        comment: &NativeId,
12880    ) -> Result<bool, SourceError> {
12881        Ok(self.comment_on(issue, comment).await?.is_some())
12882    }
12883
12884    /// The body the comment `comment` holds, exactly as GitHub holds it, when it is one of
12885    /// `issue`'s own — the read [`Self::comment_is_on`] makes, answering with what it selected.
12886    async fn comment_on(
12887        &self,
12888        issue: &NativeId,
12889        comment: &NativeId,
12890    ) -> Result<Option<String>, SourceError> {
12891        // A write the store's cache expects knows which comments its issue held, and their
12892        // bodies, at the version it expects: what this read would answer.
12893        if let Some(primed) = self.expected.primed_comment(issue, comment) {
12894            return Ok(primed);
12895        }
12896        let asked = self
12897            .graphql(graphql::COMMENT_ISSUE, json!({"id":comment.0}))
12898            .await;
12899        let data = match asked {
12900            Ok(data) => data,
12901            Err(error) if unresolvable_node(&error) => return Ok(None),
12902            Err(error) => return Err(error),
12903        };
12904        let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
12905            return Ok(None);
12906        };
12907        if optional_str(node, "__typename")? != Some("IssueComment") {
12908            return Ok(None);
12909        }
12910        let on = node.get("issue").ok_or_else(|| SourceError::Malformed {
12911            message: format!("GitHub issue comment {} names no issue", comment.0),
12912        })?;
12913        if required_str(on, "id")? != issue.0 {
12914            return Ok(None);
12915        }
12916        Ok(Some(required_str(node, "body")?.to_owned()))
12917    }
12918
12919    /// Which far ends this item's own `blockedBy` relationship holds, and which it cannot.
12920    async fn partition_edges(
12921        &self,
12922        near_kind: BoardKind,
12923        near_content: ContentKind,
12924        carried: Option<&[Value]>,
12925        depends_on: &[DependencyEdge],
12926    ) -> Result<(Vec<String>, Vec<DependencyEdge>), SourceError> {
12927        let mut native = Vec::new();
12928        let mut fallback = Vec::new();
12929        let far_ends: Vec<(&DependencyEdge, &str, bool, Option<&Value>)> = depends_on
12930            .iter()
12931            .map(|edge| {
12932                // An opaque far end names another tracker, so it is never this board's own.
12933                let same_source = edge.to.designator().is_none()
12934                    && edge
12935                        .to
12936                        .source()
12937                        .is_none_or(|source| source == self.name.as_str());
12938                // A qualified id's source segment runs to its *first* colon — `GlobalId` and
12939                // `DependencyEndpoint::source` both read it that way — and a native id may hold
12940                // colons of its own, so the far end is everything after that one separator.
12941                // Splitting at the last would truncate `work:urn:task:7` to `7`.
12942                let far_id = if edge.to.is_qualified() {
12943                    edge.to
12944                        .id()
12945                        .split_once(':')
12946                        .map_or(edge.to.id(), |(_, native)| native)
12947                } else {
12948                    edge.to.id()
12949                };
12950                // One that already blocks the near issue was answered by that issue's own
12951                // read, which carried each of its blockers' kinds — an issue every one — so it
12952                // is not read again.
12953                let blocking = carried.and_then(|nodes| {
12954                    nodes
12955                        .iter()
12956                        .find(|node| node.get("id").and_then(Value::as_str) == Some(far_id))
12957                });
12958                (edge, far_id, same_source, blocking)
12959            })
12960            .collect();
12961        // Every other same-source far end is read by its own id, exactly as the item it is a
12962        // far end of is: whether this board holds it is that read's answer, never a listing's.
12963        // They are read together, [`DETAIL_BATCH`] to a request, rather than one each.
12964        let mut unread: Vec<NativeId> = Vec::new();
12965        for (_, far_id, same_source, blocking) in &far_ends {
12966            let id = NativeId((*far_id).to_owned());
12967            if *same_source && blocking.is_none() && !unread.contains(&id) {
12968                unread.push(id);
12969            }
12970        }
12971        let read: BTreeMap<NativeId, Option<Resolved>> = unread
12972            .iter()
12973            .cloned()
12974            .zip(self.items_by_ids(&unread).await?)
12975            .collect();
12976        for (edge, far_id, same_source, blocking) in far_ends {
12977            let far = match (same_source, blocking) {
12978                (false, _) => None,
12979                (true, Some(node)) => Some(FarEnd {
12980                    kind: if required_str(node, "title")?.starts_with(DESIGN_TITLE_PREFIX) {
12981                        BoardKind::Document
12982                    } else {
12983                        BoardKind::Work(related_kind(node, self.sub_issues)?)
12984                    },
12985                    content_kind: ContentKind::Issue,
12986                }),
12987                (true, None) => {
12988                    let read = read
12989                        .get(&NativeId(far_id.to_owned()))
12990                        .cloned()
12991                        .flatten()
12992                        .ok_or_else(|| SourceError::Refused {
12993                            message: format!("GitHub dependency item {far_id} was not found"),
12994                        })?;
12995                    Some(FarEnd {
12996                        kind: read.kind,
12997                        content_kind: read.content_kind,
12998                    })
12999                }
13000            };
13001            let far = far.as_ref();
13002            // The caller says which kind the far end is, and this board holds the far end
13003            // itself, so a disagreement is settled here rather than stored: recorded, the
13004            // wrong kind would read back as a cross-level edge that never existed; written
13005            // natively, it would name a relationship of a different level than the caller
13006            // asked for.
13007            //
13008            // A far end this board holds as a *document* fails the same comparison and is
13009            // refused by the same sentence: `ItemKind` has no document variant because
13010            // nothing may point at one, so no caller can name it correctly and the refusal
13011            // is the only honest answer.
13012            if let Some(disagreeing) = far.filter(|far| far.kind != BoardKind::Work(edge.to.kind)) {
13013                return Err(SourceError::Refused {
13014                    message: format!(
13015                        "GitHub dependency item {far_id} is a {} of this board, and this item \
13016                         names it as a {}; record the kind it is",
13017                        disagreeing.kind.describes(),
13018                        edge.to.kind.marker()
13019                    ),
13020                });
13021            }
13022            // A draft has neither `blockedBy` nor `blocking`, so no edge of one is native
13023            // however the far end is spelled — and one classified native here would be
13024            // written nowhere at all, because a draft's native reconciliation never runs.
13025            let native_here = near_content == ContentKind::Issue
13026                && far.is_some_and(|far| {
13027                    far.content_kind == ContentKind::Issue
13028                        && BoardKind::Work(edge.to.kind) == near_kind
13029                });
13030            if native_here {
13031                native.push(far_id.to_owned());
13032            } else {
13033                fallback.push(edge.clone());
13034            }
13035        }
13036        Ok((native, fallback))
13037    }
13038
13039    async fn update_existing(
13040        &self,
13041        item: &Resolved,
13042        incoming: &Incoming<'_>,
13043        body: &Option<String>,
13044        status_target: Option<&StatusTarget>,
13045    ) -> Result<(), SourceError> {
13046        let title = incoming.written_title();
13047        // A terminal status closes the issue here, in the same mutation as its body: its board
13048        // option was selected before this, so a close never lands on an item whose board cannot
13049        // show it.
13050        let mut fields = match item.content_kind {
13051            ContentKind::DraftIssue => json!({"title":title,"body":body}),
13052            ContentKind::Issue => json!({"title":title,"body":body,
13053                                         "stateInput":state_input(status_target)}),
13054        };
13055        // The people it is to be assigned to, replacing whoever it holds — sent only when they
13056        // are not exactly those, and looked up before anything of this write was sent.
13057        if let Some(people) = incoming.assignees
13058            && item
13059                .assignees
13060                .as_deref()
13061                .is_none_or(|held| !assignees::same_people(held, people))
13062        {
13063            if item.content_kind == ContentKind::DraftIssue {
13064                return Err(self.assigns_a_draft());
13065            }
13066            fields["assigneeIds"] = json!(self.people_ids(people, &item.written_name())?);
13067        }
13068        // Only the members whose value differs from the item as this write read it are sent,
13069        // and nothing at all when none does — whether or not the store's cache expects a
13070        // version of it. A member left out is one GitHub leaves as it is, so a person's edit
13071        // of it since that read is kept rather than overwritten with what it already held,
13072        // and a re-copy of an unchanged item costs no mutation.
13073        if let Some(members) = fields.as_object_mut() {
13074            if members.get("title").and_then(Value::as_str) == Some(item.title.as_str()) {
13075                members.remove("title");
13076            }
13077            let body_unchanged = match (members.get("body"), item.raw_body.as_deref()) {
13078                (Some(Value::String(sent)), Some(held)) => sent == held,
13079                (Some(Value::Null), held) => held.is_none_or(str::is_empty),
13080                _ => false,
13081            };
13082            if body_unchanged {
13083                members.remove("body");
13084            }
13085            // An issue already in the state the target asks for keeps it: an open one stays
13086            // open, and a closed one whose closure reads as the target's category keeps its
13087            // reason — a duplicate's says more than this write would.
13088            let unchanged_state = match status_target {
13089                Some(StatusTarget::Terminal(_, reason)) => {
13090                    item.closed
13091                        && closed_category(item.reason.as_deref())
13092                            == closed_category(Some(reason.reason()))
13093                }
13094                Some(StatusTarget::Column(_) | StatusTarget::Disabled(_)) => !item.closed,
13095                None => true,
13096            };
13097            if unchanged_state {
13098                members.remove("stateInput");
13099            }
13100            if members.is_empty() {
13101                return Ok(());
13102            }
13103        }
13104        self.update_content(item.content_kind, &item.id, fields)
13105            .await
13106    }
13107
13108    /// Update one board item's content with exactly `fields` beside its id, through the
13109    /// mutation its kind takes: `updateIssue` for an issue, `updateProjectV2DraftIssue` for
13110    /// a draft.
13111    ///
13112    /// Every input field either mutation leaves out is a field GitHub leaves as it is, which
13113    /// is what lets a narrow write carry the one thing it changes and nothing else.
13114    async fn update_content(
13115        &self,
13116        kind: ContentKind,
13117        id: &NativeId,
13118        fields: Value,
13119    ) -> Result<(), SourceError> {
13120        let (operation, id_key, pointer) = match kind {
13121            ContentKind::DraftIssue => (
13122                graphql::UPDATE_DRAFT,
13123                "draftIssueId",
13124                "/updateProjectV2DraftIssue/draftIssue",
13125            ),
13126            ContentKind::Issue => (graphql::UPDATE_ISSUE, "id", "/updateIssue/issue"),
13127        };
13128        if kind == ContentKind::Issue && self.hold_issue(&fields)? {
13129            return Ok(());
13130        }
13131        if kind == ContentKind::Issue && self.hold_update(id, &fields)? {
13132            return Ok(());
13133        }
13134        let mut input = fields;
13135        input[id_key] = json!(id.0);
13136        self.send_update(operation, pointer, id, input).await
13137    }
13138
13139    /// Send one item's update, `input`, as `operation`, and hold GitHub's answer at `pointer`
13140    /// to naming that item, `id`.
13141    async fn send_update(
13142        &self,
13143        operation: &str,
13144        pointer: &str,
13145        id: &NativeId,
13146        input: Value,
13147    ) -> Result<(), SourceError> {
13148        let data = match self.graphql(operation, json!({"input":&input})).await {
13149            Ok(data) => data,
13150            Err(error) => return Err(self.refusing_people(&input, error)),
13151        };
13152        let returned = data
13153            .pointer(pointer)
13154            .ok_or_else(|| SourceError::Malformed {
13155                message: "GitHub item update returned no item".into(),
13156            })?;
13157        if required_str(returned, "id")? != id.0 {
13158            return Err(SourceError::Malformed {
13159                message: "GitHub item update returned the wrong item".into(),
13160            });
13161        }
13162        self.assigned_as_asked(&input, Some(returned))
13163    }
13164
13165    /// Creates one issue, files it on the board, and reports what a read of it would say:
13166    /// its content id, its board item id, and the web address GitHub gave it.
13167    ///
13168    /// Two calls rather than one: `createIssue` answers with an issue that is on no board,
13169    /// and `addProjectV2ItemById` is what puts it there. Filing it at creation through
13170    /// `CreateIssueInput.projectV2Ids` was tried and is not done: GitHub answered with no
13171    /// board item, and the `addProjectV2ItemById` that then had to follow was refused
13172    /// "Content already exists in this project". A terminal status is not written here:
13173    /// `finish_write` selects its option first and closes the issue after, so a close never
13174    /// lands on an item whose board cannot show it.
13175    ///
13176    /// The address and the number come back here because this is the only place either is
13177    /// known before GitHub's own board read catches up — an item this run created answers
13178    /// the reads that follow it out of the record below, and one remembered without them
13179    /// would report no location and no key for the rest of the run.
13180    async fn create_and_file_issue(
13181        &self,
13182        board_id: &str,
13183        repository: &RepositoryTarget,
13184        incoming: &Incoming<'_>,
13185        body: &Option<String>,
13186    ) -> Result<Landed, SourceError> {
13187        let repository_id = self.repository_id(repository, incoming).await?;
13188        let mut input = json!({
13189            "repositoryId":repository_id,"title":incoming.written_title(),"body":body
13190        });
13191        self.assigning(&mut input, incoming)?;
13192        let data = match self
13193            .graphql(graphql::CREATE_ISSUE, json!({"input": &input}))
13194            .await
13195        {
13196            Ok(data) => data,
13197            Err(error) => return Err(self.refusing_people(&input, error)),
13198        };
13199        let created = data
13200            .pointer("/createIssue/issue")
13201            .filter(|value| !value.is_null())
13202            .ok_or_else(|| SourceError::Malformed {
13203                message: "GitHub issue creation returned no issue".into(),
13204            })?;
13205        let content_id = NativeId(required_str(created, "id")?.to_owned());
13206        // Assigned otherwise than asked, the issue is refused and taken back as the filed
13207        // create's is, a refused delete answered beside the refusal.
13208        if let Err(error) = self.assigned_as_asked(&input, Some(created)) {
13209            return Err(self.taken_back(&content_id, created, error).await);
13210        }
13211        // Optional although GitHub's schema makes it non-null: the issue exists by now, so
13212        // a response without it is not worth failing a landed write over — the item simply
13213        // reports no location until the board read catches up, which is what it did before.
13214        let url = optional_str(created, "url")?.map(str::to_owned);
13215        // The issue exists from here on, so an unreadable number and a refused board
13216        // filing below each try, best effort, to take it back: an issue in the repository
13217        // that is on no board is an item nobody asked for and nothing here would find again.
13218        //
13219        // Its number is optional on the same terms its address is — a landed write is not
13220        // worth failing over a member that came back missing, and such an item reports no
13221        // handle until a board read catches up. A number that is *present* and is not an
13222        // unsigned integer is still a response this source cannot read.
13223        let number = match created_issue_number(created) {
13224            Ok(number) => number,
13225            Err(error) => {
13226                let _ = self.delete_issue(&content_id).await;
13227                return Err(error);
13228            }
13229        };
13230        let added = match self
13231            .graphql(
13232                graphql::ADD_TO_BOARD,
13233                json!({"input":{"projectId":board_id,"contentId":content_id.0}}),
13234            )
13235            .await
13236        {
13237            Ok(added) => added,
13238            Err(error) => {
13239                let _ = self.delete_issue(&content_id).await;
13240                return Err(error);
13241            }
13242        };
13243        let item = added
13244            .pointer("/addProjectV2ItemById/item")
13245            .filter(|value| !value.is_null())
13246            .ok_or_else(|| SourceError::Malformed {
13247                message: "GitHub board addition returned no project item".into(),
13248            })?;
13249        self.note_written(&content_id, url.as_deref());
13250        Ok(Landed {
13251            content_id,
13252            item_id: Some(required_str(item, "id")?.to_owned()),
13253            url,
13254            number,
13255        })
13256    }
13257
13258    /// Move one issue under the project it now belongs to, or out of the one it left.
13259    async fn reparent(
13260        &self,
13261        held: Option<NativeId>,
13262        child: &NativeId,
13263        wanted: Option<&NativeId>,
13264    ) -> Result<(), SourceError> {
13265        if held.as_ref() == wanted {
13266            return Ok(());
13267        }
13268        if let Some(held) = &held {
13269            self.sub_issue(graphql::REMOVE_SUB_ISSUE, held, child, "removeSubIssue")
13270                .await?;
13271        }
13272        if let Some(wanted) = wanted {
13273            self.sub_issue(graphql::ADD_SUB_ISSUE, wanted, child, "addSubIssue")
13274                .await?;
13275        }
13276        Ok(())
13277    }
13278
13279    async fn sub_issue(
13280        &self,
13281        operation: &str,
13282        parent: &NativeId,
13283        child: &NativeId,
13284        root: &str,
13285    ) -> Result<(), SourceError> {
13286        let data = self
13287            .graphql(
13288                operation,
13289                json!({"input":{"issueId":parent.0,"subIssueId":child.0}}),
13290            )
13291            .await?;
13292        let issue =
13293            data.pointer(&format!("/{root}/issue"))
13294                .ok_or_else(|| SourceError::Malformed {
13295                    message: "GitHub sub-issue update returned no issue".into(),
13296                })?;
13297        let sub =
13298            data.pointer(&format!("/{root}/subIssue"))
13299                .ok_or_else(|| SourceError::Malformed {
13300                    message: "GitHub sub-issue update returned no sub-issue".into(),
13301                })?;
13302        if required_str(issue, "id")? != parent.0 || required_str(sub, "id")? != child.0 {
13303            return Err(SourceError::Malformed {
13304                message: "GitHub sub-issue update returned the wrong issues".into(),
13305            });
13306        }
13307        Ok(())
13308    }
13309
13310    /// Bring one issue's `blockedBy` to exactly `native`, sending only the difference, and say
13311    /// whether there was one.
13312    ///
13313    /// An issue [`Issue::Created`] by this very write is blocked by nothing yet, so its
13314    /// relationships are not read: there is nothing a read of them could find.
13315    async fn reconcile_blocked_by(
13316        &self,
13317        content_id: &NativeId,
13318        native: &[String],
13319        issue: Issue<'_>,
13320    ) -> Result<bool, SourceError> {
13321        let current = match issue {
13322            Issue::Created => Vec::new(),
13323            Issue::Existing(Some(held)) => held
13324                .iter()
13325                .map(|far| required_str(far, "id").map(str::to_owned))
13326                .collect::<Result<Vec<_>, _>>()?,
13327            Issue::Existing(None) => self.native_dependency_ids(content_id).await?,
13328        };
13329        let mut changed = false;
13330        for (operation, far_id) in current
13331            .iter()
13332            .filter(|id| !native.contains(id))
13333            .map(|id| (graphql::REMOVE_BLOCKED_BY, id))
13334            .chain(
13335                native
13336                    .iter()
13337                    .filter(|id| !current.contains(id))
13338                    .map(|id| (graphql::ADD_BLOCKED_BY, id)),
13339            )
13340        {
13341            let data = self
13342                .graphql(
13343                    operation,
13344                    json!({"input":{"issueId":content_id.0,"blockingIssueId":far_id}}),
13345                )
13346                .await?;
13347            let root = if operation == graphql::ADD_BLOCKED_BY {
13348                "addBlockedBy"
13349            } else {
13350                "removeBlockedBy"
13351            };
13352            let issue =
13353                data.pointer(&format!("/{root}/issue"))
13354                    .ok_or_else(|| SourceError::Malformed {
13355                        message: "GitHub dependency update returned no issue".into(),
13356                    })?;
13357            let blocker = data
13358                .pointer(&format!("/{root}/blockingIssue"))
13359                .ok_or_else(|| SourceError::Malformed {
13360                    message: "GitHub dependency update returned no blocking issue".into(),
13361                })?;
13362            if required_str(issue, "id")? != content_id.0 || required_str(blocker, "id")? != far_id
13363            {
13364                return Err(SourceError::Malformed {
13365                    message: "GitHub dependency update returned the wrong issues".into(),
13366                });
13367            }
13368            changed = true;
13369        }
13370        Ok(changed)
13371    }
13372}
13373
13374/// The board field values one write sends, in the order GitHub runs them, and the fields it
13375/// clears after them: the origin field when it moves, the `Status` option `column` names, the
13376/// priority, then each projected field.
13377fn field_writes<'a>(
13378    existing: Option<&Resolved>,
13379    origin_field: Option<&str>,
13380    origin: &str,
13381    column: Option<(String, String)>,
13382    priority: Option<&'a PriorityWrite>,
13383    projections: &'a [ProjectionWrite],
13384) -> (Vec<(String, Value)>, Vec<&'a str>) {
13385    let mut fields = Vec::new();
13386    if let Some(field_id) = origin_field
13387        && existing.map_or(!origin.is_empty(), |item| {
13388            item.origin.as_deref().unwrap_or("") != origin
13389        })
13390    {
13391        fields.push((field_id.to_owned(), json!({"text":origin})));
13392    }
13393    if let Some((field_id, option_id)) = column {
13394        fields.push((field_id, json!({"singleSelectOptionId":option_id})));
13395    }
13396    let mut clears = Vec::new();
13397    match priority {
13398        Some(PriorityWrite::Select { field, option }) => {
13399            fields.push((field.clone(), json!({"singleSelectOptionId":option})));
13400        }
13401        Some(PriorityWrite::Clear { field }) => clears.push(field.as_str()),
13402        None => {}
13403    }
13404    for projection in projections {
13405        projection.join(&mut fields, &mut clears);
13406    }
13407    (fields, clears)
13408}
13409
13410/// Everything one write decided before sending anything: see
13411/// [`GitHubProjectsSource::prepare_write`].
13412struct Prepared {
13413    /// What the write lands on.
13414    destination: WriteDestination,
13415    board: BoardFields,
13416    status_target: Option<StatusTarget>,
13417    /// The `Status` field, the option and the option's name the status lands on.
13418    // 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.
13419    column: Option<(String, String, String)>,
13420    priority_write: Option<PriorityWrite>,
13421    projections: Vec<ProjectionWrite>,
13422    projected: BTreeMap<String, String>,
13423    content_kind: ContentKind,
13424    own_repository: Option<Repository>,
13425    /// The far ends of the item's native blocked-by relationships.
13426    // 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.
13427    native: Vec<String>,
13428    slot: BTreeMap<String, Value>,
13429    content: Option<String>,
13430    body: Option<String>,
13431    /// The copy origin the item records, empty for none.
13432    // 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.
13433    origin: String,
13434    origin_field: Option<String>,
13435}
13436
13437/// One write a copy held back of the kinds sent together: a board field value, or a blocked-by
13438/// edge, each its input.
13439enum HeldWrite<'a> {
13440    Field(&'a Value),
13441    Edge(&'a Value),
13442}
13443
13444/// Whether `error` is GitHub refusing to file an issue on a board because it is filed there
13445/// already — what `addProjectV2ItemById` answers once `createIssue`'s `projectV2Ids` has placed
13446/// it, rather than answering with the item it holds.
13447fn already_on_the_board(error: &SourceError) -> bool {
13448    error
13449        .to_string()
13450        .contains("Content already exists in this project")
13451}
13452
13453/// Hold every alias `inputs` sent under `prefix` in `data` to answering with what its input
13454/// named — each `(root, named)` of `answers` — and refuse one that answered nothing or another
13455/// item.
13456fn check_aliased_answers(
13457    document: &str,
13458    data: &Value,
13459    prefix: &str,
13460    inputs: &[&Value],
13461    answers: &[(&str, &str)],
13462) -> Result<(), SourceError> {
13463    for (slot, input) in inputs.iter().enumerate() {
13464        for (root, named) in answers {
13465            let answered = data
13466                .pointer(&format!("/{prefix}{slot}/{root}/id"))
13467                .and_then(Value::as_str)
13468                .ok_or_else(|| SourceError::Malformed {
13469                    message: format!(
13470                        "GitHub answered {} with nothing at {prefix}{slot}",
13471                        operation_description(document)
13472                    ),
13473                })?;
13474            let asked = input.get(named).and_then(Value::as_str).unwrap_or_default();
13475            if answered != asked {
13476                return Err(SourceError::Malformed {
13477                    message: format!(
13478                        "GitHub answered {} at {prefix}{slot} with {answered}, which is not \
13479                         {asked}, the item it was asked to write",
13480                        operation_description(document)
13481                    ),
13482                });
13483            }
13484        }
13485    }
13486    Ok(())
13487}
13488
13489/// `error`, which stopped a batch of creates, and — when GitHub refused to take any of them
13490/// back — each issue of `left` it created that is still in the repository, which its caller,
13491/// never handed their ids, could not name.
13492fn left_behind(error: SourceError, left: &[&str]) -> SourceError {
13493    if left.is_empty() {
13494        return error;
13495    }
13496    SourceError::Refused {
13497        message: format!(
13498            "{error}; GitHub then refused to take back {}, which this write created and which \
13499             are still in the repository; next: delete {} before writing again",
13500            left.join(", "),
13501            if left.len() == 1 { "it" } else { "them" }
13502        ),
13503    }
13504}
13505
13506/// What one write lands on: the item it updates, as it stood, or where it creates a new one.
13507enum WriteDestination {
13508    /// The item as it stood, for an update.
13509    Existing(Box<Resolved>),
13510    /// Where a new item is created.
13511    New(RepositoryTarget),
13512}
13513
13514impl WriteDestination {
13515    /// The item an update writes over, as it stood; `None` for a create.
13516    fn existing(&self) -> Option<&Resolved> {
13517        match self {
13518            Self::Existing(item) => Some(item),
13519            Self::New(_) => None,
13520        }
13521    }
13522}
13523
13524/// One existing issue's update held back by [`GitHubProjectsSource::hold_update`]: the issue,
13525/// and the `UpdateIssueInput` its own [`graphql::UPDATE_ISSUE`] would have sent — the members
13526/// it writes beside that issue's id, which only [`Self::new`] sets.
13527struct HeldUpdate {
13528    issue: NativeId,
13529    // 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.
13530    input: Value,
13531}
13532
13533impl HeldUpdate {
13534    /// The update writing `members` — an `UpdateIssueInput` without its id — to `issue`.
13535    fn new(issue: &NativeId, members: &Value) -> Self {
13536        let mut input = members.clone();
13537        input["id"] = json!(issue.0);
13538        Self {
13539            issue: issue.clone(),
13540            input,
13541        }
13542    }
13543}
13544
13545/// What a copy has held back of the items it created; see
13546/// [`GitHubProjectsSource::hold_back`].
13547#[derive(Debug, Default)]
13548enum Deferred {
13549    /// Writes are being held back, and nothing has been held yet.
13550    #[default]
13551    Nothing,
13552    /// The items held back, every one of them on `board`.
13553    Held {
13554        /// The board every one of them is on.
13555        board: BoardId,
13556        /// Each created item, in the order it was created.
13557        created: Vec<HeldBack>,
13558    },
13559}
13560
13561impl Deferred {
13562    /// Whether `content` is one of the items held back.
13563    fn holds(&self, content: &NativeId) -> bool {
13564        match self {
13565            Self::Nothing => false,
13566            Self::Held { created, .. } => created.iter().any(|held| held.content == *content),
13567        }
13568    }
13569}
13570
13571/// One created item's parts that land once [`TaskSource::finish_writes`] is called.
13572#[derive(Debug)]
13573struct HeldBack {
13574    /// The issue.
13575    content: NativeId,
13576    /// Its board field values other than its `Status`, in the order they are written.
13577    fields: Vec<(String, Value)>,
13578    /// The `Status` field, and the option and its name that the item's status lands on.
13579    // llmlint: ignore[invalid_states_unrepresentable] The same triple `column_for` returns and `Prepared::column` carries, held back unchanged until it is sent.
13580    status: Option<(String, String, String)>,
13581    /// The fields it clears after those are written.
13582    clears: Vec<String>,
13583    /// The reason it is closed for, once its option is selected; `None` leaves it open.
13584    close: Option<ClosedState>,
13585    /// The issues it is blocked by.
13586    edges: Vec<NativeId>,
13587}
13588
13589/// The member [`answer_with_errors`] carries a response's GraphQL errors under, beside its data:
13590/// no GitHub type has a field of this name.
13591const ANSWER_ERRORS: &str = "onetaskgraphErrors";
13592
13593/// A response's `data` with its GraphQL errors beside it under [`ANSWER_ERRORS`], when it has
13594/// both — or `None`, for an answer [`GitHubProjectsSource::answer`] reads as it always has.
13595///
13596/// What [`graphql::CREATE_ISSUES`] is answered with: GitHub runs a document's mutation fields in
13597/// order and answers each one that ran, so a refusal of one alias leaves the issues the others
13598/// created named in the data beside it — the ids a copy needs to take them back.
13599fn answer_with_errors(body: &str) -> Option<Value> {
13600    let parsed: Value = serde_json::from_str(body).ok()?;
13601    let errors = parsed
13602        .get("errors")?
13603        .as_array()
13604        .filter(|errors| !errors.is_empty())?;
13605    let mut data = parsed.get("data").filter(|data| data.is_object())?.clone();
13606    data[ANSWER_ERRORS] = Value::Array(errors.clone());
13607    Some(data)
13608}
13609
13610/// The `createIssue` input that files the new issue on `board` and, when `incoming` names one,
13611/// under its project — see [`GitHubProjectsSource::create_filed_issue`].
13612fn filed_input(
13613    repository: &str,
13614    board: &str,
13615    incoming: &Incoming<'_>,
13616    body: &Option<String>,
13617) -> Value {
13618    let mut input = json!({"repositoryId":repository,"title":incoming.written_title(),
13619                           "body":body,"projectV2Ids":[board]});
13620    if let Some(parent) = incoming.parent {
13621        input["parentIssueId"] = json!(parent.0);
13622    }
13623    input
13624}
13625
13626/// The name of option `option` of field `field` among a board's `fields`.
13627fn option_name<'a>(fields: &'a Value, field: &str, option: &str) -> Option<&'a str> {
13628    fields
13629        .get("nodes")?
13630        .as_array()?
13631        .iter()
13632        .find(|node| node.get("id").and_then(Value::as_str) == Some(field))?
13633        .get("options")?
13634        .as_array()?
13635        .iter()
13636        .find(|candidate| candidate.get("id").and_then(Value::as_str) == Some(option))?
13637        .get("name")?
13638        .as_str()
13639}
13640
13641/// What a write needs to know of one far end it names: which kind of item it is, and whether
13642/// it is an issue a native relationship can name.
13643struct FarEnd {
13644    kind: BoardKind,
13645    content_kind: ContentKind,
13646}
13647
13648/// Whether the issue one write reconciles was created by that write or was already there.
13649#[derive(Clone, Copy, PartialEq, Eq)]
13650enum Issue<'a> {
13651    /// Created by this write, so it holds no relationships yet.
13652    Created,
13653    /// On the board before this write, holding whatever relationships it holds — the far
13654    /// ends of its whole `blockedBy`, when the read that reached it carried them.
13655    Existing(Option<&'a [Value]>),
13656}
13657
13658/// What resolving one node id reached; see [`GitHubProjectsSource::reach`].
13659enum Reached {
13660    /// An issue this board holds, resolved into everything this source reports about it.
13661    Held(Box<Resolved>),
13662    /// Nothing this board holds: no such node, or a node on some other board.
13663    Nothing,
13664    /// A board draft, which [`graphql::ISSUE`] reaches and reads nothing of, so it is read
13665    /// again by [`GitHubProjectsSource::draft_by_id`].
13666    Draft,
13667}
13668
13669/// What GitHub says when a string is not a node id it can resolve.
13670///
13671/// Matched because it is the ordinary answer to a project selector naming a project by its
13672/// *name*, and reporting that as a failure would make naming one impossible. It is read
13673/// off the refusal GitHub sent, never guessed from the shape of the string: this source
13674/// does not define the syntax of a GitHub node id and would be wrong about it.
13675const UNRESOLVABLE_NODE: &str = "could not resolve to a node";
13676
13677/// `error` with `note` added to the end of what it says, its kind and every other member
13678/// unchanged — so a caller still branches on the failure that happened, and reads beside it
13679/// what that failure left behind.
13680fn noting(error: SourceError, note: &str) -> SourceError {
13681    match error {
13682        SourceError::Config { message } => SourceError::Config {
13683            message: message + note,
13684        },
13685        SourceError::Auth { message } => SourceError::Auth {
13686            message: message + note,
13687        },
13688        SourceError::Refused { message } => SourceError::Refused {
13689            message: message + note,
13690        },
13691        SourceError::RateLimited {
13692            retry_after_seconds,
13693            message,
13694        } => SourceError::RateLimited {
13695            retry_after_seconds,
13696            message: Some(message.unwrap_or_default() + note),
13697        },
13698        SourceError::Unavailable { message } => SourceError::Unavailable {
13699            message: message + note,
13700        },
13701        SourceError::Malformed { message } => SourceError::Malformed {
13702            message: message + note,
13703        },
13704    }
13705}
13706
13707/// The variables of one [`graphql::ISSUE_COPY_DETAILS`] request, as [`detail_batch`] binds its
13708/// own: a slot `batch` has no id for is bound to its last id, read again at no added price.
13709fn copy_detail_batch(batch: &[NativeId], comments: &PageRequest, children: bool) -> Value {
13710    let mut variables = serde_json::Map::new();
13711    for slot in 0..COPY_DETAIL_BATCH {
13712        let id = batch.get(slot).or(batch.last()).map(|id| id.0.clone());
13713        variables.insert(format!("id{slot}"), json!(id));
13714    }
13715    variables.insert("project".to_owned(), json!(batch.first().map(|id| &id.0)));
13716    variables.insert("children".to_owned(), json!(children));
13717    variables.insert("first".to_owned(), json!(comments.limit.min(MAX_PAGE_SIZE)));
13718    variables.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
13719    variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
13720    variables.insert("duplicates".to_owned(), json!(true));
13721    Value::Object(variables)
13722}
13723
13724/// The variables of one [`graphql::ISSUE_DETAILS`] request over `batch` — at most
13725/// [`DETAIL_BATCH`] ids — each item with the first page of its comments when `comments` asks
13726/// for them.
13727///
13728/// The document is fixed-size, so a slot `batch` has no id for is bound to its last id, which
13729/// is read again at no added price.
13730fn detail_batch(batch: &[NativeId], comments: Option<&PageRequest>) -> Value {
13731    let mut variables = serde_json::Map::new();
13732    for slot in 0..DETAIL_BATCH {
13733        let id = batch.get(slot).or(batch.last()).map(|id| id.0.clone());
13734        variables.insert(format!("id{slot}"), json!(id));
13735    }
13736    variables.insert(
13737        "first".to_owned(),
13738        json!(comments.map_or(MAX_PAGE_SIZE, |page| page.limit.min(MAX_PAGE_SIZE))),
13739    );
13740    variables.insert("comments".to_owned(), json!(comments.is_some()));
13741    variables.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
13742    variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
13743    variables.insert("duplicates".to_owned(), json!(true));
13744    Value::Object(variables)
13745}
13746
13747/// Whether this refusal is GitHub saying the id names no node at all.
13748fn unresolvable_node(error: &SourceError) -> bool {
13749    matches!(error, SourceError::Refused { message }
13750        if message.to_ascii_lowercase().contains(UNRESOLVABLE_NODE))
13751}
13752
13753/// One project name, as a search qualifier which filters on it at the server.
13754///
13755/// Quoted so the whole title is one phrase rather than a bag of words, with the two
13756/// characters GitHub's own quoting grammar gives a meaning inside a quoted phrase escaped
13757/// the way it documents. A title matched here is still compared for equality afterwards:
13758/// the qualifier narrows what the server sends, and this source decides what it names.
13759fn title_qualifier(name: &str) -> String {
13760    format!("in:title {}", quoted(name))
13761}
13762
13763/// `value` as one quoted phrase of a GitHub search or a board filter, with the two
13764/// characters GitHub's quoting grammar gives a meaning inside a quoted phrase escaped the way
13765/// it documents — so a value holding a qualifier's spelling is searched for rather than
13766/// obeyed.
13767fn quoted(value: &str) -> String {
13768    let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
13769    format!("\"{escaped}\"")
13770}
13771
13772/// The search qualifier for the issues updated at or after `since`.
13773///
13774/// Written to the second, rounded down, which can only widen what the search returns.
13775fn updated_qualifier(since: DateTime<Utc>) -> String {
13776    format!("updated:>={}", since.format("%Y-%m-%dT%H:%M:%S+00:00"))
13777}
13778
13779/// The search terms that narrow a board-scoped issue search to a task query's text and
13780/// metadata predicates, or `None` when it carries neither.
13781///
13782/// The text is one quoted phrase, searched `in:title`, `in:body` or both as its fields say,
13783/// and each metadata value is one more quoted phrase, which GitHub finds in the body because
13784/// its index covers the metadata comment the value is stored in. GitHub ANDs the phrases and
13785/// matches each in any field the `in:` qualifier names, so a query naming a title search and
13786/// a metadata value searches both fields for both — wider than asked, never narrower, and
13787/// every candidate is confirmed in process afterwards.
13788///
13789/// **This narrows a text search, and that is this source's declared semantics.** GitHub
13790/// matches whole tokens where a substring rule would match inside a word, so an item holding
13791/// the text only inside a longer word is not returned. A text of nothing but whitespace
13792/// matches every item, so it narrows nothing and is not sent.
13793fn narrowing_qualifiers(query: &TaskQuery) -> Option<String> {
13794    let text = query
13795        .text
13796        .as_ref()
13797        .filter(|text| !text.terms.trim().is_empty());
13798    if text.is_none() && query.metadata.is_empty() {
13799        return None;
13800    }
13801    let (title, body) = match text.map(|text| text.fields) {
13802        None => (false, true),
13803        Some(TextFields::Title) => (true, !query.metadata.is_empty()),
13804        Some(TextFields::Content) => (false, true),
13805        Some(TextFields::TitleOrContent) => (true, true),
13806    };
13807    let fields = match (title, body) {
13808        (true, true) => "in:title,body",
13809        (true, false) => "in:title",
13810        _ => "in:body",
13811    };
13812    let phrases = text
13813        .map(|text| text.terms.clone())
13814        .into_iter()
13815        .chain(
13816            query
13817                .metadata
13818                .iter()
13819                .map(|wanted| as_stored(wanted.value())),
13820        )
13821        .map(|phrase| quoted(&phrase))
13822        .collect::<Vec<_>>();
13823    Some(format!("{fields} {}", phrases.join(" ")))
13824}
13825
13826/// Whether every status category `query` keeps reads only off an open issue or a draft: a
13827/// closed issue reads `done`, `cancelled` or — closed for a reason that implies no category —
13828/// `unknown`, so a status filter naming none of those three can ask every issue search it sends
13829/// for open issues alone; each candidate's category is still confirmed from its own item.
13830fn open_only(query: &TaskQuery) -> bool {
13831    !query.statuses.is_empty()
13832        && query.statuses.iter().all(|category| {
13833            !matches!(
13834                category,
13835                StatusCategory::Done | StatusCategory::Cancelled | StatusCategory::Unknown
13836            )
13837        })
13838}
13839
13840/// Whether every status category `query` keeps is one only an open item reads as — `draft`,
13841/// `backlog`, `todo`, `queued`, `in-progress` and `unknown` — so a listing of it can read the
13842/// board's open items alone.
13843///
13844/// `unknown` is among them here though [`open_only`] leaves it out: a closed issue reads
13845/// `unknown` only for a closure reason GitHub never records on a closed issue (see
13846/// [`closed_category`]), so an open-only read of the board loses nothing a whole one keeps,
13847/// while an issue search, which [`open_only`] narrows, keeps its own rule.
13848fn open_items_only(query: &TaskQuery) -> bool {
13849    !query.statuses.is_empty()
13850        && query
13851            .statuses
13852            .iter()
13853            .all(|category| !matches!(category, StatusCategory::Done | StatusCategory::Cancelled))
13854}
13855
13856/// What a task query is narrowed by beside a board-scoped issue search's scope — its comment
13857/// activity and its text and metadata, with `is:open` when [`open_only`] — or `None` for a query
13858/// carrying none of those, which no narrowed search answers.
13859///
13860/// A narrowed search never answers a draft, which is no issue, so narrowing it to open issues
13861/// too leaves out nothing such a search could have answered.
13862fn search_qualifiers(query: &TaskQuery) -> Option<String> {
13863    let mut qualifiers: Vec<String> = [
13864        query.commented_since.map(updated_qualifier),
13865        narrowing_qualifiers(query),
13866    ]
13867    .into_iter()
13868    .flatten()
13869    .collect();
13870    if qualifiers.is_empty() {
13871        return None;
13872    }
13873    if open_only(query) {
13874        qualifiers.push(OPEN_QUALIFIER.to_owned());
13875    }
13876    Some(qualifiers.join(" "))
13877}
13878
13879/// The search terms that narrow a board-scoped issue search to a project or document query's
13880/// text, or `None` when it has none or a blank one: the phrase, in the fields, a task query
13881/// carrying that text alone is sent as by [`narrowing_qualifiers`].
13882fn text_qualifiers(text: Option<&TextQuery>) -> Option<String> {
13883    narrowing_qualifiers(&TaskQuery {
13884        text: text.cloned(),
13885        ..TaskQuery::default()
13886    })
13887}
13888
13889/// Refuses a project or document query's text GitHub's issue search cannot find, before
13890/// anything is asked of GitHub, on exactly the terms [`refuse_unsearchable`] refuses a task
13891/// query's.
13892fn refuse_unsearchable_text(text: Option<&TextQuery>) -> Result<(), SourceError> {
13893    refuse_unsearchable(&TaskQuery {
13894        text: text.cloned(),
13895        ..TaskQuery::default()
13896    })
13897}
13898
13899/// Refuses a task query naming a text or a metadata value GitHub's issue search cannot find,
13900/// before anything is asked of GitHub.
13901///
13902/// GitHub's index holds words, so a phrase with no letter or digit names none to find, and no
13903/// bounded query answers it: sent, GitHub's answer to it is nothing this source may rely on;
13904/// left out, the search is every issue of the board. So this source says it cannot answer
13905/// rather than reading the board or answering nothing. A blank text is not refused: it narrows
13906/// nothing GitHub could search for, and keeps the board read it always had.
13907fn refuse_unsearchable(query: &TaskQuery) -> Result<(), SourceError> {
13908    const WHY: &str = "GitHub's issue search indexes words, so it cannot answer a value with no \
13909                       letter or digit with a bounded query";
13910    if let Some(text) = &query.text
13911        && !text.terms.trim().is_empty()
13912        && !has_words(&text.terms)
13913    {
13914        return Err(SourceError::Refused {
13915            message: format!(
13916                "cannot search for the text {:?}: {WHY}; search for a text holding a letter or a digit",
13917                text.terms
13918            ),
13919        });
13920    }
13921    if let Some(wanted) = query
13922        .metadata
13923        .iter()
13924        .find(|wanted| !has_words(wanted.value()))
13925    {
13926        return Err(SourceError::Refused {
13927            message: format!(
13928                "cannot filter by the metadata value {:?} at {:?}: {WHY}; filter by a value holding a letter or a digit",
13929                wanted.value(),
13930                std::iter::once(wanted.key())
13931                    .chain(wanted.path().iter().map(String::as_str))
13932                    .collect::<Vec<_>>()
13933                    .join("/"),
13934            ),
13935        });
13936    }
13937    Ok(())
13938}
13939
13940/// Whether GitHub's index could hold a word of `phrase`: whether it has a letter or a digit.
13941fn has_words(phrase: &str) -> bool {
13942    phrase.chars().any(char::is_alphanumeric)
13943}
13944
13945/// `value` spelled the way the metadata slot stores it: as the inside of its JSON string.
13946///
13947/// What GitHub indexes is the slot's JSON text, so a value holding a character JSON escapes —
13948/// a newline, a tab, a quote — is found by the escape the body holds and not by the character,
13949/// which GitHub's word match would read as different words.
13950fn as_stored(value: &str) -> String {
13951    let encoded = Value::String(value.to_owned()).to_string();
13952    encoded[1..encoded.len() - 1].to_owned()
13953}
13954
13955/// The one narrower question a task query carrying a text, metadata or origin predicate is
13956/// sent as.
13957enum Narrowing {
13958    /// Every carrier of this origin: [`graphql::ORIGIN_LOOKUP`].
13959    Origin(String),
13960    /// The board-scoped issue search narrowed by these qualifiers.
13961    Search(String),
13962}
13963
13964impl Narrowing {
13965    /// What this question is remembered under for the length of one command.
13966    fn key(&self) -> String {
13967        match self {
13968            Self::Origin(origin) => format!("origin {origin}"),
13969            Self::Search(also) => format!("search {also}"),
13970        }
13971    }
13972}
13973
13974/// Where one connection of [`graphql::ORIGIN_LOOKUP`] resumes.
13975enum Resumed {
13976    /// It reported another page, which starts after this cursor.
13977    More(String),
13978    /// It has ended. Sending this cursor again — the page's own end when it had one, and
13979    /// otherwise the cursor it was reached from — answers an empty page, so the one document
13980    /// can go on walking the other connection.
13981    Ended(Option<String>),
13982}
13983
13984impl Resumed {
13985    /// Whether the connection has another page.
13986    const fn has_more(&self) -> bool {
13987        matches!(self, Self::More(_))
13988    }
13989
13990    /// The cursor to send this connection next.
13991    fn cursor(self) -> Option<String> {
13992        match self {
13993            Self::More(next) => Some(next),
13994            Self::Ended(last) => last,
13995        }
13996    }
13997}
13998
13999/// Where `connection`, reached from `after`, resumes — refused when it reports another page
14000/// with no cursor to it, or from a cursor that does not advance.
14001fn resumed(connection: &Value, after: Option<&str>) -> Result<Resumed, SourceError> {
14002    let info = connection
14003        .get("pageInfo")
14004        .ok_or_else(|| SourceError::Malformed {
14005            message: "GitHub connection has no pageInfo".into(),
14006        })?;
14007    let end = optional_str(info, "endCursor")?;
14008    if required_bool(info, "hasNextPage")? {
14009        let next = end.ok_or_else(|| SourceError::Malformed {
14010            message: "GitHub connection reports another page and no endCursor".into(),
14011        })?;
14012        validate_cursor_progress(after, next)?;
14013        return Ok(Resumed::More(next.to_owned()));
14014    }
14015    Ok(Resumed::Ended(
14016        end.map(str::to_owned).or_else(|| after.map(str::to_owned)),
14017    ))
14018}
14019
14020/// The board, and every item on it this source reports.
14021#[derive(Clone)]
14022struct Board {
14023    id: String,
14024    fields: Value,
14025    items: Vec<Resolved>,
14026}
14027
14028/// What a write needs of the board and nothing more: its node id and its field
14029/// definitions, in the shape a read of the board's own `fields` gives them.
14030///
14031/// Deliberately no items. A write decides which item it writes, which parent it files
14032/// under and which far ends it names by reading each of them by its own id; this is the
14033/// half of the board those reads cannot carry, and holding no item is what keeps it from
14034/// ever being asked whether an item is there.
14035#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
14036struct BoardFields {
14037    id: BoardId,
14038    fields: Value,
14039}
14040
14041/// A board's node id: what a field write and `addProjectV2ItemById` address.
14042///
14043/// Never blank, because a blank one addresses no board — so an id GitHub answers blank is
14044/// refused where it is read, and one an item names blank is read as not named at all.
14045#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
14046#[serde(try_from = "String")]
14047struct BoardId(String);
14048
14049impl TryFrom<String> for BoardId {
14050    type Error = String;
14051
14052    /// The same refusal [`BoardId::parse`] makes, for an id read back from a kept context.
14053    fn try_from(id: String) -> Result<Self, Self::Error> {
14054        Self::parse(&id).map_err(|error| error.to_string())
14055    }
14056}
14057
14058/// Where one write left its item, for the record the rest of the command reads it out of.
14059///
14060/// A named record rather than a tuple because the update arm and the create arm each fill
14061/// all four, and two `Option`s of different meaning side by side in a tuple are two
14062/// positions a reader has to count.
14063struct Landed {
14064    /// The issue's own node id, which is the [`NativeId`] this source reports.
14065    content_id: NativeId,
14066    /// The board item's id, which is what a field write addresses — `None` for an issue its
14067    /// create filed on the board itself, whose board item GitHub adds after answering and
14068    /// [`TaskSource::finish_writes`] reads.
14069    // 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.
14070    item_id: Option<String>,
14071    /// The web address GitHub gave the issue, when it gave one.
14072    // 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.
14073    url: Option<String>,
14074    /// The issue's number on its repository, when GitHub reported one.
14075    number: Option<u64>,
14076}
14077
14078impl BoardId {
14079    fn parse(id: &str) -> Result<Self, SourceError> {
14080        if id.trim().is_empty() {
14081            return Err(SourceError::Malformed {
14082                message: "GitHub named a board with a blank node id".into(),
14083            });
14084        }
14085        Ok(Self(id.to_owned()))
14086    }
14087
14088    fn as_str(&self) -> &str {
14089        &self.0
14090    }
14091}
14092
14093impl Board {
14094    fn field<'a>(fields: &'a Value, name: &str) -> Result<Option<&'a Value>, SourceError> {
14095        complete_connection(fields, "project fields", NESTED_PAGE_SIZE)?;
14096        let nodes = fields
14097            .get("nodes")
14098            .and_then(Value::as_array)
14099            .ok_or_else(|| SourceError::Malformed {
14100                message: "GitHub project fields.nodes is not an array".into(),
14101            })?;
14102        Ok(nodes
14103            .iter()
14104            .find(|field| field.get("name").and_then(Value::as_str) == Some(name)))
14105    }
14106}
14107
14108/// One board item, resolved into everything this source reports about it.
14109///
14110/// Serializable because it is what [`TaskSource::write_context`] hands the store's cache and
14111/// [`TaskSource::prime_write`] takes back — see [`expected`].
14112#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
14113struct Resolved {
14114    item_id: String,
14115    id: NativeId,
14116    content_kind: ContentKind,
14117    kind: BoardKind,
14118    title: String,
14119    body: Option<String>,
14120    /// The body exactly as GitHub holds it, metadata slot and all, which is what a write
14121    /// that changes the slot alone has to keep byte for byte outside it.
14122    raw_body: Option<String>,
14123    status: Status,
14124    /// The name of the board `Status` option this item sits in, as the board spells it.
14125    option: Option<String>,
14126    /// What its `Priority` field says, read through this instance's mapping.
14127    priority: HeldPriority,
14128    /// Whether this item's issue is closed. A draft has no such state and is never closed.
14129    closed: bool,
14130    /// GitHub's reason for a closed issue's closure, as it spells it — `None` for an open
14131    /// issue, a draft, and an issue closed before GitHub recorded reasons.
14132    #[serde(default)]
14133    reason: Option<String>,
14134    /// The tasks this one delivers, read out of its slot. Empty for anything not a task.
14135    delivers: Vec<TaskRef>,
14136    /// Every task that delivers this one, read out of its slot. Empty for anything not a
14137    /// task.
14138    delivered_by: Vec<TaskRef>,
14139    labels: Vec<Label>,
14140    parent: Option<NativeId>,
14141    /// The issue's GitHub parent on a source reading sub-issues as children (`sub_issues:
14142    /// parent`), where [`Self::parent`] — the project it is filed under — is always `None`.
14143    #[serde(default)]
14144    issue_parent: Option<NativeId>,
14145    // 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.
14146    origin: Option<String>,
14147    /// What each board text field this instance projects metadata onto holds for this item,
14148    /// by field name — only the fields holding a value, an empty text included. What a write compares the
14149    /// item's metadata against, so a field already holding its value is not written again;
14150    /// never read back as metadata, which the slot alone reports.
14151    projected: BTreeMap<String, String>,
14152    /// The issue's own number on its repository, as GitHub reports it.
14153    ///
14154    /// `None` in exactly two cases: a draft, which has no number at all — `DraftIssue`
14155    /// declares none, and a draft is not filed in a repository to be numbered by one — and
14156    /// an issue this run created whose creating mutation answered without one, which is a
14157    /// response GitHub's own schema says cannot happen and which a landed write is not
14158    /// worth failing over. An `Issue` read off the board always has one.
14159    number: Option<u64>,
14160    url: Option<String>,
14161    created_at: Option<DateTime<Utc>>,
14162    updated_at: Option<DateTime<Utc>>,
14163    /// When the board item itself last changed — what a board field write moves — when the
14164    /// read that reached it said.
14165    item_updated_at: Option<DateTime<Utc>>,
14166    /// How many comments the issue holds, when the read that reached it said.
14167    comment_count: Option<u64>,
14168    /// How many relationship events the issue's timeline holds — every dependency, as
14169    /// `blockedBy` or `blocking`, and every project membership, as its parent, added or
14170    /// removed — when the read that reached it said.
14171    relationship_events: Option<u64>,
14172    /// The server's clock on the response that read it — its `Date` header — when the
14173    /// response carried one.
14174    served_at: Option<DateTime<Utc>>,
14175    /// The digest of its [`change_token::Facets`] — its own kind, its board field values and
14176    /// its labels — when the read that reached it carried all three whole.
14177    #[serde(default)]
14178    facets: Option<change_token::FacetsDigest>,
14179    own_repository: Option<Repository>,
14180    repositories: Vec<Repository>,
14181    classification: Classification,
14182    slot: BTreeMap<String, Value>,
14183    /// The node id of the board this item sits on, when the read that reached it said.
14184    board_id: Option<String>,
14185    /// The definition of every board field this item holds a value of, in the shape a read
14186    /// of the board's own `fields` gives one.
14187    ///
14188    /// Only the fields this item has a value in: a field it holds nothing of is not here,
14189    /// which says nothing about whether the board has it.
14190    fields: Vec<Value>,
14191    /// Every field the board this item sits on defines, as its own read of the board's
14192    /// `fields` gives them — when the read that reached the item carried them, which a read
14193    /// of it by its own id does. What a write of it needs of the board, then, needs no read
14194    /// of the board.
14195    board_fields: Option<Value>,
14196    /// The far ends of this issue's whole `blockedBy` connection, each as a dependency read
14197    /// selects one — when the read that reached it carried the connection to its end, which a
14198    /// read of it by its own id does for any issue blocked by no more than a page. What a
14199    /// write reconciles that relationship against, and what a read of its forward edges in
14200    /// the same command answers with.
14201    blocked_by: Option<Vec<Value>>,
14202    /// Every person the item is assigned to, by login in the order GitHub answered them — read
14203    /// only by a source opted in to assignees, and `None` for any other, and for a record no
14204    /// read or write of this process showed them on.
14205    #[serde(default)]
14206    assignees: Option<Vec<String>>,
14207}
14208
14209impl Resolved {
14210    /// The board this item's own read names it on, when that read named one this source can
14211    /// address.
14212    fn named_board(&self) -> Option<BoardId> {
14213        self.board_id
14214            .as_deref()
14215            .and_then(|id| BoardId::parse(id).ok())
14216    }
14217
14218    /// The board's id and every field it defines, when the read that reached this item
14219    /// carried both — which a read of it by its own id does.
14220    fn carried_board(&self) -> Option<BoardFields> {
14221        Some(BoardFields {
14222            id: self.named_board()?,
14223            fields: self.board_fields.clone()?,
14224        })
14225    }
14226
14227    /// Whether this item holds a value of the board field called `name`, and so carries
14228    /// that field's definition. `false` says nothing about whether the board has the field.
14229    fn defines(&self, name: &str) -> bool {
14230        self.fields
14231            .iter()
14232            .any(|field| field.get("name").and_then(Value::as_str) == Some(name))
14233    }
14234
14235    /// The metadata a caller sees: their own keys, plus the copy origin this source keeps
14236    /// in a field of its own, and none of the five keys that are only an encoding.
14237    ///
14238    /// The two delivery keys are left out for every kind, not only for a task: they are
14239    /// the encoding of [`Task::delivers`] and [`Task::delivered_by`], and a project or a
14240    /// document carrying one holds nothing a caller's own metadata could mean by it.
14241    fn metadata(&self) -> BTreeMap<String, Value> {
14242        let mut metadata = self.slot.clone();
14243        metadata.remove(Repository::METADATA_KEY);
14244        metadata.remove(DependencyEdge::RECORDED_KEY);
14245        metadata.remove(ItemKind::METADATA_KEY);
14246        metadata.remove(TaskRef::DELIVERS_KEY);
14247        metadata.remove(TaskRef::DELIVERED_BY_KEY);
14248        metadata.remove(Classification::METADATA_KEY);
14249        // The board field is the origin, and the body's copy of it is only a mirror for the
14250        // issue search to find: an item whose field holds none has none, whatever its body
14251        // says, so no reader ever sees two answers.
14252        metadata.remove(ORIGIN_KEY);
14253        if let Some(origin) = &self.origin {
14254            metadata.insert(ORIGIN_KEY.to_owned(), Value::String(origin.clone()));
14255        }
14256        metadata
14257    }
14258
14259    /// Where this item is, as a link a reader can open.
14260    ///
14261    /// A board is a hosted place and every issue on it has a web address, so that address
14262    /// is what "where is this?" means here — and [`Location::Url`] is what says which kind
14263    /// of place it is, so a reader knows to open it rather than to read a file out. It
14264    /// does not replace or derive from `url`: the field goes on reporting exactly what it
14265    /// reported before, and this says what that address *is*.
14266    ///
14267    /// An item GitHub gave no `url` for — a draft has none — reports no location at all
14268    /// rather than a third variant, which is the contract's "the source did not say". An
14269    /// issue this run created is not one of those: its address comes back from the
14270    /// creating mutation, so it is somewhere a reader can open from the moment it exists
14271    /// rather than from whenever the board read catches up.
14272    fn location(&self) -> Option<Location> {
14273        self.url.clone().map(Location::Url)
14274    }
14275
14276    /// The short handle this board's backend shows people for a task: the issue's number
14277    /// alone, as a decimal string.
14278    ///
14279    /// The number alone rather than `owner/repo#1043`, because that is the contract's
14280    /// value for this backend. A draft has no number and so no handle, which is the
14281    /// contract's *absent* rather than a handle of some other shape — and the native
14282    /// [`Task::id`] here is the issue's GraphQL node id, which this neither replaces nor
14283    /// derives from.
14284    fn key(&self) -> Option<String> {
14285        self.number.map(|number| number.to_string())
14286    }
14287
14288    /// This item's change token — see [`change_token`] — or `None` when the read that
14289    /// reached it did not carry all six of its parts, which a draft never does, did not say
14290    /// when GitHub served it, or found it changed too recently to have settled.
14291    fn version(&self) -> Option<String> {
14292        let parts = self.token_parts()?;
14293        change_token::settled(parts.issue, parts.item, self.served_at?)
14294            .then(|| change_token::spell(&parts))
14295    }
14296
14297    /// The change token this item, read just after a write of it, holds now — whether or not it
14298    /// has settled: what a written task's `version` answers (see
14299    /// [`GitHubProjectsSource::written_tokens`]), spelled from the parts a later read spells its
14300    /// token from.
14301    fn written_version(&self) -> Option<String> {
14302        self.token_parts().map(|parts| change_token::spell(&parts))
14303    }
14304
14305    /// Every part of this item's change token, or `None` when the read that reached it did not
14306    /// carry them all — a draft never does.
14307    fn token_parts(&self) -> Option<change_token::Parts> {
14308        match self.content_kind {
14309            ContentKind::Issue => Some(change_token::Parts {
14310                issue: self.updated_at?,
14311                item: self.item_updated_at?,
14312                comments: self.comment_count?,
14313                relationships: self.relationship_events?,
14314                facets: self.facets.clone()?,
14315                repository: self.own_repository.clone()?,
14316            }),
14317            ContentKind::DraftIssue => None,
14318        }
14319    }
14320
14321    /// Whether its `Priority` field holds a value at all, mapped or not.
14322    fn holds_priority(&self) -> bool {
14323        self.priority != HeldPriority::Read(Priority::None)
14324    }
14325
14326    /// The task this item is.
14327    ///
14328    /// Fails for an item whose `Priority` field holds an option the mapping does not name:
14329    /// reading that as a level would be a guess, and reading it as `none` would let the next
14330    /// copy clear a priority a person set.
14331    fn task(&self) -> Result<Task, SourceError> {
14332        let priority = match &self.priority {
14333            HeldPriority::Read(priority) => *priority,
14334            HeldPriority::Unmapped(option) => {
14335                return Err(SourceError::Malformed {
14336                    message: format!(
14337                        "task {}{} sits in the board {PRIORITY_FIELD} option {option:?}, which \
14338                         this source's priority_mapping does not name, so its priority cannot be \
14339                         read; next: name {option:?} under priority_mapping, or move the item to \
14340                         a mapped option",
14341                        self.id,
14342                        self.number
14343                            .map(|number| format!(" (#{number})"))
14344                            .unwrap_or_default()
14345                    ),
14346                });
14347            }
14348        };
14349        let metadata = self.metadata();
14350        Ok(Task {
14351            version: self.version(),
14352            id: self.id.clone(),
14353            key: self.key(),
14354            title: self.title.clone(),
14355            // The `## Links` section the engine rendered is stripped, so content round-trips.
14356            content: onetaskgraph_plugin_api::read_content(self.body.clone(), &metadata),
14357            status: self.status.clone(),
14358            priority,
14359            labels: self.labels.clone(),
14360            project: self.parent.clone(),
14361            url: self.url.clone(),
14362            location: self.location(),
14363            created_at: self.created_at,
14364            updated_at: self.updated_at,
14365            metadata,
14366            repositories: self.repositories.clone(),
14367            delivers: self.delivers.clone(),
14368            delivered_by: self.delivered_by.clone(),
14369            classification: self.classification,
14370            assignees: self.assignees.clone(),
14371        })
14372    }
14373
14374    fn project(&self) -> Project {
14375        Project {
14376            version: self.version(),
14377            id: self.id.clone(),
14378            title: self.title.clone(),
14379            content: self.body.clone(),
14380            status: self.status.clone(),
14381            labels: self.labels.clone(),
14382            url: self.url.clone(),
14383            location: self.location(),
14384            created_at: self.created_at,
14385            updated_at: self.updated_at,
14386            metadata: self.metadata(),
14387            repositories: self.repositories.clone(),
14388            classification: self.classification,
14389        }
14390    }
14391
14392    /// The same issue as a document: the project it is filed under, and no status and no
14393    /// dependencies, because a document is not work.
14394    fn document(&self) -> Document {
14395        Document {
14396            version: self.version(),
14397            id: self.id.clone(),
14398            title: self.title.clone(),
14399            content: self.body.clone(),
14400            project: self.parent.clone(),
14401            labels: self.labels.clone(),
14402            url: self.url.clone(),
14403            location: self.location(),
14404            created_at: self.created_at,
14405            updated_at: self.updated_at,
14406            metadata: self.metadata(),
14407            repositories: self.repositories.clone(),
14408            classification: self.classification,
14409        }
14410    }
14411}
14412
14413/// Where one targeted update moves an item's status, and which of its two halves move.
14414struct StatusMove {
14415    /// The board the item's `Status` field is on.
14416    board: BoardId,
14417    /// The `Status` field's id.
14418    field: String,
14419    /// The option's id.
14420    option: String,
14421    /// The option's name, as the board spells it.
14422    name: String,
14423    /// What the status asks of the issue's state.
14424    target: StatusTarget,
14425    /// The status the item reads as once it is there.
14426    landed: Status,
14427    /// Which of the status's two halves differ from what the item holds.
14428    moves: Moves,
14429}
14430
14431/// Which halves of an item's status one targeted update moves: its `Status` option, the open or
14432/// closed state of its issue, or both. A status neither half of which differs is no move at all,
14433/// and is not a value of this type.
14434#[derive(Clone, Copy, PartialEq, Eq)]
14435enum Moves {
14436    /// The option alone.
14437    Option,
14438    /// The issue's state alone: open, closed, or closed with another reason.
14439    State,
14440    /// Both.
14441    Both,
14442}
14443
14444impl Moves {
14445    /// What differs, or `None` when nothing does.
14446    const fn of(option: bool, state: bool) -> Option<Self> {
14447        match (option, state) {
14448            (true, true) => Some(Self::Both),
14449            (true, false) => Some(Self::Option),
14450            (false, true) => Some(Self::State),
14451            (false, false) => None,
14452        }
14453    }
14454
14455    /// Whether the option moves.
14456    const fn option(self) -> bool {
14457        matches!(self, Self::Option | Self::Both)
14458    }
14459
14460    /// Whether the issue's state moves.
14461    const fn state(self) -> bool {
14462        matches!(self, Self::State | Self::Both)
14463    }
14464}
14465
14466/// What one write is, and the status that comes with being it.
14467///
14468/// One value rather than a [`BoardKind`] beside an `Option<Status>`: a document has no
14469/// status and a task or a project always has one, so "a document carrying a status" and
14470/// "a task carrying none" are states a write cannot be in rather than states every use
14471/// site below has to defend against.
14472enum Written<'a> {
14473    /// A document, which is not work and so has no status at all.
14474    Document,
14475    /// A task or a project, and the status it is being written with.
14476    Work(ItemKind, &'a Status),
14477}
14478
14479impl Written<'_> {
14480    /// Which of the board's three kinds this write is.
14481    const fn kind(&self) -> BoardKind {
14482        match self {
14483            Self::Document => BoardKind::Document,
14484            Self::Work(kind, _) => BoardKind::Work(*kind),
14485        }
14486    }
14487
14488    /// The status this write carries. A document carries none, so a write of one says
14489    /// nothing about the issue's open or closed state and selects no board `Status`
14490    /// option.
14491    const fn status(&self) -> Option<&Status> {
14492        match self {
14493            Self::Document => None,
14494            Self::Work(_, status) => Some(status),
14495        }
14496    }
14497
14498    /// The status this write carries with the kind whose half of `status_mapping` it is
14499    /// written through.
14500    const fn work_status(&self) -> Option<(ItemKind, &Status)> {
14501        match self {
14502            Self::Document => None,
14503            Self::Work(kind, status) => Some((*kind, status)),
14504        }
14505    }
14506}
14507
14508/// The item being written, in the one shape all three write methods reach.
14509struct Incoming<'a> {
14510    written: Written<'a>,
14511    /// The title a person wrote. A document's goes onto the issue with
14512    /// [`DESIGN_TITLE_PREFIX`] put back, so a round trip returns the title that went in.
14513    title: &'a str,
14514    content: Option<&'a str>,
14515    assets: Option<&'a onetaskgraph_plugin_api::AssetWrite>,
14516    labels: &'a [Label],
14517    metadata: &'a BTreeMap<String, Value>,
14518    repositories: &'a [Repository],
14519    /// Recorded in the slot while private, and nowhere while public.
14520    classification: Classification,
14521    parent: Option<&'a NativeId>,
14522    /// [`Task::delivers`], already checked. Empty for a project or a document, which is
14523    /// what keeps either key out of their slot.
14524    delivers: &'a [TaskRef],
14525    /// [`Task::delivered_by`], already checked. Empty for a project or a document.
14526    delivered_by: &'a [TaskRef],
14527    /// [`Task::priority`], for a task written to an instance that holds one; `None` for a
14528    /// project, a document, and every write to an instance with no `priority_mapping` —
14529    /// which is what keeps such a write's requests exactly what they were before.
14530    priority: Option<Priority>,
14531    /// [`Task::assignees`] of a task written to a source opted in to them — the people it is
14532    /// to be assigned to, replacing whoever it holds — and `None` for everything else, which
14533    /// leaves an existing item's as they are and creates one unassigned.
14534    assignees: Option<&'a [String]>,
14535}
14536
14537/// What one write does to one projected metadata text field, by the field's id.
14538#[derive(Debug, Clone)]
14539enum ProjectionWrite {
14540    /// Write this text.
14541    Set {
14542        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.
14543        text: String,
14544    },
14545    /// Clear the field's value.
14546    Clear { field: String }, // llmlint: ignore[invalid_states_unrepresentable] As above.
14547}
14548
14549impl ProjectionWrite {
14550    /// Add this write to a field write's list of values and list of clears.
14551    fn join<'a>(&'a self, values: &mut Vec<(String, Value)>, clears: &mut Vec<&'a str>) {
14552        match self {
14553            Self::Set { field, text } => values.push((field.clone(), json!({"text": text}))),
14554            Self::Clear { field } => clears.push(field),
14555        }
14556    }
14557}
14558
14559/// What one write does to an item's `Priority` field.
14560enum PriorityWrite {
14561    /// Select this option of this field.
14562    Select {
14563        /// The `Priority` field's id.
14564        field: String,
14565        /// The mapped option's id.
14566        option: String,
14567    },
14568    /// Clear the field's value, which is what `none` is.
14569    Clear {
14570        /// The `Priority` field's id.
14571        field: String,
14572    },
14573}
14574
14575impl Incoming<'_> {
14576    /// The title this write puts on the issue.
14577    fn written_title(&self) -> String {
14578        match self.written {
14579            Written::Document => format!("{DESIGN_TITLE_PREFIX}{}", self.title),
14580            Written::Work(..) => self.title.to_owned(),
14581        }
14582    }
14583}
14584
14585#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
14586enum ContentKind {
14587    DraftIssue,
14588    Issue,
14589}
14590
14591/// What one board issue is: a document, or the work an [`ItemKind`] names.
14592///
14593/// A type of this source's own rather than an `ItemKind` with a third variant, because
14594/// `ItemKind` names what a dependency endpoint points at and nothing may point at a
14595/// document — the contract keeps a document out of that enum deliberately. Holding the
14596/// board's three answers in one value is what makes every place that asks "which is this?"
14597/// answer all three, rather than a `document: bool` beside a `kind` that means nothing for
14598/// two thirds of the board.
14599#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
14600enum BoardKind {
14601    /// An issue whose title begins [`DESIGN_TITLE_PREFIX`].
14602    Document,
14603    /// Every other issue, and every draft.
14604    Work(ItemKind),
14605}
14606
14607impl BoardKind {
14608    /// The kind of an item titled `title`, filed under a project or not, holding `sub_issues`
14609    /// sub-issues and carrying the kind marker `marked` in its slot.
14610    ///
14611    /// The design prefix is read *first*, before either of the two rules that separate a
14612    /// project from a task. A document is not work whatever sub-issues it has and whatever
14613    /// marker it carries, and reading the prefix later would make a design issue with none of
14614    /// either an empty project. Being a sub-issue wins outright over the rest, and no marker
14615    /// overrides it: an issue filed under a project is that project's task even when it has
14616    /// sub-issues of its own.
14617    fn of(title: &str, filed: bool, sub_issues: u64, marked: Option<ItemKind>) -> Self {
14618        if title.starts_with(DESIGN_TITLE_PREFIX) {
14619            Self::Document
14620        } else if filed {
14621            Self::Work(ItemKind::Task)
14622        } else if sub_issues > 0 || marked == Some(ItemKind::Project) {
14623            Self::Work(ItemKind::Project)
14624        } else {
14625            Self::Work(ItemKind::Task)
14626        }
14627    }
14628
14629    /// What the change token's facets call this kind.
14630    const fn facet(self) -> change_token::FacetKind {
14631        match self {
14632            Self::Document => change_token::FacetKind::Document,
14633            Self::Work(ItemKind::Project) => change_token::FacetKind::Project,
14634            Self::Work(ItemKind::Task) => change_token::FacetKind::Task,
14635        }
14636    }
14637
14638    /// Whose half of `status_mapping` an item of this kind reads its status through. A
14639    /// document has no status of its own, so the task half stands in for whatever the issue
14640    /// holds; nothing reports it.
14641    const fn status_kind(self) -> ItemKind {
14642        match self {
14643            Self::Document => ItemKind::Task,
14644            Self::Work(kind) => kind,
14645        }
14646    }
14647
14648    /// How a refusal names this kind to the person reading it.
14649    const fn describes(self) -> &'static str {
14650        match self {
14651            Self::Document => "document",
14652            Self::Work(kind) => kind.marker(),
14653        }
14654    }
14655}
14656
14657/// Whether `labels` satisfies `filter`, matching by name, case-insensitively.
14658///
14659/// This is the local Markdown source's `labels_match`, spelled the same way on purpose:
14660/// the shared cross-source journeys assert one answer to one question, so two sources
14661/// that disagree about what "carries the label bug" means fail them.
14662fn labels_match(labels: &[Label], filter: &LabelFilter) -> bool {
14663    let holds = |name: &String| {
14664        labels
14665            .iter()
14666            .any(|label| label.name.eq_ignore_ascii_case(name))
14667    };
14668    (filter.any_of.is_empty() || filter.any_of.iter().any(holds))
14669        && filter.all_of.iter().all(holds)
14670        && !filter.none_of.iter().any(holds)
14671}
14672
14673/// Whether `category` is one of `statuses`. An empty list is unfiltered rather than
14674/// "keeps nothing", which is what lets a `Vec<StatusCategory>` spell no filter at all.
14675fn status_matches(category: StatusCategory, statuses: &[StatusCategory]) -> bool {
14676    statuses.is_empty() || statuses.contains(&category)
14677}
14678
14679/// Whether `title`/`content` satisfies `query`, matching case-insensitively.
14680///
14681/// `content` is the item's own prose — the body with this source's trailing metadata
14682/// comment already taken off — so a search never matches an encoding the author of the
14683/// issue never wrote.
14684fn text_matches(title: &str, content: Option<&str>, query: &TextQuery) -> bool {
14685    let terms = query.terms.to_lowercase();
14686    let in_title = title.to_lowercase().contains(&terms);
14687    let in_content = content.is_some_and(|body| body.to_lowercase().contains(&terms));
14688    match query.fields {
14689        TextFields::Title => in_title,
14690        TextFields::Content => in_content,
14691        TextFields::TitleOrContent => in_title || in_content,
14692    }
14693}
14694
14695/// Whether `task` satisfies `query`, with `project` deciding the project predicate.
14696///
14697/// The project predicate is passed separately because a read narrowed to one project has
14698/// already answered it by asking *that project* for its own items — and re-applying it
14699/// there would compare the caller's selector, which may be a project's **name**, against
14700/// the id of the project that name resolved to, and keep nothing. Every other read passes
14701/// `query.project` and applies it here, which is what keeps `projects` a predicate this
14702/// source really does apply.
14703fn task_matches(task: &Task, query: &TaskQuery, project: &ProjectFilter) -> bool {
14704    labels_match(&task.labels, &query.labels)
14705        && status_matches(task.status.category, &query.statuses)
14706        && (query.priorities.is_empty() || query.priorities.contains(&task.priority))
14707        && match project {
14708            ProjectFilter::Any => true,
14709            ProjectFilter::Orphans => task.project.is_none(),
14710            ProjectFilter::Is(id) => task.project.as_ref() == Some(id),
14711        }
14712        && query
14713            .text
14714            .as_ref()
14715            .is_none_or(|text| text_matches(&task.title, task.content.as_deref(), text))
14716        // Against the parsed metadata slot, and against the origin field, which is where
14717        // `Resolved::metadata` reads each of them from.
14718        && query.metadata_matches(&task.metadata)
14719        && query.origin_matches(&task.metadata)
14720}
14721
14722fn project_matches(project: &Project, query: &ProjectQuery) -> bool {
14723    labels_match(&project.labels, &query.labels)
14724        && status_matches(project.status.category, &query.statuses)
14725        && query
14726            .text
14727            .as_ref()
14728            .is_none_or(|text| text_matches(&project.title, project.content.as_deref(), text))
14729}
14730
14731/// The same three predicates a task query carries, minus the status filter.
14732///
14733/// A document is not work, so it has no status for one to compare against and the query
14734/// type carries none. The project predicate is the same one — a design issue filed under a
14735/// project issue is in that project, and one filed under nothing is in none — so it is
14736/// spelled the same way here rather than answered differently.
14737fn document_matches(document: &Document, query: &DocumentQuery, project: &ProjectFilter) -> bool {
14738    labels_match(&document.labels, &query.labels)
14739        && match project {
14740            ProjectFilter::Any => true,
14741            ProjectFilter::Orphans => document.project.is_none(),
14742            ProjectFilter::Is(id) => document.project.as_ref() == Some(id),
14743        }
14744        && query
14745            .text
14746            .as_ref()
14747            .is_none_or(|text| text_matches(&document.title, document.content.as_deref(), text))
14748}
14749
14750/// Why a GitHub item's change token does not vouch for its forward edges.
14751///
14752/// A forward edge names its far end and that far end's kind, and the near item's token moves
14753/// with the edges it holds but says nothing of the far ends themselves: a far end turning from a
14754/// task into a project when it gains a sub-issue, retitled into a document, or deleted moves
14755/// nothing the near token reads, so an edge kept at the near version could name a far end that
14756/// is no longer what it said.
14757const FAR_ENDS_UNCOVERED: &str = "a github item's change token does not attest a far end's kind, \
14758     whether it became a document, or its deletion, so its forward edges are always read from \
14759     github";
14760
14761/// The issue-search qualifier that keeps open issues alone, which a status filter naming only
14762/// categories an open issue reads as narrows a board-scoped search with.
14763const OPEN_QUALIFIER: &str = "is:open";
14764
14765/// What the board's open items are held under among the narrowed answers of one command — a
14766/// key no [`Narrowing`], each `origin …` or `search …`, can spell.
14767const OPEN_ITEMS_KEY: &str = "items is:open";
14768
14769/// The board filter `task status reconcile` reads the board through: closed items alone.
14770const CLOSED_FILTER: &str = "is:closed";
14771
14772/// The variables of one [`graphql::ISSUES_BY_REFERENCE`] request for `batch`: each slot names
14773/// one reference, and a slot the batch has none for names its last one again.
14774fn reference_batch(batch: &[IssueRef]) -> Value {
14775    let mut variables = serde_json::Map::new();
14776    for slot in 0..REFERENCE_BATCH {
14777        let issue = batch.get(slot).or(batch.last());
14778        variables.insert(format!("owner{slot}"), json!(issue.map(|i| &i.owner)));
14779        variables.insert(format!("name{slot}"), json!(issue.map(|i| &i.name)));
14780        variables.insert(format!("number{slot}"), json!(issue.map(|i| i.number)));
14781    }
14782    variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
14783    variables.insert("statusField".to_owned(), json!(STATUS_FIELD));
14784    variables.insert("duplicates".to_owned(), json!(true));
14785    Value::Object(variables)
14786}
14787
14788/// One issue an issue read by reference answered, in the shape every other read of an issue
14789/// hands its resolver: each board membership's `Status` value, read by name, as the one field
14790/// value that membership carries.
14791///
14792/// A membership's `status` is `null` when its card sits at no option — or on a board with no
14793/// field of that name — and otherwise an option value naming its option; anything else is not
14794/// an answer to this read, and is refused rather than read as a card at no option.
14795fn held_issue(issue: &Value) -> Result<Value, SourceError> {
14796    let malformed = |what: &str| SourceError::Malformed {
14797        message: format!("GitHub answered an issue read by reference with {what}"),
14798    };
14799    let mut issue = issue.clone();
14800    let nodes = issue
14801        .pointer_mut("/projectItems/nodes")
14802        .and_then(Value::as_array_mut)
14803        .ok_or_else(|| malformed("no list of board memberships"))?;
14804    for node in nodes {
14805        let node = node
14806            .as_object_mut()
14807            .ok_or_else(|| malformed("a board membership that is not an object"))?;
14808        let status = match node.get("status") {
14809            None => return Err(malformed("a board membership with no status member")),
14810            Some(Value::Null) => None,
14811            Some(status) if status.get("name").is_some_and(Value::is_string) => {
14812                Some(status.clone())
14813            }
14814            // A single-select value of another field type answers `{}`; only an option value
14815            // carries a name.
14816            Some(status) if status.as_object().is_some_and(serde_json::Map::is_empty) => None,
14817            Some(_) => return Err(malformed("a membership status that names no option")),
14818        };
14819        node.insert(
14820            "fieldValues".to_owned(),
14821            json!({"nodes": status.into_iter().collect::<Vec<_>>(),
14822                   "pageInfo": {"hasNextPage": false}}),
14823        );
14824    }
14825    Ok(issue)
14826}
14827
14828/// The issue one slot of a read by reference answered, `None` when GitHub answered that
14829/// slot's repository or issue `null` — which [`GitHubProjectsSource::answer_unresolved`]
14830/// admitted only beside a `NOT_FOUND` naming that very slot — and a refusal when the answer
14831/// leaves the slot, or its `issue` member, out: an answer missing a member is malformed rather
14832/// than a reference nothing holds.
14833fn referenced_issue(data: &Value, slot: usize) -> Result<Option<&Value>, SourceError> {
14834    let alias = format!("r{slot}");
14835    let repository = data.get(&alias).ok_or_else(|| SourceError::Malformed {
14836        message: format!("GitHub answered a read by reference with no {alias}"),
14837    })?;
14838    if repository.is_null() {
14839        return Ok(None);
14840    }
14841    let issue = repository
14842        .get("issue")
14843        .ok_or_else(|| SourceError::Malformed {
14844            message: format!("GitHub answered {alias} of a read by reference with no issue"),
14845        })?;
14846    if issue.is_null() {
14847        return Ok(None);
14848    }
14849    // `Repository.issue` is typed `Issue`, so anything else is not an answer to this read.
14850    if optional_str(issue, "__typename")? != Some("Issue") {
14851        return Err(SourceError::Malformed {
14852            message: format!(
14853                "GitHub answered {alias} of a read by reference with an issue whose __typename \
14854                 is not Issue"
14855            ),
14856        });
14857    }
14858    Ok(Some(issue))
14859}
14860
14861/// A closure reason as a person reads it: `NOT_PLANNED` as `not planned`.
14862fn spoken_reason(reason: &str) -> String {
14863    reason.to_ascii_lowercase().replace('_', " ")
14864}
14865
14866impl GitHubProjectsSource {
14867    /// Every task and project of this board whose card contradicts its issue's closure, each
14868    /// judged against its own kind's half of `status_mapping`, read through the board's own
14869    /// `is:closed` filter, page by page — never the board's unfiltered `items`.
14870    ///
14871    /// Each item the filter answers is confirmed from its own node: an open one, one whose
14872    /// closure reads `unknown`, and one whose card is already in line are left out whatever
14873    /// the filter let through. The board's fields ride along and are held for the option
14874    /// writes that follow, so those need no read of the board.
14875    async fn contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
14876        let mut after: Option<String> = None;
14877        let mut found = Vec::new();
14878        loop {
14879            let data = self
14880                .graphql(
14881                    graphql::CLOSED_ITEMS,
14882                    json!({"owner":self.owner,"number":self.project_number,
14883                           "first":MAX_PAGE_SIZE,"after":after,"filter":CLOSED_FILTER,
14884                           "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
14885                )
14886                .await?;
14887            let board = data
14888                .pointer("/closedItems/projectV2")
14889                .filter(|value| !value.is_null())
14890                .ok_or_else(|| SourceError::Refused {
14891                    message: format!(
14892                        "GitHub project {}/{} was not found or is not visible to the token",
14893                        self.owner, self.project_number
14894                    ),
14895                })?;
14896            *self.fields_cache()? = Some(BoardFields {
14897                id: BoardId::parse(required_str(board, "id")?)?,
14898                fields: board.get("fields").cloned().unwrap_or(Value::Null),
14899            });
14900            let items = board.get("items").ok_or_else(|| SourceError::Malformed {
14901                message: "GitHub project closed items are missing".into(),
14902            })?;
14903            for item in items
14904                .get("nodes")
14905                .and_then(Value::as_array)
14906                .ok_or_else(|| SourceError::Malformed {
14907                    message: "GitHub project items.nodes is not an array".into(),
14908                })?
14909            {
14910                let Some(resolved) = self.resolve(item)? else {
14911                    continue;
14912                };
14913                let BoardKind::Work(kind) = resolved.kind else {
14914                    continue;
14915                };
14916                let Some((closed_as, name)) = self.statuses.contradicted(
14917                    kind,
14918                    resolved.option.as_deref(),
14919                    resolved.closed,
14920                    resolved.reason.as_deref(),
14921                ) else {
14922                    continue;
14923                };
14924                found.push(StatusContradiction {
14925                    closed_as,
14926                    to: name.to_owned(),
14927                    option: resolved.option.clone(),
14928                    item: match kind {
14929                        ItemKind::Task => ContradictedItem::Task(resolved.task()?),
14930                        ItemKind::Project => ContradictedItem::Project(resolved.project()),
14931                    },
14932                });
14933            }
14934            let info = items
14935                .get("pageInfo")
14936                .ok_or_else(|| SourceError::Malformed {
14937                    message: "GitHub project items have no pageInfo".into(),
14938                })?;
14939            if !required_bool(info, "hasNextPage")? {
14940                return Ok(found);
14941            }
14942            let next = required_str(info, "endCursor")?;
14943            validate_cursor_progress(after.as_deref(), next)?;
14944            after = Some(next.to_owned());
14945        }
14946    }
14947
14948    /// What this board holds for each issue in `issues`, once each in the order given, read
14949    /// [`REFERENCE_BATCH`] references at a time — and nothing else of the board.
14950    ///
14951    /// An issue GitHub cannot find for this source's credential, and one with no item on this
14952    /// board, are both absent. A closure that already says the work will not be done here —
14953    /// not planned, duplicate — is skipped: a landing does not overrule it. An item closed as
14954    /// completed whose card sits at its kind's `done` option is unchanged, and every other item
14955    /// is due a `done` write. A project item — a plan's home card, its issue holding the plan's
14956    /// tasks as sub-issues — is held under exactly these rules, judged against the project
14957    /// kind's half of `status_mapping`.
14958    async fn holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
14959        let mut distinct: Vec<IssueRef> = Vec::with_capacity(issues.len());
14960        for issue in issues {
14961            if !distinct.contains(issue) {
14962                distinct.push(issue.clone());
14963            }
14964        }
14965        let done = |kind: ItemKind| {
14966            self.statuses
14967                .target(kind, StatusCategory::Done)
14968                .option()
14969                .unwrap_or("Done")
14970                .to_owned()
14971        };
14972        // GitHub numbers an issue with a GraphQL `Int`, a signed 32-bit value, so a reference past
14973        // its range names no issue any repository can hold: it is answered absent and never sent,
14974        // where binding it would have GitHub refuse the whole batch.
14975        let readable: Vec<IssueRef> = distinct
14976            .iter()
14977            .filter(|issue| i32::try_from(issue.number).is_ok())
14978            .cloned()
14979            .collect();
14980        let mut holdings = Vec::with_capacity(readable.len());
14981        for batch in readable.chunks(REFERENCE_BATCH) {
14982            let data = self
14983                .graphql(graphql::ISSUES_BY_REFERENCE, reference_batch(batch))
14984                .await?;
14985            for (slot, issue) in batch.iter().enumerate() {
14986                let node = referenced_issue(&data, slot)?;
14987                let resolved = match node {
14988                    Some(node) => self.resolve_issue_as(&held_issue(node)?, false).await?,
14989                    None => None,
14990                };
14991                // A task and a project are both held; a document is not work, so nothing is.
14992                let Some((item, kind)) = resolved.and_then(|item| match item.kind {
14993                    BoardKind::Work(kind) => Some((item, kind)),
14994                    BoardKind::Document => None,
14995                }) else {
14996                    holdings.push(IssueHolding {
14997                        issue: issue.clone(),
14998                        completion: Completion::Absent,
14999                    });
15000                    continue;
15001                };
15002                let task = match kind {
15003                    ItemKind::Task => {
15004                        let held = item.task()?;
15005                        HeldTask {
15006                            id: held.id,
15007                            kind,
15008                            option: item.option.clone(),
15009                            classification: held.classification,
15010                            repositories: held.repositories,
15011                            delivers: held.delivers,
15012                        }
15013                    }
15014                    // A project delivers no task, so what its write keeps in step is nothing.
15015                    ItemKind::Project => {
15016                        let held = item.project();
15017                        HeldTask {
15018                            id: held.id,
15019                            kind,
15020                            option: item.option.clone(),
15021                            classification: held.classification,
15022                            repositories: held.repositories,
15023                            delivers: Vec::new(),
15024                        }
15025                    }
15026                };
15027                let done = done(kind);
15028                let completion = match (item.closed, item.reason.as_deref()) {
15029                    (true, Some(reason @ ("NOT_PLANNED" | "DUPLICATE"))) => Completion::Skipped {
15030                        task,
15031                        reason: format!("closed as {}", spoken_reason(reason)),
15032                    },
15033                    (true, None | Some("COMPLETED"))
15034                        if item
15035                            .option
15036                            .as_deref()
15037                            .is_some_and(|option| option.eq_ignore_ascii_case(&done)) =>
15038                    {
15039                        Completion::Unchanged { task }
15040                    }
15041                    _ => {
15042                        let kept = item.clone();
15043                        self.held_cache
15044                            .lock()
15045                            .map_err(|_| SourceError::Unavailable {
15046                                message: "items read by issue reference were left \
15047                                          inconsistent; run the command again"
15048                                    .into(),
15049                            })?
15050                            .insert(kept.id.clone(), kept);
15051                        Completion::Due {
15052                            task,
15053                            to: done.clone(),
15054                        }
15055                    }
15056                };
15057                holdings.push(IssueHolding {
15058                    issue: issue.clone(),
15059                    completion,
15060                });
15061            }
15062        }
15063        let mut read = holdings.into_iter();
15064        let mut answered = Vec::with_capacity(distinct.len());
15065        for issue in distinct {
15066            if i32::try_from(issue.number).is_ok() {
15067                answered.push(read.next().ok_or_else(|| SourceError::Malformed {
15068                    message: format!("no holding was read for {issue}"),
15069                })?);
15070            } else {
15071                answered.push(IssueHolding {
15072                    issue,
15073                    completion: Completion::Absent,
15074                });
15075            }
15076        }
15077        Ok(answered)
15078    }
15079}
15080
15081#[async_trait::async_trait]
15082impl TaskSource for GitHubProjectsSource {
15083    fn kind(&self) -> &'static str {
15084        KIND
15085    }
15086    /// GitHub's issue search, which narrows a read of the comments made since an instant, is
15087    /// an index behind the writes it indexes — the credentialed lane has watched it miss a newly
15088    /// commented issue for thirty seconds — so a watermark is set back by
15089    /// [`COMMENT_SEARCH_LAG`], four times that.
15090    fn comment_consistency_window(&self) -> std::time::Duration {
15091        COMMENT_SEARCH_LAG
15092    }
15093    /// The `Date` of the last answer GitHub gave this source.
15094    fn served_at(&self) -> Option<DateTime<Utc>> {
15095        *self
15096            .last_served
15097            .lock()
15098            .unwrap_or_else(std::sync::PoisonError::into_inner)
15099    }
15100    fn attach_body_markup(&self, markup: onetaskgraph_plugin_api::SharedBodyMarkup) {
15101        let _ = self.body_markup.set(markup);
15102    }
15103    fn order_versions(&self, a: &str, b: &str) -> Option<std::cmp::Ordering> {
15104        change_token::order(a, b)
15105    }
15106    /// A task's fields and comments: §4.13d of `docs/plugin-protocol.md` states, member by
15107    /// member, the change each part of the token moves for. Not its forward edges — see
15108    /// [`FAR_ENDS_UNCOVERED`].
15109    fn version_coverage(&self) -> VersionCoverage {
15110        VersionCoverage {
15111            forward_edges: Coverage::Uncovered {
15112                reason: FAR_ENDS_UNCOVERED.to_owned(),
15113            },
15114            ..VersionCoverage::whole()
15115        }
15116    }
15117    /// Every part, for a copy's skip: the relationship count moves for an edge added or removed
15118    /// and for a far end deleted, so the token sees every change to a task's edges but one — a
15119    /// far end's own kind flipping, by gaining a sub-issue or being retitled into a document,
15120    /// which `spike-coverage` measured stale 1 of 1. A skipping recopy does not carry that, and
15121    /// the next copy that reads the task does (`docs/plugin-protocol.md` §4.13d).
15122    // 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.
15123    fn copy_version_coverage(&self) -> VersionCoverage {
15124        VersionCoverage::whole()
15125    }
15126    /// A project's fields, and not its forward edges, for the same reason a task's are not.
15127    fn project_version_coverage(&self) -> ProjectVersionCoverage {
15128        ProjectVersionCoverage {
15129            fields: Coverage::Covered,
15130            forward_edges: Coverage::Uncovered {
15131                reason: FAR_ENDS_UNCOVERED.to_owned(),
15132            },
15133        }
15134    }
15135    /// A document's fields and the manifest of its image assets, which its metadata slot
15136    /// records: both are the issue's body, whose every edit moves the token's issue time.
15137    fn document_version_coverage(&self) -> DocumentVersionCoverage {
15138        DocumentVersionCoverage::whole()
15139    }
15140    fn write_context(&self, id: &NativeId) -> Option<Value> {
15141        self.context_of(id)
15142    }
15143    fn board_context(&self) -> Option<Value> {
15144        self.board_context_held()
15145    }
15146    fn prime_write(&self, id: &NativeId, context: &Value, board: Option<&Value>) -> bool {
15147        self.prime(id, context, board)
15148    }
15149    fn unprime(&self, id: &NativeId) {
15150        self.unprime_held(id);
15151    }
15152    fn placement_context(&self) -> Option<Value> {
15153        self.placement_held()
15154    }
15155    fn prime_placement(&self, context: &Value) -> bool {
15156        self.prime_placement_held(context)
15157    }
15158    fn written_context(&self, id: &NativeId) -> Option<Value> {
15159        self.written_held(id)
15160    }
15161    fn prime_written(&self, id: &NativeId, context: &Value, task: &Task) -> bool {
15162        self.prime_written_held(id, context, task)
15163    }
15164    fn begin_journal(&self) {
15165        self.expected.begin();
15166    }
15167    fn end_journal(&self) -> Option<WriteJournal> {
15168        Some(self.expected.end())
15169    }
15170    fn capabilities(&self) -> Capabilities {
15171        Capabilities {
15172            projects: Support::Native,
15173            documents: Support::Native,
15174            comments: Support::Native,
15175            assets: Support::Native,
15176            priority: if self.priorities.is_some() {
15177                Support::Native
15178            } else {
15179                Support::Unsupported
15180            },
15181            filter_by_priority: Support::Native,
15182            filter_by_comment_activity: Support::Native,
15183            filter_by_metadata: Support::Native,
15184            filter_by_origin: Support::Native,
15185            reconcile_status: Support::Native,
15186            complete_by_issue: Support::Native,
15187            orphan_tasks: Support::Native,
15188            filter_by_label: Support::Native,
15189            filter_by_status: Support::Native,
15190            search_title: Support::Native,
15191            search_content: Support::Native,
15192            task_dependencies: DependencySupport::BothDirections,
15193            project_dependencies: DependencySupport::BothDirections,
15194            max_page_size: MAX_PAGE_SIZE,
15195            assignees: if self.assignees {
15196                Support::Native
15197            } else {
15198                Support::Unsupported
15199            },
15200        }
15201    }
15202    async fn visibility(
15203        &self,
15204        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15205    ) -> Result<onetaskgraph_plugin_api::Visibility, SourceError> {
15206        self.write_visibility(target).await
15207    }
15208    async fn visibility_with_project(
15209        &self,
15210        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15211        project: &onetaskgraph_plugin_api::WriteTarget<'_>,
15212    ) -> Result<onetaskgraph_plugin_api::Visibility, SourceError> {
15213        self.write_visibility_with_project(target, project).await
15214    }
15215    fn declare_visibility(&self, declared: onetaskgraph_plugin_api::Visibility) {
15216        self.declared_private.store(
15217            declared == onetaskgraph_plugin_api::Visibility::Private,
15218            std::sync::atomic::Ordering::SeqCst,
15219        );
15220    }
15221    fn scope_visibility<'a>(
15222        &'a self,
15223        operation: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>>,
15224    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>> {
15225        self.scope_visibility_reads(operation)
15226    }
15227
15228    /// Where a create of `target` would file its issue, by [`Self::creation_rule`] — the rule
15229    /// the create applies — reading the parent project's issue only when `target` names one.
15230    async fn creation_repository(
15231        &self,
15232        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15233    ) -> Result<Option<Repository>, SourceError> {
15234        let onetaskgraph_plugin_api::WriteTarget::New {
15235            repositories,
15236            project,
15237        } = target
15238        else {
15239            return Ok(None);
15240        };
15241        let target = self
15242            .creation_rule(repositories, *project, "a new item")
15243            .await?;
15244        Repository::try_from(target.origin())
15245            .map(Some)
15246            .map_err(|message| SourceError::Malformed { message })
15247    }
15248    /// Every issue of the repository a create of `target` files in whose body carries `key` in
15249    /// its metadata slot, read off that repository's issues newest first back to `since` —
15250    /// never through search, whose index lags a fresh issue by seconds.
15251    async fn created_with_key(
15252        &self,
15253        record: onetaskgraph_plugin_api::MetadataRecord,
15254        key: &str,
15255        since: Option<DateTime<Utc>>,
15256        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15257    ) -> Result<Vec<NativeId>, SourceError> {
15258        let _ = record;
15259        let onetaskgraph_plugin_api::WriteTarget::New {
15260            repositories,
15261            project,
15262        } = target
15263        else {
15264            return Ok(Vec::new());
15265        };
15266        let repository = self
15267            .creation_rule(repositories, *project, "a new item")
15268            .await?;
15269        let wanted = Value::String(key.to_owned());
15270        let mut found = Vec::new();
15271        let mut after: Option<String> = None;
15272        let mut followed = std::collections::HashSet::new();
15273        loop {
15274            let data = self
15275                .graphql(
15276                    graphql::ISSUES_BY_CREATION,
15277                    json!({"owner": repository.owner, "name": repository.name,
15278                           "first": MAX_PAGE_SIZE, "after": after}),
15279                )
15280                .await?;
15281            let issues =
15282                data.pointer("/repository/issues")
15283                    .ok_or_else(|| SourceError::Malformed {
15284                        message: format!(
15285                            "GitHub answered no issues for repository {}",
15286                            repository.slug()
15287                        ),
15288                    })?;
15289            let malformed = |what: &str| SourceError::Malformed {
15290                message: format!(
15291                    "GitHub answered a page of repository {}'s issues {what}",
15292                    repository.slug()
15293                ),
15294            };
15295            let nodes = issues
15296                .get("nodes")
15297                .and_then(Value::as_array)
15298                .ok_or_else(|| malformed("with no list of issues"))?;
15299            let mut older = false;
15300            for node in nodes {
15301                let id = node
15302                    .get("id")
15303                    .and_then(Value::as_str)
15304                    .filter(|id| !id.is_empty())
15305                    .ok_or_else(|| malformed("holding an issue with no id"))?;
15306                let created = optional_time(node, "createdAt")?
15307                    .ok_or_else(|| malformed("holding an issue with no creation time"))?;
15308                if since.is_some_and(|since| created < since) {
15309                    older = true;
15310                    break;
15311                }
15312                let body = match node.get("body") {
15313                    Some(Value::String(body)) => Some(body.clone()),
15314                    Some(Value::Null) => None,
15315                    _ => return Err(malformed("holding an issue with no body member")),
15316                };
15317                let (_, metadata) = metadata_body(body)?;
15318                if metadata.get(MetadataKey::CREATE_KEY) == Some(&wanted) {
15319                    found.push(NativeId(id.to_owned()));
15320                }
15321            }
15322            let next = issues
15323                .pointer("/pageInfo/hasNextPage")
15324                .and_then(Value::as_bool)
15325                .ok_or_else(|| malformed("that does not say whether another follows"))?;
15326            if older || !next {
15327                return Ok(found);
15328            }
15329            // A page that says another follows names where it starts, and never a page already
15330            // read: anything else would ask for the same pages again for ever.
15331            let cursor = issues
15332                .pointer("/pageInfo/endCursor")
15333                .and_then(Value::as_str)
15334                .filter(|cursor| !cursor.is_empty())
15335                .map(str::to_owned);
15336            if cursor
15337                .as_ref()
15338                .is_none_or(|cursor| !followed.insert(cursor.clone()))
15339            {
15340                return Err(SourceError::Malformed {
15341                    message: format!(
15342                        "GitHub answered a page of repository {}'s issues that says another \
15343                         follows without a new cursor to it",
15344                        repository.slug()
15345                    ),
15346                });
15347            }
15348            after = cursor;
15349        }
15350    }
15351
15352    /// `Repository.issues` lists an issue GitHub committed only once its listing catches up.
15353    fn create_key_lags(&self) -> bool {
15354        true
15355    }
15356
15357    /// The task as this process's own latest write of it left it, from the item it recorded
15358    /// that write as — never a request. Its `version` is always `None`: a board's change token
15359    /// is given only once an item has gone unchanged for [`change_token::SETTLED`], which an
15360    /// item this command has just written has not, so no write's own answer can vouch for one.
15361    async fn written_task(&self, id: &NativeId) -> Option<Task> {
15362        let held = self
15363            .created()
15364            .ok()?
15365            .iter()
15366            .find(|held| held.id == *id)
15367            .cloned()
15368            .or_else(|| {
15369                self.updated()
15370                    .ok()?
15371                    .iter()
15372                    .find(|held| held.id == *id)
15373                    .cloned()
15374            })?;
15375        let mut task = held.task().ok()?;
15376        task.version = self.written_token(id);
15377        Some(task)
15378    }
15379
15380    /// Why `creation_owners` refuses a create of `target`, by [`Self::creation_rule`] — read
15381    /// only when the list is not empty, so a source restricting nothing reads nothing.
15382    async fn creation_refusal(
15383        &self,
15384        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15385    ) -> Result<Option<String>, SourceError> {
15386        let onetaskgraph_plugin_api::WriteTarget::New {
15387            repositories,
15388            project,
15389        } = target
15390        else {
15391            return Ok(None);
15392        };
15393        if self.creation_owners.is_empty() {
15394            return Ok(None);
15395        }
15396        let target = self
15397            .creation_rule(repositories, *project, "a new item")
15398            .await?;
15399        Ok(self.owner_refusal(&target))
15400    }
15401
15402    async fn health(&self) -> Result<Health, SourceError> {
15403        let board = self.board_page(None, 1).await?;
15404        Ok(Health {
15405            reachable: true,
15406            detail: Some(format!(
15407                "reading GitHub project {}/{} ({})",
15408                self.owner,
15409                self.project_number,
15410                required_str(&board, "title")?
15411            )),
15412        })
15413    }
15414    /// The board's own node id, digested: the one request reading its fields, or none when
15415    /// this command has read them already.
15416    async fn designator(&self) -> Result<Option<Designator>, SourceError> {
15417        let board = self.board_fields().await?;
15418        Designator::of_backend(KIND, board.id.as_str())
15419            .map(Some)
15420            .map_err(|message| SourceError::Malformed { message })
15421    }
15422    async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError> {
15423        self.item_by_id(id)
15424            .await?
15425            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
15426            .map(|item| item.task())
15427            .transpose()
15428    }
15429    async fn task_assets(
15430        &self,
15431        id: &NativeId,
15432    ) -> Result<Vec<onetaskgraph_plugin_api::Asset>, SourceError> {
15433        self.held_assets(id, BoardKind::Work(ItemKind::Task)).await
15434    }
15435    async fn task_asset(
15436        &self,
15437        id: &NativeId,
15438        name: &onetaskgraph_plugin_api::AssetName,
15439    ) -> Result<Option<Vec<u8>>, SourceError> {
15440        self.held_asset(id, BoardKind::Work(ItemKind::Task), name)
15441            .await
15442    }
15443    async fn set_task_rendering_with_assets(
15444        &self,
15445        id: &NativeId,
15446        content: &str,
15447        provenance: &Value,
15448        _answers: &BTreeMap<String, Value>,
15449        assets: &onetaskgraph_plugin_api::AssetWrite,
15450    ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
15451        self.replace_rendering(
15452            id,
15453            BoardKind::Work(ItemKind::Task),
15454            content,
15455            provenance,
15456            Some(assets),
15457        )
15458        .await
15459    }
15460    async fn document_assets(
15461        &self,
15462        id: &NativeId,
15463    ) -> Result<Vec<onetaskgraph_plugin_api::Asset>, SourceError> {
15464        self.held_assets(id, BoardKind::Document).await
15465    }
15466    async fn document_asset(
15467        &self,
15468        id: &NativeId,
15469        name: &onetaskgraph_plugin_api::AssetName,
15470    ) -> Result<Option<Vec<u8>>, SourceError> {
15471        self.held_asset(id, BoardKind::Document, name).await
15472    }
15473    async fn set_document_rendering_with_assets(
15474        &self,
15475        id: &NativeId,
15476        content: &str,
15477        provenance: &Value,
15478        _answers: &BTreeMap<String, Value>,
15479        assets: &onetaskgraph_plugin_api::AssetWrite,
15480    ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
15481        self.replace_rendering(id, BoardKind::Document, content, provenance, Some(assets))
15482            .await
15483    }
15484    async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError> {
15485        Ok(self
15486            .item_by_id(id)
15487            .await?
15488            .filter(|item| item.kind == BoardKind::Work(ItemKind::Project))
15489            .map(|item| item.project()))
15490    }
15491    /// Every narrowed search and origin lookup asked, a page at a time, as aliased fields of one
15492    /// [`graphql::SEARCH_BATCH`] request a round — a search's issue search in an `s<n>` field,
15493    /// an origin's board filter in an `o<n>` field beside its issue search — and every other
15494    /// query by [`Self::query_tasks`] on its own: one narrowed by a project or by comment
15495    /// activity, one carrying no narrowing, one resumed from a cursor that read handed out, and
15496    /// every query of a process that has written this board, whose own writes complete a
15497    /// narrowed answer. A lone search is its own read too, which costs a batch's point at a
15498    /// page of its own size.
15499    ///
15500    /// Each search's first page asks [`SEARCH_BATCH_FIRST_PAGE`] rows and each later page
15501    /// [`SEARCH_PAGE_SIZE`]. GitHub answers an error about one aliased field at that field's
15502    /// path, beside the others' answers, so a refused page fails that query's answer alone; a
15503    /// request it refuses whole is every query of that request's answer.
15504    async fn query_tasks_batch(
15505        &self,
15506        asks: &[(TaskQuery, PageRequest)],
15507    ) -> Vec<Result<Page<Task>, SourceError>> {
15508        self.search_batched(asks).await
15509    }
15510    async fn query_tasks(
15511        &self,
15512        query: &TaskQuery,
15513        page: &PageRequest,
15514    ) -> Result<Page<Task>, SourceError> {
15515        validate_page(page)?;
15516        refuse_unsearchable(query)?;
15517        // A closed issue reads `done`, `cancelled` or — closed for a reason that implies no
15518        // category — `unknown`; every other category reads only off an open issue or a draft. So
15519        // a status filter naming none of those three asks every issue search it sends for open
15520        // issues alone; each candidate's category is still confirmed from its own item below.
15521        let open_only = open_only(query);
15522        if query.origin.is_none()
15523            && !matches!(query.project, ProjectFilter::Is(_))
15524            && let Some(also) = search_qualifiers(query)
15525        {
15526            return self.search_tasks(query, page, &also).await;
15527        }
15528
15529        // A read narrowed to one project asks that project for its own tasks, so nothing
15530        // about it costs what the rest of the board holds. A read carrying a text, metadata
15531        // or origin predicate asks GitHub the narrower question those predicates are, and a
15532        // read narrowed to comment activity alone asks the board's own issue search for the
15533        // issues updated since, which is every issue a comment could have been written or
15534        // edited on since. Every other task read is a question about the whole board and is
15535        // answered by reading it.
15536        let (held, membership) = match (&query.project, query.commented_since) {
15537            (ProjectFilter::Is(project), _) => (
15538                match self.held_task_children(project)? {
15539                    // Taken as `project_children` takes the project's own sub-issue read: with
15540                    // every item this process wrote under it since, and none it moved away.
15541                    Some(held) => self.completed_with_written(
15542                        held.into_iter()
15543                            .filter(|child| child.parent.as_ref() == Some(project))
15544                            .collect(),
15545                        |own| own.parent.as_ref() == Some(project),
15546                    )?,
15547                    None => self.project_children(project).await?,
15548                },
15549                // Answered by where these items came from; see `task_matches`.
15550                &ProjectFilter::Any,
15551            ),
15552            (ProjectFilter::Any | ProjectFilter::Orphans, since) => {
15553                match (self.narrowed(query).await?, since) {
15554                    (Some(narrowed), _) => (narrowed, &query.project),
15555                    (None, Some(since)) => (self.updated_since(since).await?, &query.project),
15556                    // The board's own items list every draft; only the search half, which
15557                    // completes them with issues they lag behind on, is narrowed — a closed
15558                    // issue that half leaves out is at no category the filter keeps.
15559                    // Every category it keeps reads only off an open item, so it reads the
15560                    // board's open items alone, through the board's own filter.
15561                    (None, None) if open_items_only(query) => {
15562                        (self.open_items().await?, &query.project)
15563                    }
15564                    (None, None) if open_only => (
15565                        self.board_completed_by(Some(OPEN_QUALIFIER)).await?.items,
15566                        &query.project,
15567                    ),
15568                    (None, None) => (self.board().await?.items, &query.project),
15569                }
15570            }
15571        };
15572        // Every candidate this read confirms by its comments is read together.
15573        let candidates = self.comment_candidates(held.iter(), query, membership)?;
15574        self.hold_comment_pages(&candidates).await?;
15575        // Filtered before paged: a page of a filtered result is a page of the survivors,
15576        // never the survivors of a page.
15577        let mut tasks = Vec::new();
15578        for item in held
15579            .iter()
15580            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
15581        {
15582            let task = item.task()?;
15583            if task_matches(&task, query, membership)
15584                && self.commented_since(item, query.commented_since).await?
15585            {
15586                tasks.push(task);
15587            }
15588        }
15589        Ok(offset_page(
15590            tasks,
15591            numeric_cursor(page.cursor.as_ref())?,
15592            page.limit.min(MAX_PAGE_SIZE) as usize,
15593        ))
15594    }
15595    /// Read board pages directly, at the board connection's consistency. Unlike
15596    /// `query_tasks`, this does not complete a lagging board with issue search: a complete
15597    /// sweep needs one request per listing page, including the first comments.
15598    async fn query_task_details(
15599        &self,
15600        query: &TaskQuery,
15601        page: &PageRequest,
15602        comments: Option<&PageRequest>,
15603    ) -> Result<Page<TaskDetailRead>, SourceError> {
15604        let Some(comments) = comments else {
15605            let tasks = self.query_tasks(query, page).await?;
15606            return Ok(Page {
15607                items: tasks
15608                    .items
15609                    .into_iter()
15610                    .map(|task| TaskDetailRead {
15611                        task,
15612                        comments: None,
15613                    })
15614                    .collect(),
15615                next: tasks.next,
15616            });
15617        };
15618        validate_page(page)?;
15619        validate_page(comments)?;
15620        refuse_unsearchable(query)?;
15621        if comments.cursor.is_some() || query.commented_since.is_some() {
15622            return Err(SourceError::Refused {
15623                message: "a board listing with comments requires a first comment page and cannot filter by comment activity".into(),
15624            });
15625        }
15626        let after = page.cursor.as_ref().map(|cursor| cursor.0.as_str());
15627        let data = self
15628            .graphql(
15629                graphql::BOARD_WITH_COMMENTS,
15630                json!({
15631                    "owner":self.owner,"number":self.project_number,
15632                    "first":page.limit.min(MAX_PAGE_SIZE),"after":after,
15633                    "commentFirst":comments.limit.min(MAX_PAGE_SIZE),
15634                    "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true,
15635                }),
15636            )
15637            .await?;
15638        let connection = data
15639            .pointer("/owner/projectV2/items")
15640            .filter(|value| !value.is_null())
15641            .ok_or_else(|| SourceError::Refused {
15642                message: "GitHub project was not found or is not visible to the token".into(),
15643            })?;
15644        let mut items = Vec::new();
15645        for node in optional_nodes(Some(connection), "board items")?
15646            .into_iter()
15647            .flatten()
15648        {
15649            let Some(item) = self.resolve(node)? else {
15650                continue;
15651            };
15652            if item.kind != BoardKind::Work(ItemKind::Task) {
15653                continue;
15654            }
15655            let task = item.task()?;
15656            if !task_matches(&task, query, &query.project) {
15657                continue;
15658            }
15659            let read = if item.content_kind == ContentKind::DraftIssue {
15660                Err(self.draft_has_no_comments(&task.id))
15661            } else {
15662                self.expected.learn_comments(&task.id, &node["content"]);
15663                comment_page(&node["content"], &task.id.0, None).map(Some)
15664            };
15665            items.push(TaskDetailRead {
15666                task,
15667                comments: Some(read),
15668            });
15669        }
15670        let next = next_cursor(connection)?;
15671        if let Some(next) = &next {
15672            validate_cursor_progress(after, &next.0)?;
15673        }
15674        Ok(Page { items, next })
15675    }
15676
15677    async fn query_projects(
15678        &self,
15679        query: &ProjectQuery,
15680        page: &PageRequest,
15681    ) -> Result<Page<Project>, SourceError> {
15682        validate_page(page)?;
15683        refuse_unsearchable_text(query.text.as_ref())?;
15684        // The projects a board holds are found by an issue search scoped to that board,
15685        // never by walking the board's own item connection: what tells a project from a
15686        // task is the `parent` each issue carries, which costs nothing to read. A query
15687        // carrying a text asks that search for the text too, so it reads the issues that
15688        // hold it rather than every issue of the board.
15689        let held = match self.text_searched(query.text.as_ref()).await? {
15690            Some(searched) => searched,
15691            None => self.board_issues().await?,
15692        };
15693        let projects = held
15694            .iter()
15695            .filter(|item| item.kind == BoardKind::Work(ItemKind::Project))
15696            .map(Resolved::project)
15697            .filter(|project| project_matches(project, query))
15698            .collect();
15699        Ok(offset_page(
15700            projects,
15701            numeric_cursor(page.cursor.as_ref())?,
15702            page.limit.min(MAX_PAGE_SIZE) as usize,
15703        ))
15704    }
15705    async fn query_projects_by_origin(
15706        &self,
15707        origin: &str,
15708        page: &PageRequest,
15709    ) -> Result<Page<Project>, SourceError> {
15710        validate_page(page)?;
15711        let projects = self
15712            .copied_from(origin, BoardKind::Work(ItemKind::Project))
15713            .await?
15714            .iter()
15715            .map(Resolved::project)
15716            .collect();
15717        Ok(offset_page(
15718            projects,
15719            numeric_cursor(page.cursor.as_ref())?,
15720            page.limit.min(MAX_PAGE_SIZE) as usize,
15721        ))
15722    }
15723    async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
15724        let Some(item) = self
15725            .document_by_id(id)
15726            .await?
15727            .filter(|item| item.kind == BoardKind::Document)
15728        else {
15729            return Ok(None);
15730        };
15731        self.expected.read_document(&item);
15732        Ok(Some(item.document()))
15733    }
15734    async fn query_documents_by_origin(
15735        &self,
15736        origin: &str,
15737        page: &PageRequest,
15738    ) -> Result<Page<Document>, SourceError> {
15739        validate_page(page)?;
15740        let documents = self
15741            .copied_from(origin, BoardKind::Document)
15742            .await?
15743            .iter()
15744            .map(Resolved::document)
15745            .collect();
15746        Ok(offset_page(
15747            documents,
15748            numeric_cursor(page.cursor.as_ref())?,
15749            page.limit.min(MAX_PAGE_SIZE) as usize,
15750        ))
15751    }
15752    async fn query_documents(
15753        &self,
15754        query: &DocumentQuery,
15755        page: &PageRequest,
15756    ) -> Result<Page<Document>, SourceError> {
15757        validate_page(page)?;
15758        // Narrowed to one project, this is the same sub-issue read a task list scoped to
15759        // that project makes — a document filed under a project is a sub-issue of it too,
15760        // and which of them come back is the kind this caller asked for. Unscoped, a query
15761        // carrying a text asks the board-scoped issue search for it, as a task query does,
15762        // and only one carrying none reads the board.
15763        let (held, membership) = match &query.project {
15764            ProjectFilter::Is(project) => (
15765                self.project_children(project).await?,
15766                // Answered by where these items came from; see `task_matches`.
15767                &ProjectFilter::Any,
15768            ),
15769            ProjectFilter::Any | ProjectFilter::Orphans => {
15770                refuse_unsearchable_text(query.text.as_ref())?;
15771                match self.text_searched(query.text.as_ref()).await? {
15772                    Some(searched) => (searched, &query.project),
15773                    None => (self.board().await?.items, &query.project),
15774                }
15775            }
15776        };
15777        // Filtered before paged, exactly as a task read is: a page of a filtered result is
15778        // a page of the survivors, never the survivors of a page.
15779        let documents = held
15780            .iter()
15781            .filter(|item| item.kind == BoardKind::Document)
15782            .map(Resolved::document)
15783            .filter(|document| document_matches(document, query, membership))
15784            .collect();
15785        Ok(offset_page(
15786            documents,
15787            numeric_cursor(page.cursor.as_ref())?,
15788            page.limit.min(MAX_PAGE_SIZE) as usize,
15789        ))
15790    }
15791    async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError> {
15792        validate_page(page)?;
15793        let offset = numeric_cursor(page.cursor.as_ref())?;
15794        let mut labels = self
15795            .board()
15796            .await?
15797            .items
15798            .into_iter()
15799            .flat_map(|item| item.labels)
15800            .fold(Vec::new(), |mut all, label| {
15801                if !all.iter().any(|x: &Label| x.id == label.id) {
15802                    all.push(label);
15803                }
15804                all
15805            });
15806        labels.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.0.cmp(&b.id.0)));
15807        Ok(offset_page(
15808            labels,
15809            offset,
15810            page.limit.min(MAX_PAGE_SIZE) as usize,
15811        ))
15812    }
15813    async fn task_dependencies(
15814        &self,
15815        id: &NativeId,
15816        direction: Direction,
15817        page: &PageRequest,
15818    ) -> Result<Page<DependencyEdge>, SourceError> {
15819        self.dependencies(id, ItemKind::Task, direction, page).await
15820    }
15821    async fn project_dependencies(
15822        &self,
15823        id: &NativeId,
15824        direction: Direction,
15825        page: &PageRequest,
15826    ) -> Result<Page<DependencyEdge>, SourceError> {
15827        self.dependencies(id, ItemKind::Project, direction, page)
15828            .await
15829    }
15830
15831    fn writes(&self) -> WriteSupport {
15832        WriteSupport::Supported
15833    }
15834
15835    /// Create or update one task.
15836    ///
15837    /// Its `delivers` and `delivered_by` are checked before anything is read or written —
15838    /// neither may name the task itself or name one task twice — and land in the body's
15839    /// metadata slot under their reserved keys, in place of any caller metadata of those
15840    /// names.
15841    async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
15842        if write.item.project.is_some() {
15843            self.projectless()?;
15844        }
15845        self.write_task_assets(write, None)
15846            .await
15847            .map(|written| written.id)
15848    }
15849
15850    async fn read_ahead_origins_for_copy(&self, origins: &[String]) -> Result<(), SourceError> {
15851        self.origins_ahead(origins).await
15852    }
15853
15854    async fn member_classifications(
15855        &self,
15856        project: &NativeId,
15857    ) -> Result<Option<Vec<(Classification, Vec<Repository>)>>, SourceError> {
15858        Ok(self
15859            .member_classes
15860            .lock()
15861            .map_err(|_| SourceError::Unavailable {
15862                message: "a project's members held for its classification were left \
15863                          inconsistent; run the command again"
15864                    .into(),
15865            })?
15866            .remove(project))
15867    }
15868
15869    /// The issue's own web address, as the `createIssue` that made it in this command answered
15870    /// it: a task, a project and a document are each an issue here.
15871    fn written_location(
15872        &self,
15873        _record: onetaskgraph_plugin_api::MetadataRecord,
15874        id: &NativeId,
15875    ) -> Option<Location> {
15876        self.written
15877            .lock()
15878            .unwrap_or_else(std::sync::PoisonError::into_inner)
15879            .get(id)
15880            .cloned()
15881            .map(Location::Url)
15882    }
15883
15884    /// [`MUTATION_BATCH`], while writes are held back: [`graphql::CREATE_ISSUES`] creates that many
15885    /// in one request, and a copy's tasks are created together only then, since their fields
15886    /// and edges are what is held back.
15887    fn create_batch_limit(&self) -> usize {
15888        if self.deferring().unwrap_or(false) {
15889            MUTATION_BATCH
15890        } else {
15891            1
15892        }
15893    }
15894
15895    // 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.
15896    async fn write_tasks(&self, writes: &[ItemWrite<Task>]) -> Result<Vec<NativeId>, SourceError> {
15897        if writes.iter().any(|write| write.item.project.is_some()) {
15898            self.projectless()?;
15899        }
15900        if let Some(write) = writes.iter().find(|write| write.target.is_some()) {
15901            return Err(SourceError::Refused {
15902                message: format!(
15903                    "write_tasks creates tasks, and the write of {} names the existing task {}; \
15904                     next: update it with write_task",
15905                    write.item.id,
15906                    write.target.as_ref().map_or("", |target| target.0.as_str())
15907                ),
15908            });
15909        }
15910        if !self.deferring()? {
15911            let mut created = Vec::with_capacity(writes.len());
15912            for write in writes {
15913                match self.write_task(write).await {
15914                    Ok(id) => created.push(id),
15915                    Err(error) => {
15916                        let mut left: Vec<&str> = Vec::new();
15917                        for id in &created {
15918                            if self.delete_issue(id).await.is_err() {
15919                                left.push(id.0.as_str());
15920                            }
15921                        }
15922                        return Err(left_behind(error, &left));
15923                    }
15924                }
15925            }
15926            return Ok(created);
15927        }
15928        self.create_together(writes).await
15929    }
15930
15931    fn begin_deferred_writes(&self) {
15932        if let Ok(mut deferred) = self.deferred.lock() {
15933            deferred.get_or_insert_with(Deferred::default);
15934        }
15935    }
15936
15937    async fn finish_writes(&self) -> Result<(), SourceError> {
15938        self.send_held_updates().await?;
15939        self.send_held_back().await
15940    }
15941
15942    async fn write_task_with_assets(
15943        &self,
15944        write: &ItemWrite<Task>,
15945        _answers: Option<&BTreeMap<String, Value>>,
15946        assets: &onetaskgraph_plugin_api::AssetWrite,
15947    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
15948        self.write_task_assets(write, Some(assets)).await
15949    }
15950
15951    async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
15952        self.projectless()?;
15953        self.write_item(
15954            &Incoming {
15955                written: Written::Work(ItemKind::Project, &write.item.status),
15956                title: &write.item.title,
15957                content: write.item.content.as_deref(),
15958                assets: None,
15959                labels: &write.item.labels,
15960                metadata: &write.item.metadata,
15961                repositories: &write.item.repositories,
15962                classification: write.item.classification,
15963                parent: None,
15964                delivers: &[],
15965                delivered_by: &[],
15966                priority: None,
15967                assignees: None,
15968            },
15969            write.target.as_ref(),
15970            &write.depends_on,
15971        )
15972        .await
15973        .map(|written| written.id)
15974    }
15975
15976    fn task_body_size(
15977        &self,
15978        write: &ItemWrite<Task>,
15979        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
15980    ) -> Option<onetaskgraph_plugin_api::BodySize> {
15981        Some(self.body_size(&self.task_incoming(write, assets).ok()?))
15982    }
15983
15984    fn project_body_size(
15985        &self,
15986        write: &ItemWrite<Project>,
15987    ) -> Option<onetaskgraph_plugin_api::BodySize> {
15988        Some(self.body_size(&Incoming {
15989            written: Written::Work(ItemKind::Project, &write.item.status),
15990            title: &write.item.title,
15991            content: write.item.content.as_deref(),
15992            assets: None,
15993            labels: &write.item.labels,
15994            metadata: &write.item.metadata,
15995            repositories: &write.item.repositories,
15996            classification: write.item.classification,
15997            parent: None,
15998            delivers: &[],
15999            delivered_by: &[],
16000            priority: None,
16001            assignees: None,
16002        }))
16003    }
16004
16005    fn document_body_size(
16006        &self,
16007        write: &ItemWrite<Document>,
16008        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
16009    ) -> Option<onetaskgraph_plugin_api::BodySize> {
16010        Some(self.body_size(&Incoming {
16011            written: Written::Document,
16012            title: &write.item.title,
16013            content: write.item.content.as_deref(),
16014            assets,
16015            labels: &write.item.labels,
16016            metadata: &write.item.metadata,
16017            repositories: &write.item.repositories,
16018            classification: write.item.classification,
16019            parent: write.item.project.as_ref(),
16020            delivers: &[],
16021            delivered_by: &[],
16022            priority: None,
16023            assignees: None,
16024        }))
16025    }
16026
16027    /// Create or update one document, which is one issue titled the way this board spells
16028    /// a document.
16029    ///
16030    /// Everything else is exactly a task write: caller metadata goes to the same canonical
16031    /// JSON slot at the end of the body and comes back with its JSON types intact, a key
16032    /// or a field this board cannot carry is refused by name rather than dropped, a target
16033    /// naming an issue this board does not hold is refused rather than created, and an
16034    /// issue this call created is taken back when the rest of the write fails.
16035    async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
16036        self.write_document_assets(write, None)
16037            .await
16038            .map(|written| written.id)
16039    }
16040
16041    async fn write_document_with_assets(
16042        &self,
16043        write: &ItemWrite<Document>,
16044        _answers: Option<&BTreeMap<String, Value>>,
16045        assets: &onetaskgraph_plugin_api::AssetWrite,
16046    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
16047        self.write_document_assets(write, Some(assets)).await
16048    }
16049
16050    /// Refused exactly as the write refuses it, from what the write reads: the mapping first,
16051    /// which reads nothing; then the board's `Status` option. Over an existing item that is
16052    /// read off the item, as the write reads it, and the item is held among this command's
16053    /// resolved records so the write that follows reuses that read rather than repeating it;
16054    /// an item that does not carry the field takes the board's fields, which are held once
16055    /// read. A create is checked against the board's fields only when this command already
16056    /// holds them, because a create reads them together with its repository, in one request,
16057    /// and refuses a missing option before it writes anything.
16058    async fn check_status_write(
16059        &self,
16060        kind: ItemKind,
16061        category: StatusCategory,
16062        target: Option<&NativeId>,
16063    ) -> Result<(), SourceError> {
16064        let status = self.resolved_target(kind, category)?;
16065        if status.option().is_none() {
16066            return Ok(());
16067        }
16068        let fields = match target {
16069            Some(target) => {
16070                // A target this board does not hold is the write's own refusal to make.
16071                let Some(item) = self.bound_item(target).await? else {
16072                    return Ok(());
16073                };
16074                self.resolved_cache()?.insert(target.clone(), item.clone());
16075                // Only the `Status` field decides whether the write can land.
16076                self.fields_for(Some(&item), false, true, false)
16077                    .await?
16078                    .fields
16079            }
16080            None => {
16081                let held = self
16082                    .board_cache()?
16083                    .as_ref()
16084                    .map(|board| board.fields.clone());
16085                match held.or_else(|| {
16086                    self.fields_cache()
16087                        .ok()
16088                        .and_then(|cache| cache.as_ref().map(|board| board.fields.clone()))
16089                }) {
16090                    Some(fields) => fields,
16091                    None => return Ok(()),
16092                }
16093            }
16094        };
16095        self.column_for(&fields, kind, category, &status)
16096            .map(|_| ())
16097    }
16098
16099    /// What a write of `status` reads back as: the `Status` option its category maps to for
16100    /// `kind`, and for a closing category the closure that option and its fixed reason read
16101    /// as — exactly what [`BoardStatuses::status`] reports of the item once written. A category
16102    /// this instance has no option for is answered as given, since writing it is refused.
16103    fn status_as_written(&self, kind: ItemKind, status: &Status) -> Status {
16104        match self.statuses.target(kind, status.category) {
16105            StatusTarget::Column(name) => {
16106                self.statuses.status(kind, Some(name.as_str()), false, None)
16107            }
16108            StatusTarget::Terminal(name, reason) => {
16109                self.statuses
16110                    .status(kind, Some(name.as_str()), true, Some(reason.reason()))
16111            }
16112            StatusTarget::Disabled(_) => status.clone(),
16113        }
16114    }
16115
16116    /// Set one task's status alone.
16117    ///
16118    /// An open target reopens a closed issue with an `updateIssue` carrying only its
16119    /// `stateInput`, then selects the board option with `updateProjectV2ItemFieldValue`; a
16120    /// terminal target selects its mapped option, then closes with its fixed reason. No
16121    /// request carries a title, a body or a label. The status
16122    /// answered is what [`BoardStatuses::status`] reads off the state just written, which is
16123    /// what a re-read reports.
16124    async fn set_task_status(
16125        &self,
16126        id: &NativeId,
16127        category: StatusCategory,
16128    ) -> Result<Option<Status>, SourceError> {
16129        self.set_status(id, ItemKind::Task, category).await
16130    }
16131
16132    /// Set one task's status and answer the task with it, reading the item once: the read the
16133    /// task is answered from is handed to the status write, which would otherwise read the
16134    /// same issue again — two requests on a fresh process, the read and the field write,
16135    /// where the default's `get_task` before `set_task_status` sent three.
16136    async fn set_task_status_reading(
16137        &self,
16138        id: &NativeId,
16139        category: StatusCategory,
16140    ) -> Result<Option<Task>, SourceError> {
16141        // Refused before anything is read, in the words the write itself refuses it.
16142        self.resolved_target(ItemKind::Task, category)?;
16143        let Some(item) = self
16144            .bound_item(id)
16145            .await?
16146            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
16147        else {
16148            return Ok(None);
16149        };
16150        let mut task = item.task()?;
16151        self.held_cache
16152            .lock()
16153            .map_err(|_| SourceError::Unavailable {
16154                message: "items read by issue reference were left inconsistent; run the \
16155                          command again"
16156                    .into(),
16157            })?
16158            .insert(id.clone(), item);
16159        let Some(status) = self.set_status(id, ItemKind::Task, category).await? else {
16160            return Ok(None);
16161        };
16162        task.status = status;
16163        Ok(Some(task))
16164    }
16165
16166    /// Set one project's status alone, by exactly the paired write a task's status takes, for
16167    /// the project kind: a terminal category selects the project kind's mapped option and then
16168    /// closes the issue with the category's fixed reason — an issue already closed with a
16169    /// reason that reads that category is left as it is — and an open category reopens a closed
16170    /// issue and then selects its option. A board draft is refused a terminal category as a
16171    /// task's is.
16172    async fn set_project_status(
16173        &self,
16174        id: &NativeId,
16175        category: StatusCategory,
16176    ) -> Result<Option<Status>, SourceError> {
16177        self.projectless()?;
16178        self.set_status(id, ItemKind::Project, category).await
16179    }
16180
16181    /// Every task and project whose card contradicts its issue's closure, read through the
16182    /// board's own `is:closed` filter; see [`TaskSource::status_contradictions`].
16183    async fn status_contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
16184        self.contradictions().await
16185    }
16186
16187    /// What this board holds for each issue reference, one request per fifty of them; see
16188    /// [`TaskSource::issue_holdings`].
16189    async fn issue_holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
16190        self.holdings(issues).await
16191    }
16192
16193    /// Set one task's priority alone: one `updateProjectV2ItemFieldValue` selecting the
16194    /// mapped option of the board's `Priority` field, or one `clearProjectV2ItemFieldValue`
16195    /// for `none`. Refused by an instance with no `priority_mapping`.
16196    async fn set_task_priority(
16197        &self,
16198        id: &NativeId,
16199        priority: Priority,
16200    ) -> Result<Option<Priority>, SourceError> {
16201        self.set_priority(id, priority).await
16202    }
16203
16204    /// Replace one task's content with a single body update that keeps the metadata slot
16205    /// byte for byte.
16206    async fn set_task_content(
16207        &self,
16208        id: &NativeId,
16209        content: &str,
16210    ) -> Result<Option<()>, SourceError> {
16211        self.replace_content(id, content).await
16212    }
16213
16214    /// Replace one task issue's content and its provenance slot entry with a single body
16215    /// update. The answers are not kept: see `replace_rendering`.
16216    async fn set_task_rendering(
16217        &self,
16218        id: &NativeId,
16219        content: &str,
16220        provenance: &Value,
16221        _answers: &BTreeMap<String, Value>,
16222    ) -> Result<Option<()>, SourceError> {
16223        self.replace_rendering(
16224            id,
16225            BoardKind::Work(ItemKind::Task),
16226            content,
16227            provenance,
16228            None,
16229        )
16230        .await
16231        .map(|written| written.map(|_| ()))
16232    }
16233
16234    /// Replace one design-document issue's content and its provenance slot entry, on exactly
16235    /// the terms of [`set_task_rendering`](TaskSource::set_task_rendering).
16236    async fn set_document_rendering(
16237        &self,
16238        id: &NativeId,
16239        content: &str,
16240        provenance: &Value,
16241        _answers: &BTreeMap<String, Value>,
16242    ) -> Result<Option<()>, SourceError> {
16243        self.replace_rendering(id, BoardKind::Document, content, provenance, None)
16244            .await
16245            .map(|written| written.map(|_| ()))
16246    }
16247
16248    /// Replace one project issue's content and its provenance slot entry, on exactly the
16249    /// terms of [`set_task_rendering`](TaskSource::set_task_rendering).
16250    async fn set_project_rendering(
16251        &self,
16252        id: &NativeId,
16253        content: &str,
16254        provenance: &Value,
16255        _answers: &BTreeMap<String, Value>,
16256    ) -> Result<Option<()>, SourceError> {
16257        self.projectless()?;
16258        self.replace_rendering(
16259            id,
16260            BoardKind::Work(ItemKind::Project),
16261            content,
16262            provenance,
16263            None,
16264        )
16265        .await
16266        .map(|written| written.map(|_| ()))
16267    }
16268
16269    /// Apply a targeted update with one read of the item and a write only for what differs:
16270    /// the `Status` and `Priority` field writes in one request, the `blockedBy` difference,
16271    /// and last one `updateIssue` for title, body and state. See `targeted_update`.
16272    async fn update_task(
16273        &self,
16274        id: &NativeId,
16275        update: &TaskUpdate,
16276    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
16277        self.targeted_update(id, update).await
16278    }
16279
16280    /// Each issue's sub-issue parent and children and its links, read in batches.
16281    async fn read_relations(
16282        &self,
16283        ids: &[NativeId],
16284    ) -> Vec<Result<Option<onetaskgraph_plugin_api::Relations>, SourceError>> {
16285        self.relations_of(ids).await
16286    }
16287
16288    async fn set_parents(
16289        &self,
16290        writes: &[onetaskgraph_plugin_api::ParentWrite],
16291    ) -> Vec<Result<onetaskgraph_plugin_api::ParentAnswer, SourceError>> {
16292        self.parents_set(writes).await
16293    }
16294
16295    fn link_types(&self) -> onetaskgraph_plugin_api::LinkTypes {
16296        self.link_types.clone()
16297    }
16298
16299    async fn add_native_links(
16300        &self,
16301        links: &[onetaskgraph_plugin_api::NativeLink],
16302    ) -> Vec<Result<(), SourceError>> {
16303        self.native_links(links, relations::NativeWrite::Add).await
16304    }
16305
16306    async fn remove_native_links(
16307        &self,
16308        links: &[onetaskgraph_plugin_api::NativeLink],
16309    ) -> Vec<Result<(), SourceError>> {
16310        self.native_links(links, relations::NativeWrite::Remove)
16311            .await
16312    }
16313
16314    /// Every task read together — [`DETAIL_BATCH`] to a [`graphql::ISSUE_DETAILS`] request —
16315    /// and each update's hold and guard decided on that read; then each update the read lets
16316    /// through composed exactly as [`Self::update_task`] composes one, its board field writes
16317    /// and its issue update held back and sent in [`graphql::WRITE_TASKS`] requests: every
16318    /// field write first, then the issue update of every task whose field writes all landed.
16319    ///
16320    /// **Where GitHub would refuse the batch as a whole, each item is read on its own:** a
16321    /// batched node read naming an id that resolves to nothing is refused whole, so each id of
16322    /// that batch is read by itself, the missing one answered missing and the rest as
16323    /// themselves. A batch of one, an update of a board draft, one naming dependencies and one
16324    /// of an item whose body this process has not read are each made on their own, as
16325    /// [`Self::update_task`] makes them, because each sends writes of its own in an order the
16326    /// batch does not hold. A field write GitHub refuses fails that task's update alone and
16327    /// sends nothing of its body.
16328    async fn update_tasks(
16329        &self,
16330        updates: &[onetaskgraph_plugin_api::BatchUpdate],
16331    ) -> Vec<Result<onetaskgraph_plugin_api::BatchAnswer<TaskUpdateOutcome>, SourceError>> {
16332        self.updates_batched(updates).await
16333    }
16334
16335    /// Replace one task's `delivered_by` with a single body update that changes the
16336    /// metadata slot and nothing outside it.
16337    async fn set_delivered_by(
16338        &self,
16339        id: &NativeId,
16340        delivered_by: &[TaskRef],
16341    ) -> Result<Option<()>, SourceError> {
16342        self.replace_delivered_by(id, delivered_by).await
16343    }
16344
16345    /// Set one key of one task issue's metadata with a single body update that changes the
16346    /// metadata slot and nothing outside it — no title, label, state or board field request —
16347    /// and sends nothing when the task already holds that value under the key.
16348    async fn set_task_metadata(
16349        &self,
16350        id: &NativeId,
16351        key: &MetadataKey,
16352        value: &Value,
16353    ) -> Result<Option<Task>, SourceError> {
16354        Ok(self
16355            .set_slot_key(id, BoardKind::Work(ItemKind::Task), key, value)
16356            .await?
16357            .map(|item| item.task())
16358            .transpose()?)
16359    }
16360
16361    /// Set one key of one project issue's metadata, on exactly the terms of
16362    /// [`set_task_metadata`](TaskSource::set_task_metadata).
16363    async fn set_project_metadata(
16364        &self,
16365        id: &NativeId,
16366        key: &MetadataKey,
16367        value: &Value,
16368    ) -> Result<Option<Project>, SourceError> {
16369        self.projectless()?;
16370        Ok(self
16371            .set_slot_key(id, BoardKind::Work(ItemKind::Project), key, value)
16372            .await?
16373            .map(|item| item.project()))
16374    }
16375
16376    /// Set one key of one design-document issue's metadata, on exactly the terms of
16377    /// [`set_task_metadata`](TaskSource::set_task_metadata).
16378    async fn set_document_metadata(
16379        &self,
16380        id: &NativeId,
16381        key: &MetadataKey,
16382        value: &Value,
16383    ) -> Result<Option<Document>, SourceError> {
16384        Ok(self
16385            .set_slot_key(id, BoardKind::Document, key, value)
16386            .await?
16387            .map(|item| item.document()))
16388    }
16389
16390    /// Take one key out of one issue's metadata slot with a single body update that changes the
16391    /// slot and nothing outside it, sending nothing when the slot does not hold the key.
16392    async fn remove_record_metadata(
16393        &self,
16394        record: onetaskgraph_plugin_api::MetadataRecord,
16395        id: &NativeId,
16396        key: &MetadataKey,
16397    ) -> Result<Option<Option<String>>, SourceError> {
16398        let kind = match record {
16399            onetaskgraph_plugin_api::MetadataRecord::Task => BoardKind::Work(ItemKind::Task),
16400            onetaskgraph_plugin_api::MetadataRecord::Project => BoardKind::Work(ItemKind::Project),
16401            onetaskgraph_plugin_api::MetadataRecord::Document => BoardKind::Document,
16402        };
16403        let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
16404            return Ok(None);
16405        };
16406        if item.slot.contains_key(key.as_str()) {
16407            let mut slot = item.slot.clone();
16408            slot.remove(key.as_str());
16409            self.write_slot(&mut item, &slot).await?;
16410            self.remember_written(item.clone(), false)?;
16411        }
16412        Ok(Some(match record {
16413            onetaskgraph_plugin_api::MetadataRecord::Task => item.task()?.version,
16414            onetaskgraph_plugin_api::MetadataRecord::Project => item.project().version,
16415            onetaskgraph_plugin_api::MetadataRecord::Document => item.document().version,
16416        }))
16417    }
16418
16419    async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
16420        self.delete_item(id).await
16421    }
16422
16423    async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
16424        self.projectless()?;
16425        self.delete_item(id).await
16426    }
16427
16428    async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
16429        self.delete_item(id).await
16430    }
16431
16432    /// One page of the task issue's own comments, walked by GitHub's own cursor.
16433    ///
16434    /// Nothing here filters, so nothing has to be read ahead of the page: the caller's limit is
16435    /// the page GitHub is asked for and GitHub's `endCursor` is the cursor handed back.
16436    ///
16437    /// One request, [`graphql::ISSUE_DETAIL`]: the read that says the id names a task of this
16438    /// board is the read of its comments. A draft this process already resolved is refused
16439    /// without one.
16440    async fn task_comments(
16441        &self,
16442        task: &NativeId,
16443        page: &PageRequest,
16444    ) -> Result<Option<Page<Comment>>, SourceError> {
16445        validate_page(page)?;
16446        let cached = self.resolved_cache()?.get(task).cloned();
16447        if let Some(item) = cached {
16448            if item.kind != BoardKind::Work(ItemKind::Task) {
16449                return Ok(None);
16450            }
16451            if item.content_kind == ContentKind::DraftIssue {
16452                return Err(self.draft_has_no_comments(task));
16453            }
16454        }
16455        // The first page a comment-activity read just read of this task, at the size asked, is
16456        // that read's answer: taken, so it answers once.
16457        if page.cursor.is_none()
16458            && page.limit >= MAX_PAGE_SIZE
16459            && let Some(held) = self.held_comments()?.remove(task)
16460        {
16461            return Ok(Some(held));
16462        }
16463        match self.issue_detail(task, page).await? {
16464            Some(TaskDetailRead {
16465                comments: Some(comments),
16466                ..
16467            }) => comments,
16468            _ => Ok(None),
16469        }
16470    }
16471
16472    /// Every id's task, with the first page of its comments when `comments` names it:
16473    /// [`DETAIL_BATCH`] items per [`graphql::ISSUE_DETAILS`] request, and one item with its
16474    /// comments in one [`graphql::ISSUE_DETAIL`] request.
16475    async fn get_task_details(
16476        &self,
16477        ids: &[NativeId],
16478        comments: Option<&PageRequest>,
16479    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
16480        if let Some(page) = comments
16481            && let Err(error) = validate_page(page)
16482        {
16483            return ids.iter().map(|_| Err(error.clone())).collect();
16484        }
16485        match (ids, comments) {
16486            ([id], Some(page)) => vec![self.issue_detail(id, page).await],
16487            ([id], None) => vec![self.task_read(id).await],
16488            _ => self.issue_details(ids, comments).await,
16489        }
16490    }
16491
16492    /// Every id's task with the first page of its comments and its `blockedBy`, as a copy reads
16493    /// the tasks it carries: [`COPY_DETAIL_BATCH`] items per [`graphql::ISSUE_COPY_DETAILS`]
16494    /// request, so the dependency read a copy makes of each next is answered from this one.
16495    async fn get_task_details_for_copy(
16496        &self,
16497        ids: &[NativeId],
16498        comments: &PageRequest,
16499    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
16500        // A page past the first is a page of one task's comments, which the detail read of it
16501        // alone answers.
16502        if comments.cursor.is_some() {
16503            return self.get_task_details(ids, Some(comments)).await;
16504        }
16505        if let Err(error) = validate_page(comments) {
16506            return ids.iter().map(|_| Err(error.clone())).collect();
16507        }
16508        let mut read = Vec::with_capacity(ids.len());
16509        for batch in ids.chunks(COPY_DETAIL_BATCH) {
16510            match self
16511                .graphql(
16512                    graphql::ISSUE_COPY_DETAILS,
16513                    copy_detail_batch(batch, comments, false),
16514                )
16515                .await
16516            {
16517                Ok(data) => {
16518                    for (slot, id) in batch.iter().enumerate() {
16519                        let read_one = match data.get(format!("i{slot}")) {
16520                            Some(node) => self.detail_of(id, node, true, None).await,
16521                            None => Err(SourceError::Malformed {
16522                                message: format!(
16523                                    "GitHub answered a batch read with no item for {}",
16524                                    id.0
16525                                ),
16526                            }),
16527                        };
16528                        read.push(read_one);
16529                    }
16530                }
16531                Err(error) if unresolvable_node(&error) => {
16532                    for id in batch {
16533                        read.push(self.issue_detail(id, comments).await);
16534                    }
16535                }
16536                Err(error) => read.extend(batch.iter().map(|_| Err(error.clone()))),
16537            }
16538        }
16539        read
16540    }
16541
16542    /// Every id's item, whatever kind it is, read [`COPY_DETAIL_BATCH`] at a time with
16543    /// [`graphql::ISSUE_COPY_DETAILS`] — the document a copy reads the tasks it carries with —
16544    /// and held for the next read of each by id; see `read_ahead`.
16545    ///
16546    /// What this run wrote is never read: its own record answers, as it does for a read by id.
16547    /// Nor is an item a listing of its project carried whole earlier in this command — see
16548    /// `carried` — which is held in place of reading it.
16549    /// A batch GitHub refuses because one of its ids resolves to no node at all holds nothing,
16550    /// so each of its ids is read on its own and answered as that read answers; a draft, and an
16551    /// answer naming another issue than the one asked for, are left to their own reads too.
16552    async fn read_ahead_for_copy(&self, ids: &[NativeId]) -> Result<(), SourceError> {
16553        // The origins asked just before go out now, beside the members of the one project this
16554        // names when it names one; a project those origins answered whole is held for its next
16555        // read by id rather than read again here.
16556        let hinted = match ids {
16557            [one] => Some(one),
16558            _ => None,
16559        };
16560        self.send_pending_origins(hinted).await?;
16561        if let Some(project) = hinted {
16562            let answered = self.resolved_cache()?.get(project).cloned();
16563            if let Some(answered) = answered
16564                && answered.kind == BoardKind::Work(ItemKind::Project)
16565            {
16566                self.read_ahead()?.insert(project.clone(), Some(answered));
16567                return Ok(());
16568            }
16569        }
16570        let mut unread: Vec<NativeId> = Vec::new();
16571        // Read whole by a listing of its project in this command, which a mutation naming it
16572        // would have dropped: held as a batch would have held it, once every batch is answered.
16573        let mut listed: Vec<NativeId> = Vec::new();
16574        {
16575            let created = self.created()?;
16576            let held = self.read_ahead()?;
16577            let carried = self.carried()?;
16578            for id in ids {
16579                if unread.contains(id)
16580                    || listed.contains(id)
16581                    || held.contains_key(id)
16582                    || created.iter().any(|own| own.id == *id)
16583                {
16584                    continue;
16585                }
16586                // An issue a listing carried without the whole of what blocks it is read in a
16587                // batch too, which carries that, rather than having its dependency read sent
16588                // on its own once the copy reconciles its edges.
16589                let whole = carried.get(id).is_some_and(|item| {
16590                    item.content_kind != ContentKind::Issue || item.blocked_by.is_some()
16591                });
16592                if whole {
16593                    listed.push(id.clone());
16594                } else {
16595                    unread.push(id.clone());
16596                }
16597            }
16598        }
16599        // Nothing of an item's comments is wanted here: the smallest page keeps the read to
16600        // what the item itself costs.
16601        let comments = PageRequest {
16602            cursor: None,
16603            limit: 1,
16604        };
16605        // Held only once every batch has been answered, so a read-ahead that fails part way
16606        // holds nothing — what a listing carried included, which stays carried — and every
16607        // item is read on its own, as the method promises.
16608        let mut read: Vec<(NativeId, Option<Resolved>)> = Vec::new();
16609        // The issues the first id names as sub-issues, as `ISSUE_COPY_DETAILS`'s `children`
16610        // answered them: what a project copy's orphan check asks, when that first id is its
16611        // project.
16612        let mut children: Option<(NativeId, Vec<(String, String)>)> = None;
16613        for (index, batch) in unread.chunks(COPY_DETAIL_BATCH).enumerate() {
16614            let data = match self
16615                .graphql(
16616                    graphql::ISSUE_COPY_DETAILS,
16617                    copy_detail_batch(batch, &comments, index == 0),
16618                )
16619                .await
16620            {
16621                Ok(data) => data,
16622                Err(error) if unresolvable_node(&error) => continue,
16623                Err(error) => return Err(error),
16624            };
16625            for (slot, id) in batch.iter().enumerate() {
16626                let Some(node) = data.get(format!("i{slot}")) else {
16627                    continue;
16628                };
16629                let held = if node.is_null() {
16630                    None
16631                } else {
16632                    match optional_str(node, "__typename")? {
16633                        Some("DraftIssue") => continue,
16634                        Some("Issue") if required_str(node, "id")? != id.0 => continue,
16635                        _ => {}
16636                    }
16637                    // Remembered below with the rest, so a later batch refused leaves no
16638                    // dependency read answered from this one either.
16639                    self.resolve_issue_as(node, false).await?
16640                };
16641                read.push((id.clone(), held));
16642            }
16643            if index == 0
16644                && let Some(node) = data.get("children").filter(|node| !node.is_null())
16645                && node.get("id").and_then(Value::as_str) == batch.first().map(|id| id.0.as_str())
16646                && node.pointer("/subIssues/pageInfo/hasNextPage") == Some(&Value::Bool(false))
16647            {
16648                // A list GitHub did not answer is not an empty one: it would answer the project's
16649                // task listing with nothing, and the orphan check with no orphans.
16650                let listed = node
16651                    .pointer("/subIssues/nodes")
16652                    .and_then(Value::as_array)
16653                    .ok_or_else(|| SourceError::Malformed {
16654                        message: format!(
16655                            "GitHub answered the sub-issues of project {} with no list of them",
16656                            batch[0].0
16657                        ),
16658                    })?
16659                    .iter()
16660                    .map(|child| {
16661                        Ok((
16662                            required_str(child, "id")?.to_owned(),
16663                            required_str(child, "title")?.to_owned(),
16664                        ))
16665                    })
16666                    .collect::<Result<Vec<_>, SourceError>>()?;
16667                children = Some((batch[0].clone(), listed));
16668            }
16669        }
16670        // The project's tasks are known from this read alone when every child it named is held
16671        // from it, but for a document, which its title says is one and which a task listing
16672        // never answers: then a listing of the project's tasks is answered from them.
16673        if let Some((project, listed)) = children
16674            && read.iter().any(|(id, held)| {
16675                *id == project
16676                    && held
16677                        .as_ref()
16678                        .is_some_and(|held| held.kind == BoardKind::Work(ItemKind::Project))
16679            })
16680        {
16681            let mut tasks = Vec::new();
16682            let mut whole = true;
16683            for (child, title) in &listed {
16684                match read.iter().find(|(id, _)| id.0 == *child) {
16685                    Some((_, Some(held))) if held.parent.as_ref() == Some(&project) => {
16686                        if held.kind == BoardKind::Work(ItemKind::Task) {
16687                            tasks.push(held.clone());
16688                        }
16689                    }
16690                    _ if title.starts_with(DESIGN_TITLE_PREFIX) => {}
16691                    _ => whole = false,
16692                }
16693            }
16694            if whole {
16695                self.task_children()?.insert(project, tasks);
16696            }
16697        }
16698        let mut resolved = self.resolved_cache()?;
16699        let mut ahead = self.read_ahead()?;
16700        let mut carried = self.carried()?;
16701        for item in read.iter().filter_map(|(_, held)| held.as_ref()) {
16702            resolved.insert(item.id.clone(), item.clone());
16703        }
16704        // Taken only if still carried: a mutation naming it while the batches ran dropped it,
16705        // and its next read is then its own.
16706        for id in &listed {
16707            let Some(item) = carried.remove(id) else {
16708                continue;
16709            };
16710            // The whole of what it is blocked by came with it, so the dependency read a copy
16711            // makes next is answered from this one, as a copy's detail read is.
16712            if item.blocked_by.is_some() {
16713                resolved.insert(item.id.clone(), item.clone());
16714            }
16715            read.push((id.clone(), Some(item)));
16716        }
16717        for (id, held) in read {
16718            ahead.insert(id, held);
16719        }
16720        Ok(())
16721    }
16722
16723    /// Add one comment to the task's issue, as the account the token belongs to.
16724    ///
16725    /// The author is refused before anything is sent — not even the task is read — because
16726    /// no answer GitHub could give would make posting under another name than the one asked
16727    /// for the right outcome.
16728    async fn add_comment(
16729        &self,
16730        task: &NativeId,
16731        comment: &NewComment,
16732    ) -> Result<Option<Comment>, SourceError> {
16733        if let Some(author) = &comment.author {
16734            return Err(SourceError::Refused {
16735                message: format!(
16736                    "source {} cannot post a comment as {author:?}: GitHub records the account \
16737                     the token signs in as the author of every comment; next: leave --author \
16738                     out, and the comment is posted as that account",
16739                    self.name
16740                ),
16741            });
16742        }
16743        let Some(issue) = self.commented_issue(task).await? else {
16744            return Ok(None);
16745        };
16746        let data = self
16747            .graphql(
16748                graphql::ADD_COMMENT,
16749                json!({"input":{"subjectId":issue.0,"body":comment.body.as_str()}}),
16750            )
16751            .await?;
16752        let subject = data
16753            .pointer("/addComment/subject")
16754            .filter(|value| !value.is_null())
16755            .ok_or_else(|| SourceError::Malformed {
16756                message: "GitHub comment addition returned no subject".into(),
16757            })?;
16758        if required_str(subject, "id")? != issue.0 {
16759            return Err(SourceError::Malformed {
16760                message: "GitHub comment addition answered about another issue".into(),
16761            });
16762        }
16763        let added = data
16764            .pointer("/addComment/commentEdge/node")
16765            .filter(|value| !value.is_null())
16766            .ok_or_else(|| SourceError::Malformed {
16767                message: "GitHub comment addition returned no comment".into(),
16768            })?;
16769        let added = comment_from(added)?;
16770        self.remember_commented(&issue)?;
16771        Ok(Some(added))
16772    }
16773
16774    /// Every task commented on read together — [`DETAIL_BATCH`] to a
16775    /// [`graphql::ISSUE_DETAILS`] request — and each comment's hold decided on that read; then
16776    /// every comment it lets through added by aliased `addComment`s of one
16777    /// [`graphql::ADD_COMMENTS`] request per [`COMMENT_BATCH`]. GitHub answers a refusal of one
16778    /// alias at that alias's path, so it fails that comment alone.
16779    ///
16780    /// **Where GitHub would refuse the batch as a whole, each item is read on its own:** a
16781    /// batched node read naming an id that resolves to nothing is refused whole, so each id of
16782    /// that batch is read by itself, the missing one answered missing. A batch of one is the
16783    /// comment alone, as [`Self::add_comment`] adds it.
16784    async fn add_comments(
16785        &self,
16786        comments: &[onetaskgraph_plugin_api::BatchComment],
16787    ) -> Vec<Result<onetaskgraph_plugin_api::BatchAnswer<Comment>, SourceError>> {
16788        self.comments_batched(comments).await
16789    }
16790
16791    async fn edit_comment(
16792        &self,
16793        task: &NativeId,
16794        comment: &NativeId,
16795        body: &CommentBody,
16796    ) -> Result<Option<Comment>, SourceError> {
16797        let Some(issue) = self.commented_issue(task).await? else {
16798            return Ok(None);
16799        };
16800        let Some(held) = self.comment_on(&issue, comment).await? else {
16801            return Ok(None);
16802        };
16803        // A comment a copy wrote keeps its origin through an edit: its marker is carried over.
16804        let body = CommentOrigin::kept(&held, body)?;
16805        let data = self
16806            .graphql(
16807                graphql::UPDATE_COMMENT,
16808                json!({"input":{"id":comment.0,"body":body.as_str()}}),
16809            )
16810            .await?;
16811        let edited = data
16812            .pointer("/updateIssueComment/issueComment")
16813            .filter(|value| !value.is_null())
16814            .ok_or_else(|| SourceError::Malformed {
16815                message: "GitHub comment update returned no comment".into(),
16816            })?;
16817        let edited = comment_from(edited)?;
16818        if edited.id != *comment {
16819            return Err(SourceError::Malformed {
16820                message: "GitHub comment update returned the wrong comment".into(),
16821            });
16822        }
16823        self.remember_commented(&issue)?;
16824        Ok(Some(edited))
16825    }
16826
16827    async fn delete_comment(
16828        &self,
16829        task: &NativeId,
16830        comment: &NativeId,
16831    ) -> Result<Option<NativeId>, SourceError> {
16832        let Some(issue) = self.commented_issue(task).await? else {
16833            return Ok(None);
16834        };
16835        if !self.comment_is_on(&issue, comment).await? {
16836            return Ok(None);
16837        }
16838        self.held_comments()?.remove(&issue);
16839        let data = self
16840            .graphql(graphql::DELETE_COMMENT, json!({"input":{"id":comment.0}}))
16841            .await?;
16842        // The payload says nothing about the comment it removed, so what is checked is that
16843        // GitHub answered the mutation at all rather than leaving it unanswered.
16844        data.get("deleteIssueComment")
16845            .filter(|value| !value.is_null())
16846            .ok_or_else(|| SourceError::Malformed {
16847                message: "GitHub comment deletion returned no payload".into(),
16848            })?;
16849        Ok(Some(comment.clone()))
16850    }
16851
16852    /// Every request this source has recorded, and what each of GitHub's two budgets was
16853    /// attributed — read off the same accounting the session report is rendered from, so
16854    /// the two cannot count one request two ways.
16855    async fn metering(&self) -> Result<Option<Metering>, SourceError> {
16856        Ok(Some(self.ledger.snapshot().metering()))
16857    }
16858
16859    /// One `GET /rate_limit` at this source's endpoint, every resource it reports, asked
16860    /// afresh each time and counted in nothing [`metering`](TaskSource::metering) reports:
16861    /// GitHub documents the endpoint as free. See [`quota`].
16862    async fn quota(&self) -> Result<Vec<onetaskgraph_plugin_api::QuotaReading>, SourceError> {
16863        self.rate_limits().await
16864    }
16865
16866    /// Drop every item, search answer and board read this source holds, so the next command
16867    /// reads the board as a person has since left it.
16868    ///
16869    /// Every one of those is held on the assumption that nothing but this source writes the
16870    /// board while a command runs, which stops being true the moment the command is over: a
16871    /// body a person edited would be overwritten from the record held here, and a card they
16872    /// moved would be read as still where this source left it. The board's own field
16873    /// definitions go too, because a person can add or delete a `Status` option and a write
16874    /// resolved against the held list would not re-read on a miss. What stays is what stays
16875    /// valid in normal use: each repository's node id, which a miss re-reads, the pacing of
16876    /// mutations, which is about GitHub's limiter rather than anybody's work, and the running
16877    /// accounting [`metering`](TaskSource::metering) answers from.
16878    ///
16879    /// Infallible in practice: a lock an earlier failure poisoned is cleared rather than
16880    /// refused, because clearing it is what puts it right.
16881    async fn end_command(&self) -> Result<(), SourceError> {
16882        fn clear<T: Default>(held: &Mutex<T>) {
16883            *held
16884                .lock()
16885                .unwrap_or_else(std::sync::PoisonError::into_inner) = T::default();
16886            held.clear_poison();
16887        }
16888        clear(&self.created);
16889        clear(&self.updated);
16890        clear(&self.commented);
16891        clear(&self.board_cache);
16892        clear(&self.search_cache);
16893        clear(&self.narrowed_cache);
16894        clear(&self.search_next);
16895        clear(&self.resolved_cache);
16896        clear(&self.read_ahead);
16897        clear(&self.pending_origins);
16898        clear(&self.member_classes);
16899        clear(&self.carried);
16900        clear(&self.held_cache);
16901        clear(&self.children_cache);
16902        clear(&self.task_children);
16903        clear(&self.written);
16904        clear(&self.fields_cache);
16905        clear(&self.held_comments);
16906        clear(&self.task_writes);
16907        clear(&self.written_tokens);
16908        self.forget_at_end_of_call();
16909        self.expected.end_command();
16910        Ok(())
16911    }
16912}
16913
16914/// One member of a project as a classification-only read answers it: its classification and
16915/// the repositories its work changes.
16916type MemberClass = (Classification, Vec<Repository>);
16917
16918/// Each project's sub-issues as one command read them, keyed by the selector they were asked
16919/// for under, beside the project that selector named; see `children_cache`.
16920type ProjectChildren = BTreeMap<NativeId, (NativeId, Vec<Resolved>)>;
16921
16922/// One issue comment as the contract carries it.
16923///
16924/// `author` is absent both when GitHub answers `null` for an account that no longer exists
16925/// and when it answers an actor with no login, because either way the source did not say who
16926/// wrote it — which is what an absent author means, rather than an author called nothing.
16927///
16928/// A comment a copy wrote here carries its origin as the hidden marker at the end of its body
16929/// — GitHub sets every comment's author and times itself, so there is nowhere else to keep it —
16930/// and is read back with the marker taken out and reported as its origin.
16931fn comment_from(value: &Value) -> Result<Comment, SourceError> {
16932    let actor = value.get("author").unwrap_or(&Value::Null);
16933    // A bot's login is spelled as GitHub's own pages spell it, `<login>[bot]`, so a reader —
16934    // and every copy of the comment — can tell it from a person's.
16935    let bot = actor.get("__typename").and_then(Value::as_str) == Some("Bot");
16936    Ok(Comment {
16937        origin: None,
16938        id: NativeId(required_str(value, "id")?.to_owned()),
16939        author: optional_str(actor, "login")?.map(|login| {
16940            if bot && !login.ends_with("[bot]") {
16941                format!("{login}[bot]")
16942            } else {
16943                login.to_owned()
16944            }
16945        }),
16946        created_at: optional_time(value, "createdAt")?,
16947        updated_at: optional_time(value, "updatedAt")?,
16948        body: required_str(value, "body")?.to_owned(),
16949        url: optional_str(value, "url")?.map(str::to_owned),
16950    }
16951    .unmarked())
16952}
16953
16954/// The page of comments one issue node carries, resumed from `after`.
16955fn comment_page(
16956    node: &Value,
16957    issue: &str,
16958    after: Option<&str>,
16959) -> Result<Page<Comment>, SourceError> {
16960    let connection = node
16961        .get("comments")
16962        .filter(|value| !value.is_null())
16963        .ok_or_else(|| SourceError::Malformed {
16964            message: format!("GitHub issue {issue} answered with no comments connection"),
16965        })?;
16966    let items = optional_nodes(Some(connection), "issue comments")?
16967        .into_iter()
16968        .flatten()
16969        .map(comment_from)
16970        .collect::<Result<Vec<_>, _>>()?;
16971    let next = next_cursor(connection)?;
16972    if let Some(next) = &next {
16973        validate_cursor_progress(after, &next.0)?;
16974    }
16975    Ok(Page { items, next })
16976}
16977
16978/// The far ends of an issue's whole `blockedBy` connection, when the read carried it to its
16979/// end — `None` when it carried none, or a page with more past it.
16980fn carried_blocked_by(content: &Value) -> Result<Option<Vec<Value>>, SourceError> {
16981    let Some(connection) = content.get("blockedBy").filter(|value| !value.is_null()) else {
16982        return Ok(None);
16983    };
16984    if next_cursor(connection)?.is_some() {
16985        return Ok(None);
16986    }
16987    Ok(Some(
16988        optional_nodes(Some(connection), "blocked-by issues")?
16989            .into_iter()
16990            .flatten()
16991            .cloned()
16992            .collect(),
16993    ))
16994}
16995
16996/// Where the recorded tail of a dependency walk resumes; see
16997/// [`GitHubProjectsSource::recorded_edges`].
16998const RECORDED_CURSOR: &str = "onetaskgraph.depends_on:";
16999
17000/// The board text field this source keeps a copy's origin in.
17001///
17002/// Named after the key it holds, and held to that name by the guard below rather than by
17003/// a reader noticing.
17004const ORIGIN_FIELD: &str = "onetaskgraph.origin";
17005
17006/// The metadata key that field holds.
17007///
17008/// The engine owns this key and spells it once as `GlobalId::ORIGIN_KEY`; a plugin never
17009/// constructs or interprets the qualified id it carries. This source names it only to
17010/// route it — a short, typed value belongs in a typed field rather than in the body slot
17011/// a caller's own prose shares.
17012///
17013/// Restated rather than imported, because no plugin crate may depend on the engine. What
17014/// keeps the two spellings one contract is `scripts/check-origin-key-spelling.sh`, a
17015/// target in `check`: it reads the engine's own literal and fails naming the file and the
17016/// line when a plugin's parts from it either way. Drift here has one symptom — a copy
17017/// that creates a second item every run instead of finding the one it wrote — and that is
17018/// too late to learn it.
17019const ORIGIN_KEY: &str = "onetaskgraph.origin";
17020
17021/// Where a recorded tail resumes, refusing a cursor no walk in `direction` reported.
17022///
17023/// The reserved key holds forward edges and nothing else — the reverse of a recorded edge
17024/// is derived from the far end, never written down on the near item — so only a forward
17025/// walk ever reports one of these cursors. A reverse read carrying one is resuming a walk
17026/// it did not come from, and it is told so rather than answered with an empty page that
17027/// reads as a walk which ended.
17028fn recorded_offset(
17029    cursor: Option<&str>,
17030    direction: Direction,
17031) -> Result<Option<usize>, SourceError> {
17032    cursor
17033        .and_then(|cursor| cursor.strip_prefix(RECORDED_CURSOR))
17034        .map(|offset| {
17035            if direction != Direction::DependsOn {
17036                return Err(SourceError::Config {
17037                    message: format!(
17038                        "{RECORDED_CURSOR}{offset} resumes recorded forward edges, which a \
17039                         reverse dependency read never issues; resume it in the direction \
17040                         that reported it"
17041                    ),
17042                });
17043            }
17044            offset.parse().map_err(|_| SourceError::Config {
17045                message: format!("{RECORDED_CURSOR}{offset} is not a recorded-edge cursor"),
17046            })
17047        })
17048        .transpose()
17049}
17050
17051/// What a dependency read's own answer says of a board draft: `None` when the item is not a
17052/// draft, or the answer did not carry its board item; `Some(None)` for a draft whose one board
17053/// item is not on this board, which this source does not hold; and `Some(Some(slot))`, the
17054/// draft's metadata, for one it does — its board item naming this board by its number and by
17055/// the id the same answer read of the board, as [`GitHubProjectsSource::draft_by_id`] decides.
17056fn draft_slot(
17057    data: &Value,
17058    id: &NativeId,
17059    project_number: u32,
17060) -> Result<Option<Option<BTreeMap<String, Value>>>, SourceError> {
17061    let Some(draft) = data
17062        .get("node")
17063        .filter(|node| node.get("__typename").and_then(Value::as_str) == Some("DraftIssue"))
17064    else {
17065        return Ok(None);
17066    };
17067    let Some(items) = data.pointer("/draft/projectV2Items") else {
17068        return Ok(None);
17069    };
17070    if required_str(draft, "id")? != id.0 {
17071        return Err(SourceError::Malformed {
17072            message: format!("GitHub answered a different draft for {}", id.0),
17073        });
17074    }
17075    let nodes = items
17076        .get("nodes")
17077        .and_then(Value::as_array)
17078        .ok_or_else(|| SourceError::Malformed {
17079            message: format!("GitHub draft {} projectV2Items.nodes is not an array", id.0),
17080        })?;
17081    let info = items
17082        .get("pageInfo")
17083        .ok_or_else(|| SourceError::Malformed {
17084            message: format!("GitHub draft {} projectV2Items has no pageInfo", id.0),
17085        })?;
17086    if required_bool(info, "hasNextPage")? || nodes.len() > 1 {
17087        return Err(SourceError::Malformed {
17088            message: format!(
17089                "GitHub draft {} reports more board items than the one GitHub links a draft to",
17090                id.0
17091            ),
17092        });
17093    }
17094    let board = data
17095        .pointer("/board/projectV2/id")
17096        .and_then(Value::as_str)
17097        .ok_or_else(|| SourceError::Malformed {
17098            message: format!(
17099                "GitHub answered draft {} without this board's own id beside it",
17100                id.0
17101            ),
17102        })?;
17103    let mut held = false;
17104    for node in nodes {
17105        let project = node.get("project").ok_or_else(|| SourceError::Malformed {
17106            message: format!("GitHub draft {} board item has no project", id.0),
17107        })?;
17108        let number = project
17109            .get("number")
17110            .and_then(Value::as_u64)
17111            .ok_or_else(|| SourceError::Malformed {
17112                message: format!(
17113                    "GitHub draft {} board item has no numeric project number",
17114                    id.0
17115                ),
17116            })?;
17117        let project_id = required_str(project, "id")?;
17118        held |= number == u64::from(project_number) && project_id == board;
17119    }
17120    if !held {
17121        return Ok(Some(None));
17122    }
17123    Ok(Some(Some(
17124        metadata_body(optional_str(draft, "body")?.map(str::to_owned))?.1,
17125    )))
17126}
17127
17128fn recorded_page(edges: Vec<DependencyEdge>, offset: usize, limit: usize) -> Page<DependencyEdge> {
17129    let mut page = offset_page(edges, offset, limit.max(1));
17130    page.next = page
17131        .next
17132        .map(|cursor| Cursor(format!("{RECORDED_CURSOR}{}", cursor.0)));
17133    page
17134}
17135
17136/// The kind of one issue reached through a dependency connection.
17137///
17138/// The same questions the board scan asks, over the fields the dependency document
17139/// selects, and in the same order: the design prefix first, then a sub-issue is a task,
17140/// then anything with sub-issues or the marker is a project.
17141///
17142/// # Errors
17143///
17144/// A far end this board holds as a document is refused rather than reported. The two
17145/// answers that are not refusals would both be wrong: reporting it as a task names an id
17146/// no task read of this source can find, and reporting it as a project names one no
17147/// project read can. There is no third value to return — `ItemKind` has no document
17148/// variant, because nothing may point at a document — so the relationship itself is what
17149/// the person is told about.
17150fn related_kind(value: &Value, meaning: SubIssues) -> Result<ItemKind, SourceError> {
17151    let id = required_str(value, "id")?;
17152    if required_str(value, "title")?.starts_with(DESIGN_TITLE_PREFIX) {
17153        return Err(SourceError::Refused {
17154            message: format!(
17155                "GitHub issue {id} is a document of this board — its title begins \
17156                 {DESIGN_TITLE_PREFIX:?} — and nothing may depend on a document or be depended \
17157                 on by one; next: remove that issue's blocking relationship on this board"
17158            ),
17159        });
17160    }
17161    let parent = optional_str(value.get("parent").unwrap_or(&Value::Null), "id")?;
17162    if parent.is_some() || meaning == SubIssues::Parent {
17163        return Ok(ItemKind::Task);
17164    }
17165    let (_, slot) = metadata_body(optional_str(value, "body")?.map(str::to_owned))?;
17166    let marked = ItemKind::from_metadata(&slot).map_err(|message| SourceError::Malformed {
17167        message: format!("GitHub issue {id}: {message}"),
17168    })?;
17169    let sub_issues = sub_issue_total(value)?;
17170    Ok(if sub_issues > 0 || marked == Some(ItemKind::Project) {
17171        ItemKind::Project
17172    } else {
17173        ItemKind::Task
17174    })
17175}
17176
17177/// The reason GitHub records an issue closed as a duplicate of another under.
17178const DUPLICATE_REASON: &str = "DUPLICATE";
17179
17180/// The `stateInput` that closes an issue for `reason`.
17181fn closed_input(reason: ClosedState) -> Value {
17182    json!({"value":"CLOSED","stateReason":reason.reason()})
17183}
17184
17185/// The `IssueStateUpdateInput` one status target asks for.
17186///
17187/// `stateInput` and `state` are mutually exclusive on `UpdateIssueInput`, and only this
17188/// one is ever sent. A non-terminal status always asks for `OPEN`, which is what reopens
17189/// a currently-closed issue: without that the item would read back `Unknown` and a copy
17190/// would report a change forever. A document has no status at all, and asks for neither.
17191fn state_input(target: Option<&StatusTarget>) -> Value {
17192    match target {
17193        Some(StatusTarget::Terminal(_, reason)) => closed_input(*reason),
17194        Some(StatusTarget::Column(_) | StatusTarget::Disabled(_)) => json!({"value":"OPEN"}),
17195        // A document has no status, so a write of one says nothing about the issue's open
17196        // or closed state rather than forcing it open: `stateInput` is what carries that
17197        // instruction, and an explicit null asks for no change to it.
17198        None => Value::Null,
17199    }
17200}
17201
17202/// The metadata one write stores in the item's body slot.
17203///
17204/// The typed fields travel as themselves, so the three reserved keys are rebuilt here
17205/// rather than carried: the kind marker so an empty project stays readable, the
17206/// repository list only when it is not exactly the issue's own repository, and the far
17207/// ends no relationship here can name.
17208///
17209/// The copy origin is the one typed field that is also mirrored here, and only as a
17210/// mirror: it lands in the board's origin field as well, which stays the one every reader
17211/// takes it from, and it is here so that GitHub's issue search — which indexes this comment
17212/// and catches up with a write in seconds rather than minutes — can find the item by it.
17213/// A reader of the release before this one drops the slot's copy and reads the field, so an
17214/// item written here still reads with exactly one origin there.
17215fn slot_metadata(
17216    incoming: &Incoming<'_>,
17217    own_repository: Option<&Repository>,
17218    fallback: &[DependencyEdge],
17219) -> BTreeMap<String, Value> {
17220    let mut metadata = incoming.metadata.clone();
17221    match metadata.remove(ORIGIN_KEY) {
17222        Some(Value::String(origin)) if !origin.is_empty() => {
17223            metadata.insert(ORIGIN_KEY.to_owned(), Value::String(origin));
17224        }
17225        _ => {}
17226    }
17227    match incoming.written.kind() {
17228        BoardKind::Work(kind) => metadata.insert(
17229            ItemKind::METADATA_KEY.to_owned(),
17230            Value::String(kind.marker().to_owned()),
17231        ),
17232        // A document is told by its title, so it carries no kind marker: that key names
17233        // what a dependency endpoint points at, and nothing may point at a document.
17234        BoardKind::Document => metadata.remove(ItemKind::METADATA_KEY),
17235    };
17236    incoming.classification.record(&mut metadata);
17237    let derivable = own_repository
17238        .map(|own| incoming.repositories == [own.clone()])
17239        .unwrap_or(incoming.repositories.is_empty());
17240    if derivable {
17241        metadata.remove(Repository::METADATA_KEY);
17242    } else {
17243        metadata.insert(
17244            Repository::METADATA_KEY.to_owned(),
17245            Value::Array(
17246                incoming
17247                    .repositories
17248                    .iter()
17249                    .map(|repository| Value::String(repository.as_str().to_owned()))
17250                    .collect(),
17251            ),
17252        );
17253    }
17254    // The typed lists are what land, whatever the caller's own metadata held under their
17255    // keys: a key of either name travelling beside the field would otherwise be a second
17256    // answer to the same question, and the field is the one the contract names.
17257    for (key, entries) in [
17258        (TaskRef::DELIVERS_KEY, incoming.delivers),
17259        (TaskRef::DELIVERED_BY_KEY, incoming.delivered_by),
17260    ] {
17261        set_task_list(&mut metadata, key, entries);
17262    }
17263    record_edges(&mut metadata, fallback);
17264    metadata
17265}
17266
17267/// Hold the far ends no relationship here can name under [`DependencyEdge::RECORDED_KEY`] in
17268/// one slot's metadata, or no such key when there are none.
17269fn record_edges(metadata: &mut BTreeMap<String, Value>, fallback: &[DependencyEdge]) {
17270    if fallback.is_empty() {
17271        metadata.remove(DependencyEdge::RECORDED_KEY);
17272    } else {
17273        metadata.insert(
17274            DependencyEdge::RECORDED_KEY.to_owned(),
17275            Value::Array(
17276                fallback
17277                    .iter()
17278                    .map(|edge| {
17279                        serde_json::to_value(&edge.to).expect("an endpoint renders as JSON")
17280                    })
17281                    .collect(),
17282            ),
17283        );
17284    }
17285}
17286
17287/// Every label one item carries, from its content's own connection and nowhere else.
17288///
17289/// There is no second place to read one from: no document this source sends selects the
17290/// board's built-in `Labels` field, because GitHub derives it from the content and a draft
17291/// cannot carry one at all. The module documentation records the three schema facts that
17292/// settle it.
17293fn labels(content: &Value) -> Result<Vec<Label>, SourceError> {
17294    optional_nodes(content.get("labels"), "content labels")?
17295        .into_iter()
17296        .flatten()
17297        .map(|v| {
17298            Ok(Label {
17299                id: NativeId(required_str(v, "id")?.to_owned()),
17300                name: required_str(v, "name")?.to_owned(),
17301                color: optional_str(v, "color")?.map(str::to_owned),
17302            })
17303        })
17304        .collect()
17305}
17306
17307/// Each board field value one item holds, as the change token's facets name it: the field's
17308/// name, with the single-select option's name or the text. A value of a type no read here
17309/// selects, and one naming no field, says nothing a person can rename and is left out.
17310fn facet_fields(field_values: &[Value]) -> Vec<(String, String)> {
17311    field_values
17312        .iter()
17313        .filter_map(|value| {
17314            let field = value.pointer("/field/name")?.as_str()?;
17315            let held = value.get("name").or_else(|| value.get("text"))?.as_str()?;
17316            Some((field.to_owned(), held.to_owned()))
17317        })
17318        .collect()
17319}
17320
17321/// The digest of the facets of the issue `content`, whose board item's values are
17322/// `field_values` — or `None` when the response did not carry, whole, every member they are read
17323/// from: the title, the parent, the sub-issue summary and the body its kind is read from, every
17324/// label, and every field value.
17325///
17326/// What a write's own response spells its token from, by exactly the rules a read takes them by.
17327fn facets_of(content: &Value, field_values: &Value) -> Option<change_token::FacetsDigest> {
17328    let ended = |connection: &Value| {
17329        connection.pointer("/pageInfo/hasNextPage") == Some(&Value::Bool(false))
17330    };
17331    let labels = content.get("labels").filter(|labels| ended(labels))?;
17332    if !ended(field_values) {
17333        return None;
17334    }
17335    let parent = content.get("parent")?;
17336    let (_, slot) = metadata_body(content.get("body")?.as_str().map(str::to_owned)).ok()?;
17337    let kind = BoardKind::of(
17338        content.get("title")?.as_str()?,
17339        !parent.is_null(),
17340        sub_issue_total(content).ok()?,
17341        ItemKind::from_metadata(&slot).ok()?,
17342    );
17343    let labels = self::labels(&json!({"labels": labels})).ok()?;
17344    let nodes = field_values.get("nodes")?.as_array()?;
17345    Some(change_token::Facets::new(kind.facet(), facet_fields(nodes), &labels).digest())
17346}
17347
17348/// The definition of each board field one item's values are values of, in the shape a read
17349/// of the board's own `fields` gives one.
17350///
17351/// A value names its field through a fragment on that field's own type, so the type is
17352/// known from which kind of value it is: a single-select value's field is a
17353/// `ProjectV2SingleSelectField`, options and all, and a text value's is a `ProjectV2Field`.
17354/// A value whose field carried no id, or an empty one, says nothing usable and is left out.
17355fn field_definitions(field_values: &[Value]) -> Vec<Value> {
17356    field_values
17357        .iter()
17358        .filter_map(|value| {
17359            let field = value.get("field")?.as_object()?;
17360            field.get("id")?.as_str().filter(|id| !id.is_empty())?;
17361            let typename = if value.get("text").is_some() {
17362                "ProjectV2Field"
17363            } else if value.get("name").is_some() {
17364                "ProjectV2SingleSelectField"
17365            } else {
17366                return None;
17367            };
17368            let mut defined = field.clone();
17369            defined.insert("__typename".to_owned(), json!(typename));
17370            // Only a text field holds a text value, so the value says the field's type too.
17371            if typename == "ProjectV2Field" {
17372                defined.insert("dataType".to_owned(), json!("TEXT"));
17373            }
17374            Some(Value::Object(defined))
17375        })
17376        .collect()
17377}
17378
17379fn text_field(field_values: &[Value], name: &str) -> Result<Option<String>, SourceError> {
17380    let Some(node) = field_values
17381        .iter()
17382        .find(|node| node.pointer("/field/name").and_then(Value::as_str) == Some(name))
17383    else {
17384        return Ok(None);
17385    };
17386    Ok(optional_str(node, "text")?.map(str::to_owned))
17387}
17388
17389fn valid_github_owner(owner: &str) -> bool {
17390    !owner.is_empty()
17391        && owner.len() <= 39
17392        && !owner.starts_with('-')
17393        && !owner.ends_with('-')
17394        && !owner.contains("--")
17395        && owner
17396            .bytes()
17397            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
17398}
17399
17400/// GitHub's repository-name grammar: 1-100 ASCII letters, digits, `-`, `_` or `.`, and
17401/// neither of the two names a path segment already means.
17402fn valid_github_repository_name(name: &str) -> bool {
17403    !name.is_empty()
17404        && name.len() <= 100
17405        && name != "."
17406        && name != ".."
17407        && name
17408            .bytes()
17409            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
17410}
17411
17412fn valid_environment_name(name: &str) -> bool {
17413    let mut bytes = name.bytes();
17414    bytes
17415        .next()
17416        .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
17417        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
17418}
17419
17420/// How many sub-issues one issue has.
17421///
17422/// `Issue.subIssuesSummary` is `SubIssuesSummary!` and its `total` is `Int!`, so an
17423/// absent or non-integer one is a response this source cannot read — and reading it as
17424/// zero would classify a project as a task, which is exactly the mistake the marker
17425/// exists to keep from happening quietly.
17426fn sub_issue_total(issue: &Value) -> Result<u64, SourceError> {
17427    let summary = issue
17428        .get("subIssuesSummary")
17429        .ok_or_else(|| SourceError::Malformed {
17430            message: "GitHub issue is missing subIssuesSummary".into(),
17431        })?;
17432    summary
17433        .get("total")
17434        .and_then(Value::as_u64)
17435        .ok_or_else(|| SourceError::Malformed {
17436            message: "GitHub issue subIssuesSummary.total is not an unsigned integer".into(),
17437        })
17438}
17439
17440/// One issue's own `number`.
17441///
17442/// An issue always has one: GitHub declares `Issue.number` as `Int!` and every selection of
17443/// an issue in this module asks for it. So a read of one that comes back without it, or
17444/// with something that is not an unsigned integer, is a response this source cannot read —
17445/// absence here is **not** "this issue has no number". A draft is the content that has
17446/// none, and a draft never reaches this: the caller decides on `__typename` first, the way
17447/// it does for `subIssuesSummary`, which `DraftIssue` equally declares nothing for.
17448fn issue_number(issue: &Value) -> Result<u64, SourceError> {
17449    issue
17450        .get("number")
17451        .and_then(Value::as_u64)
17452        .ok_or_else(|| SourceError::Malformed {
17453            message: "GitHub issue number is missing or is not an unsigned integer".into(),
17454        })
17455}
17456
17457/// The `number` a creating mutation answered with, and `None` when it answered without one;
17458/// why a missing one is tolerated is at the call in `create_and_file_issue`.
17459fn created_issue_number(created: &Value) -> Result<Option<u64>, SourceError> {
17460    match created.get("number") {
17461        None | Some(Value::Null) => Ok(None),
17462        Some(value) => value
17463            .as_u64()
17464            .map(Some)
17465            .ok_or_else(|| SourceError::Malformed {
17466                message: "GitHub created issue number is not an unsigned integer".into(),
17467            }),
17468    }
17469}
17470
17471fn required_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
17472    value
17473        .get(field)
17474        .and_then(Value::as_str)
17475        .ok_or_else(|| SourceError::Malformed {
17476            message: format!("GitHub response is missing string field {field}"),
17477        })
17478}
17479
17480fn required_nonblank_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
17481    let found = required_str(value, field)?;
17482    if found.trim().is_empty() {
17483        return Err(SourceError::Malformed {
17484            message: format!("GitHub response has blank string field {field}"),
17485        });
17486    }
17487    Ok(found)
17488}
17489
17490/// The slot's delimiters, which `docs/metadata.md` settles once for every source that
17491/// needs one — Linear spells them too, in its own description field.
17492///
17493/// Restated rather than shared, because a plugin crate depends on the contract crate and
17494/// nothing else of this workspace. `scripts/check-metadata-slot-encoding.sh`, a target in
17495/// `check`, is what keeps the two one encoding: drift is otherwise quiet, since each
17496/// source round-trips its own writes perfectly well under its own spelling.
17497const METADATA_OPEN: &str = "<!-- onetaskgraph.metadata\n";
17498const METADATA_CLOSE: &str = "\n-->";
17499
17500/// What the composer puts between a non-empty visible body and the slot, and the one thing
17501/// the parser takes off the visible body when it takes the slot off — exactly once, so every
17502/// other trailing byte of the body comes back as it was written.
17503// 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.
17504const METADATA_SEPARATOR: &str = "\n\n";
17505
17506/// The visible body and the metadata slot at the end of it.
17507///
17508/// The encoding is the one `docs/metadata.md` settles for Linear, which is where its
17509/// reasons are. Only a comment at the very end is a slot; one in the middle is a person's
17510/// own content and is left alone. The visible body is everything before the slot less the
17511/// one [`METADATA_SEPARATOR`] the composer put there, byte for byte.
17512fn metadata_body(
17513    body: Option<String>,
17514) -> Result<(Option<String>, BTreeMap<String, Value>), SourceError> {
17515    let Some(body) = body else {
17516        return Ok((None, BTreeMap::new()));
17517    };
17518    let Some(slot) = slot_span(&body)? else {
17519        return Ok((Some(body), BTreeMap::new()));
17520    };
17521    let metadata =
17522        serde_json::from_str(&body[slot.encoded_start..slot.encoded_end]).map_err(|error| {
17523            SourceError::Malformed {
17524                message: format!(
17525                    "invalid canonical JSON in GitHub issue onetaskgraph metadata slot: {error}"
17526                ),
17527            }
17528        })?;
17529    let before = &body[..slot.start];
17530    let visible = before.strip_suffix(METADATA_SEPARATOR).unwrap_or(before);
17531    Ok(((!visible.is_empty()).then(|| visible.to_owned()), metadata))
17532}
17533
17534/// Where the metadata slot sits in one body, as byte offsets into it.
17535struct SlotSpan {
17536    /// Where [`METADATA_OPEN`] begins.
17537    start: usize,
17538    /// Where the encoded JSON begins, just past [`METADATA_OPEN`].
17539    encoded_start: usize,
17540    /// Where the encoded JSON ends, at the start of [`METADATA_CLOSE`].
17541    encoded_end: usize,
17542    /// Just past [`METADATA_CLOSE`].
17543    end: usize,
17544}
17545
17546/// The slot at the very end of `body`, or `None` when it has none.
17547///
17548/// The one reading of *where the slot is*, shared by [`metadata_body`], which reads it, and
17549/// [`with_slot`], which rewrites it — so the two cannot disagree about which comment is the
17550/// slot.
17551fn slot_span(body: &str) -> Result<Option<SlotSpan>, SourceError> {
17552    let Some(start) = body.rfind(METADATA_OPEN) else {
17553        return Ok(None);
17554    };
17555    let encoded_start = start + METADATA_OPEN.len();
17556    let Some(relative_end) = body[encoded_start..].find(METADATA_CLOSE) else {
17557        return Err(SourceError::Malformed {
17558            message: "unterminated onetaskgraph metadata slot in GitHub issue body".into(),
17559        });
17560    };
17561    let encoded_end = encoded_start + relative_end;
17562    let end = encoded_end + METADATA_CLOSE.len();
17563    if !body[end..].trim().is_empty() {
17564        return Ok(None);
17565    }
17566    Ok(Some(SlotSpan {
17567        start,
17568        encoded_start,
17569        encoded_end,
17570        end,
17571    }))
17572}
17573
17574/// `body` with its metadata slot holding exactly `metadata`, and every byte outside the
17575/// slot as it was.
17576///
17577/// A slot that is there has its JSON replaced in place; one that becomes empty is removed
17578/// together with the one [`METADATA_SEPARATOR`] separating it from the prose before it. A
17579/// body with no slot gains one the way [`compose_body`] writes it — after that separator,
17580/// or alone in an empty body — and a body with no slot that is given no metadata is
17581/// returned as it is.
17582fn with_slot(body: &str, metadata: &BTreeMap<String, Value>) -> Result<String, SourceError> {
17583    let encoded = if metadata.is_empty() {
17584        None
17585    } else {
17586        Some(
17587            serde_json::to_string(metadata).map_err(|error| SourceError::Malformed {
17588                message: error.to_string(),
17589            })?,
17590        )
17591    };
17592    Ok(match (slot_span(body)?, encoded) {
17593        (Some(slot), Some(encoded)) => format!(
17594            "{}{encoded}{}",
17595            &body[..slot.encoded_start],
17596            &body[slot.encoded_end..]
17597        ),
17598        (Some(slot), None) => {
17599            let before = &body[..slot.start];
17600            format!(
17601                "{}{}",
17602                before.strip_suffix(METADATA_SEPARATOR).unwrap_or(before),
17603                &body[slot.end..]
17604            )
17605        }
17606        (None, None) => body.to_owned(),
17607        (None, Some(encoded)) if body.is_empty() => {
17608            format!("{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17609        }
17610        (None, Some(encoded)) => {
17611            format!("{body}{METADATA_SEPARATOR}{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17612        }
17613    })
17614}
17615
17616/// `body` with everything before its metadata slot replaced by `content`, and the slot
17617/// itself kept byte for byte.
17618///
17619/// The inverse of how [`metadata_body`] splits a body: the slot, when there is one, follows
17620/// `content` after the one [`METADATA_SEPARATOR`] the composer puts there — or alone, when
17621/// `content` is empty — so a read of the result reports `content` as the visible body and
17622/// the slot's metadata exactly as it was.
17623fn with_content(body: &str, content: &str) -> Result<String, SourceError> {
17624    let Some(slot) = slot_span(body)? else {
17625        return Ok(content.to_owned());
17626    };
17627    let kept = &body[slot.start..];
17628    Ok(if content.is_empty() {
17629        kept.to_owned()
17630    } else {
17631        format!("{content}{METADATA_SEPARATOR}{kept}")
17632    })
17633}
17634
17635/// Hold `entries` under `key` in one slot's metadata, or no such key when there are none.
17636fn set_task_list(metadata: &mut BTreeMap<String, Value>, key: &str, entries: &[TaskRef]) {
17637    if entries.is_empty() {
17638        metadata.remove(key);
17639    } else {
17640        metadata.insert(
17641            key.to_owned(),
17642            Value::Array(
17643                entries
17644                    .iter()
17645                    .map(|entry| Value::String(entry.as_str().to_owned()))
17646                    .collect(),
17647            ),
17648        );
17649    }
17650}
17651
17652fn compose_body(
17653    content: Option<&str>,
17654    metadata: &BTreeMap<String, Value>,
17655) -> Result<Option<String>, SourceError> {
17656    let visible = content.unwrap_or_default();
17657    if metadata.is_empty() {
17658        return Ok((!visible.is_empty()).then(|| visible.to_owned()));
17659    }
17660    let encoded = serde_json::to_string(metadata).map_err(|error| SourceError::Malformed {
17661        message: error.to_string(),
17662    })?;
17663    Ok(Some(if visible.is_empty() {
17664        format!("{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17665    } else {
17666        format!("{visible}{METADATA_SEPARATOR}{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17667    }))
17668}
17669
17670fn required_bool(value: &Value, field: &str) -> Result<bool, SourceError> {
17671    value
17672        .get(field)
17673        .and_then(Value::as_bool)
17674        .ok_or_else(|| SourceError::Malformed {
17675            message: format!("GitHub response is missing boolean field {field}"),
17676        })
17677}
17678fn optional_str<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>, SourceError> {
17679    match value.get(field) {
17680        None | Some(Value::Null) => Ok(None),
17681        Some(value) => value
17682            .as_str()
17683            .map(Some)
17684            .ok_or_else(|| SourceError::Malformed {
17685                message: format!("GitHub response field {field} is not a string or null"),
17686            }),
17687    }
17688}
17689fn optional_nodes<'a>(
17690    connection: Option<&'a Value>,
17691    name: &str,
17692) -> Result<Option<&'a Vec<Value>>, SourceError> {
17693    match connection {
17694        None | Some(Value::Null) => Ok(None),
17695        Some(value) => value
17696            .get("nodes")
17697            .and_then(Value::as_array)
17698            .map(Some)
17699            .ok_or_else(|| SourceError::Malformed {
17700                message: format!("GitHub {name}.nodes is not an array"),
17701            }),
17702    }
17703}
17704fn complete_connection(connection: &Value, name: &str, size: u32) -> Result<(), SourceError> {
17705    let page_info = connection
17706        .get("pageInfo")
17707        .ok_or_else(|| SourceError::Malformed {
17708            message: format!("GitHub {name} has no pageInfo"),
17709        })?;
17710    if required_bool(page_info, "hasNextPage")? {
17711        return Err(SourceError::Malformed {
17712            message: format!(
17713                "GitHub {name} exceeds the supported nested connection size of {size}"
17714            ),
17715        });
17716    }
17717    Ok(())
17718}
17719fn optional_time(value: &Value, field: &str) -> Result<Option<DateTime<Utc>>, SourceError> {
17720    optional_str(value, field)?
17721        .map(|timestamp| {
17722            timestamp.parse().map_err(|error| SourceError::Malformed {
17723                message: format!("GitHub response field {field} is not a timestamp: {error}"),
17724            })
17725        })
17726        .transpose()
17727}
17728fn validate_page(page: &PageRequest) -> Result<(), SourceError> {
17729    if page.limit == 0 {
17730        Err(SourceError::Config {
17731            message: "page limit must be at least 1".into(),
17732        })
17733    } else {
17734        Ok(())
17735    }
17736}
17737fn next_cursor(connection: &Value) -> Result<Option<Cursor>, SourceError> {
17738    let page = connection
17739        .get("pageInfo")
17740        .filter(|value| value.is_object())
17741        .ok_or_else(|| SourceError::Malformed {
17742            message: "GitHub connection is missing pageInfo".into(),
17743        })?;
17744    if required_bool(page, "hasNextPage")? {
17745        let cursor = required_str(page, "endCursor")?;
17746        validate_cursor_progress(None, cursor)?;
17747        Ok(Some(Cursor(cursor.into())))
17748    } else {
17749        Ok(None)
17750    }
17751}
17752fn validate_cursor_progress(previous: Option<&str>, next: &str) -> Result<(), SourceError> {
17753    if next.is_empty() || previous == Some(next) {
17754        Err(SourceError::Malformed {
17755            message: "GitHub pagination cursor is empty or did not advance".into(),
17756        })
17757    } else {
17758        Ok(())
17759    }
17760}
17761/// The version of this plugin's opaque narrowing-search cursor.
17762pub const SEARCH_CURSOR_VERSION: u32 = 4;
17763
17764#[derive(Serialize, Deserialize)]
17765#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
17766enum SearchConnection {
17767    Initial {},
17768    Continuing { after: Cursor },
17769    Exhausted {},
17770}
17771impl SearchConnection {
17772    fn after(&self) -> Option<&str> {
17773        match self {
17774            Self::Continuing { after } => Some(&after.0),
17775            _ => None,
17776        }
17777    }
17778    fn exhausted(&self) -> bool {
17779        matches!(self, Self::Exhausted { .. })
17780    }
17781    /// Whether a cursor naming this position, `offset` rows into its page, is one this
17782    /// plugin could have handed out: a page is resumed only part of the way through it — an
17783    /// offset of a whole page or more would skip rows nobody was given — an initial page
17784    /// only once some of it was handed out, and an exhausted connection has no page to be
17785    /// part of the way through.
17786    fn valid_resume(&self, offset: usize) -> bool {
17787        let within = offset < SEARCH_PAGE_SIZE as usize;
17788        match self {
17789            Self::Initial { .. } => offset > 0 && within,
17790            Self::Continuing { after } => !after.0.is_empty() && within,
17791            Self::Exhausted { .. } => offset == 0,
17792        }
17793    }
17794}
17795
17796/// Versioned source cursor. A zero offset and empty own-write ids are omitted.
17797#[derive(Serialize, Deserialize)]
17798#[serde(deny_unknown_fields)]
17799struct SearchPosition {
17800    version: u32,
17801    connection: SearchConnection,
17802    /// How many rows of the page `connection` starts were already handed out.
17803    #[serde(default, skip_serializing_if = "is_zero")]
17804    offset: usize,
17805    #[serde(default, skip_serializing_if = "Vec::is_empty")]
17806    seen: Vec<NativeId>,
17807    #[serde(default, skip_serializing_if = "Vec::is_empty")]
17808    own: Vec<NativeId>,
17809}
17810impl Default for SearchPosition {
17811    fn default() -> Self {
17812        Self {
17813            version: SEARCH_CURSOR_VERSION,
17814            connection: SearchConnection::Initial {},
17815            offset: 0,
17816            seen: Vec::new(),
17817            own: Vec::new(),
17818        }
17819    }
17820}
17821
17822fn is_zero(offset: &usize) -> bool {
17823    *offset == 0
17824}
17825
17826fn numeric_cursor(cursor: Option<&Cursor>) -> Result<usize, SourceError> {
17827    cursor.map_or(Ok(0), |c| {
17828        c.0.parse().map_err(|_| SourceError::Config {
17829            message: "page cursor is invalid".into(),
17830        })
17831    })
17832}
17833fn offset_page<T>(mut items: Vec<T>, offset: usize, limit: usize) -> Page<T> {
17834    if offset > items.len() {
17835        return Page::last(vec![]);
17836    }
17837    let tail = items.split_off(offset);
17838    let mut selected = tail;
17839    let next = (selected.len() > limit).then(|| Cursor((offset + limit).to_string()));
17840    selected.truncate(limit);
17841    Page {
17842        items: selected,
17843        next,
17844    }
17845}
17846
17847impl GitHubProjectsSource {
17848    /// The body [`Self::write_item`] would compose for `incoming`, sized in the characters
17849    /// [`BODY_LIMIT`] counts, without a request: its slot as `slot_metadata` writes it, every
17850    /// asset reference rewritten to its recorded URL or — for one not uploaded yet — to an
17851    /// address as long as GitHub's, and the heading markup this board's bodies carry.
17852    ///
17853    /// What the write reads rather than knows is taken as it most often lands: the issue in
17854    /// the one repository the item names, else the configured one, and every edge on the
17855    /// board's own relationships rather than in the slot.
17856    fn body_size(&self, incoming: &Incoming<'_>) -> onetaskgraph_plugin_api::BodySize {
17857        let own = match incoming.repositories {
17858            [named] => Some(named.clone()),
17859            _ => self
17860                .repository
17861                .as_ref()
17862                .and_then(|target| Repository::try_from(target.origin()).ok()),
17863        };
17864        let mut slot = slot_metadata(incoming, own.as_ref(), &[]);
17865        let content = match incoming.assets {
17866            Some(assets) => {
17867                let mut uploads = onetaskgraph_plugin_api::AssetUploads::default();
17868                for asset in &assets.assets {
17869                    let url = assets
17870                        .recorded_assets
17871                        .as_ref()
17872                        .and_then(|recorded| recorded.reusable(&asset.name, &asset.sha256))
17873                        .unwrap_or(PREDICTED_ATTACHMENT_URL)
17874                        .to_owned();
17875                    uploads.0.insert(
17876                        asset.name.clone(),
17877                        onetaskgraph_plugin_api::AssetUpload {
17878                            sha256: asset.sha256.clone(),
17879                            url,
17880                        },
17881                    );
17882                }
17883                incoming.content.map(|content| {
17884                    onetaskgraph_plugin_api::serve_asset_references(content, &mut slot, &uploads)
17885                })
17886            }
17887            None => incoming.content.map(str::to_owned),
17888        };
17889        let marked = content.as_deref().map(|content| self.marked(content));
17890        let size = compose_body(marked.as_deref(), &slot)
17891            .ok()
17892            .flatten()
17893            .map_or(0, |body| body.chars().count());
17894        onetaskgraph_plugin_api::BodySize {
17895            size: u64::try_from(size).unwrap_or(u64::MAX),
17896            limit: Some(BODY_LIMIT),
17897        }
17898    }
17899
17900    async fn write_task_assets(
17901        &self,
17902        write: &ItemWrite<Task>,
17903        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
17904    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
17905        self.write_item(
17906            &self.task_incoming(write, assets)?,
17907            write.target.as_ref(),
17908            &write.depends_on,
17909        )
17910        .await
17911    }
17912
17913    /// One task write as [`Self::write_item`] takes it, once what it delivers and its priority
17914    /// are known to be ones this source can write.
17915    fn task_incoming<'a>(
17916        &self,
17917        write: &'a ItemWrite<Task>,
17918        assets: Option<&'a onetaskgraph_plugin_api::AssetWrite>,
17919    ) -> Result<Incoming<'a>, SourceError> {
17920        let near = write.target.as_ref().unwrap_or(&write.item.id);
17921        for (key, entries) in [
17922            (TaskRef::DELIVERS_KEY, &write.item.delivers),
17923            (TaskRef::DELIVERED_BY_KEY, &write.item.delivered_by),
17924        ] {
17925            TaskRef::listed(key, near, Some(&self.name), entries.clone())
17926                .map_err(|message| SourceError::Refused { message })?;
17927        }
17928        if self.priorities.is_none() && write.item.priority != Priority::None {
17929            return Err(self.holds_no_priority());
17930        }
17931        if write.item.assignees.is_some() && !self.assignees {
17932            return Err(onetaskgraph_plugin_api::unwritable_field(KIND, "assignees"));
17933        }
17934        Ok(Incoming {
17935            written: Written::Work(ItemKind::Task, &write.item.status),
17936            title: &write.item.title,
17937            content: write.item.content.as_deref(),
17938            assets,
17939            labels: &write.item.labels,
17940            metadata: &write.item.metadata,
17941            repositories: &write.item.repositories,
17942            classification: write.item.classification,
17943            parent: write.item.project.as_ref(),
17944            delivers: &write.item.delivers,
17945            delivered_by: &write.item.delivered_by,
17946            priority: self.priorities.as_ref().map(|_| write.item.priority),
17947            assignees: write.item.assignees.as_deref(),
17948        })
17949    }
17950    async fn write_document_assets(
17951        &self,
17952        write: &ItemWrite<Document>,
17953        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
17954    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
17955        // A document takes part in no dependency graph, so there is no far end to write
17956        // natively and none to record: a caller naming one is told so rather than having it
17957        // stored under the reserved key, where a later read would report an edge the
17958        // contract says cannot exist.
17959        if !write.depends_on.is_empty() {
17960            return Err(SourceError::Refused {
17961                message: format!(
17962                    "this write names {} dependencies for a document, and a document takes \
17963                     part in no dependency graph; next: put the dependency on the task or \
17964                     project the document is about",
17965                    write.depends_on.len()
17966                ),
17967            });
17968        }
17969        self.write_item(
17970            &Incoming {
17971                written: Written::Document,
17972                title: &write.item.title,
17973                content: write.item.content.as_deref(),
17974                assets,
17975                labels: &write.item.labels,
17976                metadata: &write.item.metadata,
17977                repositories: &write.item.repositories,
17978                classification: write.item.classification,
17979                parent: write.item.project.as_ref(),
17980                delivers: &[],
17981                delivered_by: &[],
17982                priority: None,
17983                assignees: None,
17984            },
17985            write.target.as_ref(),
17986            &[],
17987        )
17988        .await
17989    }
17990}
17991
17992/// What [`TaskSource::end_command`] leaves of this source's held state, asserted on the state
17993/// itself, for the two things no journey can observe.
17994///
17995/// The journeys in `crates/onetaskgraph-e2e/tests/e2e/end_command.rs` prove through the engine,
17996/// with and without the call, that a settlement, a board listing and a metadata search each
17997/// read afresh after it — the resolved records, the written-item overlay, the board and its
17998/// search, and the narrowed searches. What they cannot reach is the held field definitions,
17999/// because a status write naming an option a person deleted is refused the same whether or
18000/// not the list is held, and a poisoned lock, because nothing outside the source can panic
18001/// while one of its locks is held. So these assert those directly, and every other holder
18002/// beside them so a holder added later without a clear in the call fails here.
18003#[cfg(test)]
18004mod end_command_tests {
18005    use super::*;
18006
18007    struct Token;
18008
18009    impl SecretResolver for Token {
18010        fn get(&self, var: &str) -> Option<SecretString> {
18011            (var == "GH_PROJECTS_TOKEN").then(|| "test-token".into())
18012        }
18013    }
18014
18015    fn source() -> GitHubProjectsSource {
18016        let config = serde_json::from_value(json!({
18017            "owner": "octo-org", "project_number": 7, "repository": "acme/work",
18018            // Nothing here is sent: the source is only built and its state inspected.
18019            "endpoint": "http://127.0.0.1:9/graphql",
18020        }))
18021        .expect("a usable configuration");
18022        GitHubProjectsSource::new(&SourceName::new("work").unwrap(), config, &Token)
18023            .expect("the source builds")
18024    }
18025
18026    /// One issue as a board read answers it.
18027    fn resolved(source: &GitHubProjectsSource) -> Resolved {
18028        source
18029            .resolve(&json!({
18030                "id": "ITEM-1",
18031                "content": {"__typename": "Issue", "id": "I_1", "title": "Held",
18032                            "body": "what a person may since have edited", "state": "OPEN",
18033                            "stateReason": null, "url": null, "number": 1,
18034                            "subIssuesSummary": {"total": 0},
18035                            "labels": {"nodes": [], "pageInfo": {"hasNextPage": false}}},
18036                "fieldValues": {"nodes": [], "pageInfo": {"hasNextPage": false}},
18037            }))
18038            .expect("the item reads")
18039            .expect("an issue")
18040    }
18041
18042    /// Hold something in every holder the call clears, and the repository id it keeps.
18043    fn fill(source: &GitHubProjectsSource) {
18044        let item = resolved(source);
18045        source.created.lock().unwrap().push(item.clone());
18046        source.updated.lock().unwrap().push(item.clone());
18047        *source.board_cache.lock().unwrap() = Some(Board {
18048            id: "PVT-board".into(),
18049            fields: json!({"nodes": []}),
18050            items: vec![item.clone()],
18051        });
18052        *source.search_cache.lock().unwrap() = Some(vec![item.clone()]);
18053        source
18054            .narrowed_cache
18055            .lock()
18056            .unwrap()
18057            .insert("status:todo".into(), vec![item.clone()]);
18058        source.children_cache.lock().unwrap().insert(
18059            NativeId("P-1".into()),
18060            (NativeId("P-1".into()), vec![item.clone()]),
18061        );
18062        source
18063            .search_next
18064            .lock()
18065            .unwrap()
18066            .insert("status:todo".into(), Some("cursor".into()));
18067        source
18068            .resolved_cache
18069            .lock()
18070            .unwrap()
18071            .insert(item.id.clone(), item);
18072        *source.fields_cache.lock().unwrap() = Some(BoardFields {
18073            id: BoardId::parse("PVT-board").unwrap(),
18074            fields: json!({"nodes": []}),
18075        });
18076        source
18077            .repository_cache
18078            .lock()
18079            .unwrap()
18080            .insert(RepositoryTarget::parse("acme/work").unwrap(), "R_1".into());
18081    }
18082
18083    fn assert_dropped(source: &GitHubProjectsSource) {
18084        assert!(source.created().unwrap().is_empty(), "created");
18085        assert!(source.updated().unwrap().is_empty(), "updated");
18086        assert!(source.board_cache().unwrap().is_none(), "board");
18087        assert!(source.search_cache.lock().unwrap().is_none(), "search");
18088        assert!(source.narrowed_cache.lock().unwrap().is_empty(), "narrowed");
18089        assert!(
18090            source.children_cache.lock().unwrap().is_empty(),
18091            "project children"
18092        );
18093        assert!(
18094            source.search_next.lock().unwrap().is_empty(),
18095            "search paging"
18096        );
18097        assert!(
18098            source.resolved_cache().unwrap().is_empty(),
18099            "resolved records"
18100        );
18101        assert!(source.fields_cache().unwrap().is_none(), "board fields");
18102        assert_eq!(
18103            source.repository_cache().unwrap().len(),
18104            1,
18105            "a repository's node id stays valid and is kept"
18106        );
18107    }
18108
18109    fn end(source: &GitHubProjectsSource) {
18110        tokio::runtime::Builder::new_current_thread()
18111            .build()
18112            .unwrap()
18113            .block_on(source.end_command())
18114            .expect("the command ends");
18115    }
18116
18117    #[test]
18118    fn the_call_drops_every_item_search_and_board_read_and_keeps_repository_ids() {
18119        let source = source();
18120        fill(&source);
18121        end(&source);
18122        assert_dropped(&source);
18123    }
18124
18125    #[test]
18126    fn the_call_clears_a_lock_an_earlier_failure_poisoned() {
18127        fn poison<T: Send>(held: &Mutex<T>) {
18128            std::thread::scope(|scope| {
18129                let _ = scope
18130                    .spawn(|| {
18131                        let _guard = held.lock().unwrap();
18132                        panic!("a failure while the lock is held");
18133                    })
18134                    .join();
18135            });
18136            assert!(held.is_poisoned());
18137        }
18138        let source = source();
18139        fill(&source);
18140        poison(&source.created);
18141        poison(&source.updated);
18142        poison(&source.board_cache);
18143        poison(&source.search_cache);
18144        poison(&source.narrowed_cache);
18145        poison(&source.search_next);
18146        poison(&source.resolved_cache);
18147        poison(&source.fields_cache);
18148        assert!(
18149            source.resolved_cache().is_err(),
18150            "a poisoned lock is refused before the call"
18151        );
18152        end(&source);
18153        assert_dropped(&source);
18154    }
18155}
18156
18157#[cfg(test)]
18158mod unprojectable_fields_tests {
18159    use super::*;
18160
18161    /// The field names `docs/metadata.md` says a `metadata_fields` entry may not name.
18162    fn documented() -> std::collections::BTreeSet<String> {
18163        let document = std::fs::read_to_string(
18164            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/metadata.md"),
18165        )
18166        .expect("docs/metadata.md is readable");
18167        let document = document.split_whitespace().collect::<Vec<_>>().join(" ");
18168        let lead = "a `field` equal, ignoring case, to ";
18169        let start = document.find(lead).expect("the refused-field sentence") + lead.len();
18170        let sentence = &document[start..];
18171        let sentence = &sentence[..sentence
18172            .find("; and two entries naming one field")
18173            .expect("the refused-field sentence ends at the duplicate rule")];
18174        let (own, github) = sentence
18175            .split_once(" or a field GitHub owns on every board (")
18176            .expect("the sentence names GitHub's own fields");
18177        own.split('`')
18178            .skip(1)
18179            .step_by(2)
18180            .chain(
18181                github
18182                    .strip_suffix(')')
18183                    .expect("GitHub's own fields close the sentence")
18184                    .split(", "),
18185            )
18186            .map(str::to_owned)
18187            .collect()
18188    }
18189
18190    /// `docs/metadata.md` states the text field's limit a caller is held to; it is this source's
18191    /// own constant, so the two cannot part.
18192    #[test]
18193    fn the_documented_text_field_limit_is_the_one_the_source_shortens_at() {
18194        let document = std::fs::read_to_string(
18195            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/metadata.md"),
18196        )
18197        .expect("docs/metadata.md is readable");
18198        let lead = "**A text field holds at most ";
18199        let start = document.find(lead).expect("the limit sentence") + lead.len();
18200        let stated = &document[start..start + document[start..].find(',').unwrap() + 4];
18201        assert_eq!(
18202            stated.replace(',', "").parse::<usize>().ok(),
18203            Some(TEXT_FIELD_LIMIT),
18204            "docs/metadata.md states {stated:?}"
18205        );
18206        assert!(document[start..].starts_with(&format!("{stated}, counted here in UTF-8 bytes.")));
18207    }
18208
18209    #[test]
18210    fn the_documented_refused_fields_are_exactly_the_ones_the_configuration_refuses() {
18211        let refused: std::collections::BTreeSet<String> = UNPROJECTABLE_FIELDS
18212            .iter()
18213            .map(|&name| name.to_owned())
18214            .collect();
18215        assert_eq!(documented(), refused, "the fields docs/metadata.md lists");
18216        let instance = SourceName::new("work").unwrap();
18217        for name in UNPROJECTABLE_FIELDS {
18218            for spelled in [name.to_owned(), name.to_uppercase()] {
18219                let entry = MetadataFieldConfig {
18220                    field: spelled.clone(),
18221                    key: "team.machine".to_owned(),
18222                    path: Vec::new(),
18223                };
18224                let refused = MetadataField::resolve(vec![entry], &instance)
18225                    .expect_err("an unprojectable field is refused");
18226                assert!(
18227                    refused.to_string().contains(&format!("{name:?}")),
18228                    "{spelled}: {refused}"
18229                );
18230            }
18231        }
18232    }
18233}