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 asked for on its first page,
760/// when every row carried the whole issue and was priced by it.
761///
762/// No longer what a batched find asks: a search slot now selects each hit's scalar fields
763/// alone, which GitHub prices as one connection whatever its page size, so a search asks its
764/// whole remaining limit — up to [`MAX_PAGE_SIZE`] — on every page.
765#[deprecated(
766    since = "0.18.0",
767    note = "a batched search slot asks its remaining limit, up to `MAX_PAGE_SIZE`, on every page"
768)]
769pub const SEARCH_BATCH_FIRST_PAGE: u32 = 3;
770
771/// The rows each resumed page of one [`graphql::SEARCH_BATCH`] round asked for, when `resumed`
772/// of its slots resumed from a cursor and every row carried the whole issue.
773///
774/// No longer what a batched find asks: with each hit's scalar fields alone, a round's price no
775/// longer grows with its rows, so its resumed pages no longer share one page of rows.
776#[deprecated(
777    since = "0.18.0",
778    note = "a batched search slot asks its remaining limit, up to `MAX_PAGE_SIZE`, on every page"
779)]
780#[must_use]
781pub fn search_batch_resumed_page(resumed: usize) -> u32 {
782    let resumed = u32::try_from(resumed.max(1)).unwrap_or(u32::MAX);
783    (SEARCH_PAGE_SIZE / resumed).max(1)
784}
785
786/// The page sizes of the most expensive [`graphql::SEARCH_BATCH`] round this source sends:
787/// every search and origin slot asking a whole page of [`MAX_PAGE_SIZE`] rows — what
788/// [`largest_page_sizes`] binds them to.
789///
790/// A search slot selects each hit's scalar fields alone, so asking every row a slot can is
791/// what the round costs at most; `tests/point_cost.rs` prices it, and the credentialed lane
792/// reconciles GitHub's own price of the document under it.
793#[must_use]
794pub fn search_batch_largest_round() -> Variables {
795    largest_page_sizes()
796}
797/// How many comments one [`graphql::ADD_COMMENTS`] request adds, and how many issue updates one
798/// [`graphql::WRITE_TASKS`] request carries: [`MUTATION_BATCH`], the most aliased mutations
799/// GitHub was seen to accept in one request.
800pub const COMMENT_BATCH: usize = MUTATION_BATCH;
801/// How many board field values one [`graphql::WRITE_TASKS`] request carries, beside
802/// [`MUTATION_BATCH`] field clears: [`WRITE_BATCH`].
803pub const TASK_FIELD_BATCH: usize = WRITE_BATCH;
804
805/// The most nodes any one document this source sends may be asked to return.
806///
807/// GitHub's own published per-query ceiling, taken from
808/// [`github_graphql_node_count::NODE_LIMIT`] rather than written out again here, so this
809/// workspace cannot hold a stale copy of somebody else's number. A query above it is
810/// **refused before it is executed**, whoever is asking and whatever board they are
811/// asking about — so this is a bound on the documents rather than a budget that runs out.
812///
813/// This is `nodeCount`, the maximum number of nodes *one query may return*. It is not
814/// `cost`, the rate-limit points a call spends against an hourly allowance shared by
815/// everything the credential does — two numbers against two limits, and this constant
816/// bounds only the first. The second is computed offline too, per document:
817/// [`worst_case_point_cost`], pinned for every document in [`graphql::DOCUMENTS`] by
818/// `tests/point_cost.rs`, and reconciled against GitHub's own `cost` by the credentialed
819/// lane. There is no constant like this one to hold a price under, because points are an
820/// hourly allowance rather than a per-call bound.
821///
822/// Neither is a session's price. What `session-cost.md` records of a whole session is its
823/// **requests** and its **worst-case nodes**; what a whole session spends in points is
824/// reported only by a credentialed run's own `x-ratelimit-*` headers, through
825/// [`accounting`]. The module section on the three ways this source reaches an item says how
826/// the count is arrived at, and which of the page sizes below decide it.
827pub const NODE_COUNT_LIMIT: u64 = github_graphql_node_count::NODE_LIMIT;
828
829/// Nested connection size for the connections that hang off one item.
830///
831/// It multiplies through every document that reaches an item under a page — the count
832/// rules multiply down a nested path — so it is the constant [`NODE_COUNT_LIMIT`] is most
833/// sensitive to. `tests/node_count.rs` is what holds the pair together: it recomputes
834/// every document under these constants and fails naming any that reaches the limit, so
835/// raising this is caught there rather than by GitHub.
836const NESTED_PAGE_SIZE: u32 = 50;
837/// How many of one issue's board memberships are read when an issue is reached directly.
838///
839/// An issue reached through a search or through its own node id carries its board half in
840/// `Issue.projectItems`, and only the entry for *this* board is read. This connection sits
841/// under a page of issues, so every point of it multiplies through the whole document and
842/// is paid for whether or not any issue is on a second board — which is why it is
843/// deliberately far smaller than [`NESTED_PAGE_SIZE`].
844///
845/// **Three, because what a page misses is now recovered rather than refused**, and the
846/// recovery is what the value is chosen against. An issue whose entry for this board sits
847/// past this page costs one further request — [`graphql::ISSUE_BOARD_ITEMS`], resumed from
848/// that page's own cursor — so the value trades a bound every read pays for a request only
849/// a multi-board issue pays. At one, a deployment whose issues commonly sit on two or more
850/// boards would pay that request *per issue*, which is order N against the one page per
851/// hundred issues a read costs today. At three it is only reached by an issue on four or
852/// more boards at once, which keeps the recovery path exceptional rather than routine for
853/// a plausible deployment.
854const BOARD_ITEMS_PAGE_SIZE: u32 = 3;
855/// How many carriers of one copy origin one page of [`graphql::ORIGIN_LOOKUP`] asks each of
856/// its two connections for.
857///
858/// An origin names one item, so the answer an origin lookup expects is one carrier, and a
859/// second is a duplicate a copy already takes the first of. Both connections are walked to
860/// exhaustion whatever this is, so it decides how many requests an unusual answer costs and
861/// never what the answer is. It is small because every point of it is paid on every lookup,
862/// and a copy makes one lookup per item it has no link for: at three, ten lookups cost fewer
863/// worst-case nodes than the one whole-board read they replaced.
864const ORIGIN_PAGE_SIZE: u32 = 3;
865/// How many carriers of each origin the batched [`graphql::ORIGIN_LOOKUPS`] asks each of its two
866/// connections for: one, the one carrier an origin names.
867///
868/// A second carrier still shows: the page then says there is more, and that origin is left to
869/// its own [`graphql::ORIGIN_LOOKUP`], which walks every page at `ORIGIN_PAGE_SIZE` — so a
870/// duplicate is found exactly as before, by the lookup that reads all of them. The feasibility
871/// spike (`board-copy-gaps-2026-10-24-spike-feasibility-report`) priced the batch of ten
872/// origins at two points with a first page of three and at one with a first page of one.
873const ORIGIN_LOOKUPS_PAGE_SIZE: u32 = 1;
874
875/// How many of one project's sub-issues one [`graphql::SUB_ISSUES`] page asks for: the most
876/// one point buys, since every row carries six connections GitHub charges for once per row.
877/// `session-cost.md` derives it; `tests/point_cost.rs` prices the document at one point and
878/// fails if one row more would still be priced at one.
879pub const MEMBER_PAGE_SIZE: u32 = 23;
880
881pub use github_graphql_node_count::{NodeCountError, Variables};
882
883/// The largest value this source can bind to each page-size variable its documents name.
884///
885/// Every `first:` in [`graphql`] reads one of these seven, and each is capped at the
886/// constant above it wherever a caller's own limit could reach it — `$first` at
887/// [`MAX_PAGE_SIZE`], `$commentFirst` at [`MAX_PAGE_SIZE`], `$nestedFirst` at `NESTED_PAGE_SIZE`, `$boardItems` at
888/// `BOARD_ITEMS_PAGE_SIZE`, `$originFirst` at `ORIGIN_PAGE_SIZE`, `$lookupFirst` at
889/// `ORIGIN_LOOKUPS_PAGE_SIZE`, `$memberFirst` at [`MEMBER_PAGE_SIZE`]. So this is the worst case a caller can drive this source to,
890/// not one configuration of it, which is what makes a bound computed under it a bound on
891/// every read.
892pub fn largest_page_sizes() -> Variables {
893    let mut sizes = Variables::from([
894        ("first".to_owned(), MAX_PAGE_SIZE),
895        ("commentFirst".to_owned(), MAX_PAGE_SIZE),
896        ("nestedFirst".to_owned(), NESTED_PAGE_SIZE),
897        ("boardItems".to_owned(), BOARD_ITEMS_PAGE_SIZE),
898        ("originFirst".to_owned(), ORIGIN_PAGE_SIZE),
899        ("lookupFirst".to_owned(), ORIGIN_LOOKUPS_PAGE_SIZE),
900        ("memberFirst".to_owned(), MEMBER_PAGE_SIZE),
901    ]);
902    // Each slot of the batched search pages at most a whole page of GitHub's.
903    for slot in 0..SEARCH_BATCH {
904        sizes.insert(format!("first{slot}"), MAX_PAGE_SIZE);
905    }
906    for slot in 0..SEARCH_BATCH_ORIGINS {
907        sizes.insert(format!("itemsFirst{slot}"), MAX_PAGE_SIZE);
908    }
909    sizes
910}
911
912/// The most nodes `document` could be asked to return, by GitHub's published rules.
913///
914/// Computed offline from the document's own text under [`largest_page_sizes`] — no
915/// network, no credential and no schema — by
916/// [`github_graphql_node_count::node_count`], which is where the rules themselves live.
917/// A document at or above [`NODE_COUNT_LIMIT`] is one GitHub refuses before executing, so
918/// this is what a check holds every document in [`graphql::DOCUMENTS`] below.
919///
920/// # Errors
921///
922/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
923/// no single operation, or binds a page size this source does not name — each of which is
924/// a defect in the document rather than a number.
925pub fn worst_case_node_count(document: &str) -> Result<u64, NodeCountError> {
926    node_count(document, &largest_page_sizes())
927}
928
929/// The most rate-limit points one call of `document` could spend, by GitHub's published
930/// rules.
931///
932/// Computed offline from the document's own text under [`largest_page_sizes`] — no
933/// network, no credential and no schema — by
934/// [`github_graphql_node_count::point_cost`], which is where the rules themselves live.
935/// This is `cost`, metered **per hour** against the allowance one credential shares across
936/// everything it does; it is not `nodeCount`, which is [`worst_case_node_count`] and is
937/// bounded per query by [`NODE_COUNT_LIMIT`]. There is no per-call ceiling to hold this
938/// under, so what `tests/point_cost.rs` does with it is pin every document in
939/// [`graphql::DOCUMENTS`] at what it costs, and the credentialed lane reconciles those
940/// figures against GitHub's own reported `cost`.
941///
942/// # Errors
943///
944/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
945/// no single operation, or binds a page size this source does not name — each of which is
946/// a defect in the document rather than a number.
947pub fn worst_case_point_cost(document: &str) -> Result<u64, NodeCountError> {
948    github_graphql_node_count::point_cost(document, &largest_page_sizes())
949}
950
951/// The rate-limit points one call of `document` spends under `variables`, by GitHub's published
952/// rules: [`worst_case_point_cost`] is this under [`largest_page_sizes`], and a request this
953/// source sent is priced by it under the page sizes that request really bound — what GitHub
954/// charges the request, since it charges every connection at the page size asked for.
955///
956/// # Errors
957///
958/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
959/// no single operation, or binds a page size `variables` does not name.
960pub fn point_cost(document: &str, variables: &Variables) -> Result<u64, NodeCountError> {
961    github_graphql_node_count::point_cost(document, variables)
962}
963
964/// The rate-limit points one request of `document` sending `variables` spends, by GitHub's
965/// published rules: [`point_cost`] under the page sizes those variables bind, each page-size
966/// variable they leave out at its largest — the price this source's accounting records a
967/// request at, and what a loopback board reports as a request's `rateLimit { cost }`.
968///
969/// # Errors
970///
971/// As [`point_cost`].
972pub fn request_point_cost(document: &str, variables: &Value) -> Result<u64, NodeCountError> {
973    let mut bindings = accounting::bindings(variables);
974    // A document spelled with assignees pages them by a variable it declares with its own
975    // default, which no request binds.
976    bindings
977        .entry("assigneeFirst".to_owned())
978        .or_insert_with(graphql::assignee_first);
979    point_cost(document, &bindings)
980}
981
982/// The most nodes `document` could be asked to return under `variables`.
983///
984/// [`worst_case_node_count`] is this under [`largest_page_sizes`], and the accounting in
985/// [`accounting`] is this under the bindings one request really sent — one spelling of the
986/// calculation, so a bound checked offline and a cost recorded at run time cannot come to
987/// disagree. The rules themselves live in [`github_graphql_node_count::node_count`].
988///
989/// # Errors
990///
991/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
992/// no single operation, or binds a page size `variables` does not name.
993pub fn node_count(document: &str, variables: &Variables) -> Result<u64, NodeCountError> {
994    github_graphql_node_count::node_count(document, variables)
995}
996
997/// `variables` with the page sizes and flags a token twin's inline issue selection binds,
998/// at a read's page sizes.
999fn token_variables(mut variables: Value) -> Value {
1000    if let Some(object) = variables.as_object_mut() {
1001        object.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
1002        object.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
1003        object.insert("duplicates".to_owned(), json!(true));
1004    }
1005    variables
1006}
1007
1008/// What a caller's request gate is told of one GraphQL request: it draws on GitHub's `graphql`
1009/// resource, it creates content exactly when it creates an issue or a comment,
1010/// and it costs what GitHub's published rules price it at under the page sizes it binds.
1011fn gated_graphql(document: &str, variables: &Value) -> onetaskgraph_plugin_api::GatedRequest {
1012    onetaskgraph_plugin_api::GatedRequest {
1013        resource: "graphql".to_owned(),
1014        content_creating: creates_content(document),
1015        cost_hint: point_cost(document, &accounting::bindings(variables)).ok(),
1016    }
1017}
1018
1019/// Whether `document` creates content GitHub's secondary limits meter as such: an issue or a
1020/// comment. `creates_content_tests` classifies every mutation root `graphql::DOCUMENTS` sends,
1021/// so a root added later fails there until it is said whether it creates content.
1022fn creates_content(document: &str) -> bool {
1023    is_mutation(document)
1024        && ["createIssue(", "addComment("]
1025            .iter()
1026            .any(|root| document.contains(root))
1027}
1028
1029#[cfg(test)]
1030mod creates_content_tests {
1031    use super::{creates_content, graphql};
1032    use std::collections::BTreeMap;
1033
1034    /// Every root field a mutation document selects at its top level, aliases resolved.
1035    fn roots(document: &str) -> Vec<String> {
1036        let body = &document[document.find('{').expect("a selection set") + 1..];
1037        let (mut braces, mut parens, mut roots) = (0_usize, 0_usize, Vec::new());
1038        let mut chars = body.char_indices().peekable();
1039        while let Some((at, c)) = chars.next() {
1040            match c {
1041                '{' => braces += 1,
1042                '}' if braces == 0 => break,
1043                '}' => braces -= 1,
1044                '(' => parens += 1,
1045                ')' => parens -= 1,
1046                // A directive's name is no field.
1047                '@' => {
1048                    while chars
1049                        .peek()
1050                        .is_some_and(|&(_, n)| n.is_ascii_alphanumeric() || n == '_')
1051                    {
1052                        chars.next();
1053                    }
1054                }
1055                c if braces == 0 && parens == 0 && (c.is_ascii_alphabetic() || c == '_') => {
1056                    let mut end = at + c.len_utf8();
1057                    while let Some(&(next, n)) = chars.peek() {
1058                        if !(n.is_ascii_alphanumeric() || n == '_') {
1059                            break;
1060                        }
1061                        end = next + n.len_utf8();
1062                        chars.next();
1063                    }
1064                    let rest = body[end..].trim_start();
1065                    // An alias names the root after its colon, which this loop reads next.
1066                    if !rest.starts_with(':') {
1067                        roots.push(body[at..end].to_owned());
1068                    }
1069                }
1070                _ => {}
1071            }
1072        }
1073        roots
1074    }
1075
1076    #[test]
1077    fn every_mutation_root_sent_is_classified_and_creates_content_agrees() {
1078        // Whether each root creates an issue or a comment: what GitHub's
1079        // secondary limits meter as content creation.
1080        let classified = BTreeMap::from([
1081            ("addBlockedBy", false),
1082            ("addComment", true),
1083            ("addProjectV2ItemById", false),
1084            ("addRelatesTo", false),
1085            ("addSubIssue", false),
1086            ("clearProjectV2ItemFieldValue", false),
1087            ("closeIssue", false),
1088            ("createIssue", true),
1089            ("createProjectV2Field", false),
1090            ("deleteIssue", false),
1091            ("deleteIssueComment", false),
1092            ("removeBlockedBy", false),
1093            ("removeRelatesTo", false),
1094            ("removeSubIssue", false),
1095            ("updateIssue", false),
1096            ("updateIssueComment", false),
1097            ("updateProjectV2DraftIssue", false),
1098            ("updateProjectV2Field", false),
1099            ("updateProjectV2ItemFieldValue", false),
1100        ]);
1101        let (mut seen, mut unclassified) = (BTreeMap::new(), std::collections::BTreeSet::new());
1102        for (document, _) in graphql::DOCUMENTS {
1103            if !super::is_mutation(document) {
1104                assert!(!creates_content(document), "a query: {document}");
1105                continue;
1106            }
1107            let roots = roots(document);
1108            assert!(!roots.is_empty(), "no root read: {document}");
1109            for root in &roots {
1110                match classified.get(root.as_str()) {
1111                    Some(&creates) => _ = seen.insert(root.clone(), creates),
1112                    None => _ = unclassified.insert(root.clone()),
1113                }
1114            }
1115            let expected = roots
1116                .iter()
1117                .any(|root| classified.get(root.as_str()) == Some(&true));
1118            assert_eq!(creates_content(document), expected, "{document}");
1119        }
1120        assert!(
1121            unclassified.is_empty(),
1122            "say whether each of these mutation roots creates content: {unclassified:?}"
1123        );
1124        let unsent: Vec<_> = classified
1125            .keys()
1126            .filter(|root| !seen.contains_key(**root))
1127            .collect();
1128        assert!(unsent.is_empty(), "classified but never sent: {unsent:?}");
1129    }
1130}
1131
1132/// The input members a mutation names the issue or board item it writes by.
1133const WRITTEN_NAMES: [&str; 4] = ["id", "issueId", "subjectId", "itemId"];
1134
1135tokio::task_local! {
1136    /// The source a targeted update is running on, by its address, while it runs: what has its
1137    /// mutations sent as the twins selecting the whole issue, so the update answers the version
1138    /// its own last response shows (see `GitHubProjectsSource::written_tokens`).
1139    static SPELLING: usize;
1140}
1141
1142/// The issue-title prefix that makes a board issue a document.
1143///
1144/// A GitHub Projects board has no document type — it holds issues — so the discriminator
1145/// is the title, and this is the whole of it: an issue whose title begins with these bytes
1146/// is a document and every other issue is the task or project the sub-issue rule makes it.
1147///
1148/// It is spelled **once**, here, and read rather than restated everywhere else — including
1149/// by the shared journeys, which take it from this constant so a board fixture cannot
1150/// drift from what this source reads. `docs/metadata.md` records the two consequences that
1151/// are not obvious from the bytes: the reported title has this prefix taken off, exactly
1152/// as the body's metadata slot is taken off `content`, and this prefix is read *before*
1153/// the sub-issue rule, so a design issue with no sub-issues is never an empty project.
1154pub const DESIGN_TITLE_PREFIX: &str = "DESIGN: ";
1155
1156/// The most characters GitHub stores in one issue's body: a longer one is refused as
1157/// `body is too long (maximum is 65536 characters)`.
1158pub const BODY_LIMIT: u64 = 65_536;
1159
1160/// The address a new upload's URL is spelled at, as GitHub serves a user attachment: what the
1161/// size of a body is measured with before an asset of it is uploaded, a UUID long.
1162const PREDICTED_ATTACHMENT_URL: &str =
1163    "https://github.com/user-attachments/assets/00000000-0000-0000-0000-000000000000";
1164
1165/// Exact GraphQL query documents issued by this plugin.
1166///
1167/// Keeping the production documents here lets the pinned-schema test validate the same
1168/// bytes that are sent to GitHub, rather than a test-only copy which could drift
1169/// independently. [`STATUS_OPTIONS_UPDATE`] is the sole document that may rewrite a board
1170/// field, and its guarded caller always supplies the complete existing option set with ids.
1171pub mod graphql {
1172    /// The board half of one item: the field values every document here reads it from.
1173    ///
1174    /// A macro for the same reason [`board_issue!`] below is one, a level further in. This
1175    /// selection is needed by that fragment, by [`BOARD`] under the board's own `items`,
1176    /// and by [`ISSUE_BOARD_ITEMS`] under a membership walk — and all three have to produce
1177    /// *the same value*, because
1178    /// [`GitHubProjectsSource::resolve`](super::GitHubProjectsSource) reads them through
1179    /// one path. Three spellings of it is what would drift, so there is one.
1180    ///
1181    /// The `Status` option and this source's own origin text field are the whole of it. It
1182    /// selects no `ProjectV2ItemFieldLabelValue`: GitHub derives that field from the item's
1183    /// content, so it holds nothing the content's own `labels` do not already say, and it
1184    /// would sit a label connection two page sizes deep.
1185    macro_rules! board_item_values {
1186        () => {
1187            r#"fieldValues(first:$nestedFirst){nodes{
1188          ... on ProjectV2ItemFieldSingleSelectValue{name field{
1189            ... on ProjectV2SingleSelectField{id name options{id name}}
1190          }}
1191          ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{id name}}}
1192        }pageInfo{hasNextPage}}"#
1193        };
1194    }
1195
1196    /// The variable every document reading an issue declares for the relationship events its
1197    /// change token counts, with its value as the default, so no caller binds it.
1198    ///
1199    /// A variable rather than a literal list because every argument a production document
1200    /// passes is a declared variable, which `tests/schema.rs` holds them to, and every member of
1201    /// its default to the pinned enum. Its default is the six event types GitHub records a
1202    /// relationship added or removed with: a dependency on either end, as `blockedBy` and
1203    /// `blocking`, so one a person makes from the far end moves this end's count too; and a
1204    /// project membership on the task, as its parent, which GitHub records there whichever
1205    /// issue the move was made from. A sub-issue's events on its parent are not counted: a
1206    /// project carries no task token, and a copy writes nothing of a task its own sub-issues
1207    /// decide. [`super::change_token`] says why the count is in the token.
1208    macro_rules! relationship_events_variable {
1209        () => {
1210            ",$relationshipEvents:[IssueTimelineItemsItemType!]=[BLOCKED_BY_ADDED_EVENT,BLOCKED_BY_REMOVED_EVENT,BLOCKING_ADDED_EVENT,BLOCKING_REMOVED_EVENT,PARENT_ISSUE_ADDED_EVENT,PARENT_ISSUE_REMOVED_EVENT]"
1211        };
1212    }
1213
1214    /// Everything this source reads about one issue, wherever it reaches that issue.
1215    ///
1216    /// A macro rather than a constant so the three documents below can `concat!` it: one
1217    /// spelling of these fields is what makes an issue read through the board-scoped
1218    /// search, through its own node id, and through its project's sub-issue relationship
1219    /// resolve to *the same* item, which is the whole of what
1220    /// [`GitHubProjectsSource::resolve_issue`](super::GitHubProjectsSource) relies on.
1221    ///
1222    /// `projectItems` is what carries the board half of an issue: the board item's own id
1223    /// and the [`board_item_values!`] above — the `Status` option and this source's origin
1224    /// text field — that a `ProjectV2.items` read used to carry. It is asked for on the
1225    /// issue rather than on the board, which is what makes the cost of a read proportional
1226    /// to what was asked for instead of to the board's size.
1227    ///
1228    /// It carries a *page* of that connection, at `BOARD_ITEMS_PAGE_SIZE`, and its
1229    /// `endCursor` is what [`ISSUE_BOARD_ITEMS`] resumes from when this board's entry is
1230    /// not on that page: a page here is where the search for the entry starts rather than
1231    /// where it ends.
1232    ///
1233    /// It does **not** select the board's `Labels` field value, and that is the whole of
1234    /// what keeps the three documents below under [`NODE_COUNT_LIMIT`](super::NODE_COUNT_LIMIT):
1235    /// a label connection there sits under `fieldValues` under `projectItems` under a page
1236    /// of issues, spending `$nestedFirst` twice down one path, and took
1237    /// [`SEARCH_ISSUES`] and [`SUB_ISSUES`] to 2,556,100 nodes against a limit of 500,000.
1238    /// No label is lost — this is a fragment `on Issue`, whose own `labels` are selected
1239    /// above, and that connection is where every label this source reports comes from. No
1240    /// document in this module selects the board field any longer, [`BOARD`] included; the
1241    /// module documentation records why nothing it could have held is lost.
1242    macro_rules! board_issue {
1243        () => {
1244            concat!(
1245                r#" fragment BoardIssue on Issue{"#,
1246                board_issue_fields!(),
1247                "}"
1248            )
1249        };
1250    }
1251
1252    /// What [`board_issue!`] selects of an issue, written out where a document selects it
1253    /// inline rather than through the fragment.
1254    macro_rules! board_issue_fields {
1255        () => {
1256            concat!(
1257                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}
1258      labels(first:$nestedFirst){nodes{id name color}pageInfo{hasNextPage}}
1259      projectItems(first:$boardItems){nodes{id updatedAt project{id number}
1260        "#,
1261                board_item_values!(),
1262                r#"}pageInfo{hasNextPage endCursor}}"#
1263            )
1264        };
1265    }
1266
1267    /// One page of a repository's issues, newest first, each with when it was created and its
1268    /// body: what a retried copy reads to find the issue its earlier attempt created, by the
1269    /// create key in that body's metadata slot — never through search, whose index lags.
1270    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}}}}";
1271    /// Every issue of one board, found by a search scoped to that board.
1272    ///
1273    /// This is how the projects a board holds are listed, and it selects no `items`
1274    /// connection on `ProjectV2`: the board is a *qualifier of the search* rather than a
1275    /// container walked page by page, so nothing nested inside a board item is paid for.
1276    /// Which of the issues it returns is a project is then read off `parent` — GitHub
1277    /// accepts `-has:parent` as a search qualifier and silently ignores it, so the
1278    /// discriminator has to be applied to the field, which is a scalar on the issue and
1279    /// costs nothing.
1280    pub const SEARCH_ISSUES: &str = concat!(
1281        r#"query($search:String!,$type:SearchType!,$first:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1282        relationship_events_variable!(),
1283        r#"){
1284      search(query:$search,type:$type,first:$first,after:$after){
1285        pageInfo{hasNextPage endCursor}
1286        nodes{__typename ...BoardIssue}
1287      }
1288    }"#,
1289        board_issue!()
1290    );
1291
1292    /// What a dependency read selects of each far end: enough to say which kind of item it
1293    /// is, its body included for the kind marker.
1294    macro_rules! related_issue {
1295        () => {
1296            " fragment Related on Issue{id title body parent{id} subIssuesSummary{total}}"
1297        };
1298    }
1299
1300    /// One issue by its own node id, which is what a qualified id names here — with what a
1301    /// write of it needs and the issue does not carry in `board_issue!`: the field
1302    /// definitions of the boards it sits on, and the far ends of its `blockedBy`.
1303    ///
1304    /// Strongly consistent, unlike the search above: GitHub's issue search is an index and
1305    /// answers a write made moments ago with the value from before it, and resolving a node
1306    /// id does not.
1307    ///
1308    /// **Why those two ride here and not on the fragment.** A copy or an update of an item
1309    /// reads it by its own id, and with them that one read answers everything the write
1310    /// needs: which option ids the board's `Status` and `Priority` fields hold — so no
1311    /// [`BOARD_FIELDS`] — and which issues block it, with each one's kind — so no
1312    /// [`ISSUE_DEPENDENCIES`]. On `board_issue!` they would sit under the hundred-issue
1313    /// pages of [`SEARCH_ISSUES`] and [`SUB_ISSUES`], multiplying both documents' price. Here
1314    /// they sit under one item, and this read is still one point.
1315    pub const ISSUE: &str = concat!(
1316        r#"query($id:ID!,$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1317        relationship_events_variable!(),
1318        r#"){
1319      node(id:$id){__typename ...BoardIssue ... on Issue{
1320        boards:projectItems(first:$boardItems){nodes{project{id number fields(first:$nestedFirst){nodes{
1321          ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1322          ... on ProjectV2Field{__typename id name dataType}
1323        }pageInfo{hasNextPage}}}}}
1324        blockedBy(first:$first){nodes{...Related}pageInfo{hasNextPage endCursor}}
1325      }}
1326    }"#,
1327        board_issue!(),
1328        related_issue!()
1329    );
1330
1331    /// One document by its own node id, as [`ISSUE`] reads one, with the project it is filed
1332    /// under and that project's members beside it: the project issue whole, and a page of its
1333    /// sub-issues, each as [`SUB_ISSUES`] carries one but with no page of what blocks it.
1334    ///
1335    /// What a guarded write of a document's metadata reads, and what reading a document by its
1336    /// id is: a write to a board the boundary screens is held to who may read the document,
1337    /// which is the project's and every member's classification as much as its own, and here
1338    /// the one request that holds the version the write is compared against answers all of it.
1339    /// Its members carry no edges, which nothing classifying them reads.
1340    pub const DOCUMENT_IN_PROJECT: &str = concat!(
1341        r#"query($id:ID!,$first:Int!,$memberFirst:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1342        relationship_events_variable!(),
1343        r#"){
1344      node(id:$id){__typename ...BoardIssue ... on Issue{
1345        boards:projectItems(first:$boardItems){nodes{project{id number fields(first:$nestedFirst){nodes{
1346          ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1347          ... on ProjectV2Field{__typename id name dataType}
1348        }pageInfo{hasNextPage}}}}}
1349        blockedBy(first:$first){nodes{...Related}pageInfo{hasNextPage endCursor}}
1350        project:parent{__typename ...BoardIssue
1351          subIssues(first:$memberFirst){pageInfo{hasNextPage endCursor} nodes{__typename ...BoardIssue}}
1352        }
1353      }}
1354    }"#,
1355        board_issue!(),
1356        related_issue!()
1357    );
1358
1359    /// One project's tasks: the sub-issues of the issue that project is, each with a page of
1360    /// what blocks it.
1361    ///
1362    /// Paged at `$memberFirst` — [`MEMBER_PAGE_SIZE`](super::MEMBER_PAGE_SIZE), the most rows
1363    /// one point buys — rather than at `$first`, because every row carries six connections and
1364    /// a hundred-row page cost six points to list a project of ten.
1365    ///
1366    /// The work this costs is the project's own size. Nothing about it grows as the board
1367    /// gains projects, or as those projects gain tasks.
1368    ///
1369    /// **Why `blockedBy` rides here and on no other page of issues.** What reads a project's
1370    /// tasks reads their edges next — `project graph` draws them, a copy carries them — and
1371    /// without them here that is one [`ISSUE_DEPENDENCIES`] per task, so the requests a graph
1372    /// costs grow with its tasks rather than with the pages of them. Carried here, a task
1373    /// blocked by no more than `$nestedFirst` issues answers its forward edges from this read,
1374    /// exactly as an [`ISSUE`] read of it does, and only one blocked by more is asked again.
1375    /// It adds a connection under each issue of the page — one rate-limit point per page,
1376    /// and `$nestedFirst` nodes per issue — and is kept off [`SEARCH_ISSUES`], whose pages
1377    /// answer questions that never read an edge.
1378    ///
1379    /// **The project issue itself rides here too**, with the page of what blocks it, because
1380    /// the reader of a project's tasks reads the project next: a copy writing the project reads
1381    /// it and its edges before it writes them. Carried on the request that already names the
1382    /// project, the first page answers that read and the dependency read after it, at the
1383    /// state GitHub answered in this command, rather than spending one more read on an item
1384    /// the cache's token cannot vouch for whole. Each sub-issue is kept the same way, so a
1385    /// copy's read of a task this listing carried is answered by it rather than sent again.
1386    /// Only a copy's read-before-write takes them; every other read by id reads GitHub.
1387    pub const SUB_ISSUES: &str = concat!(
1388        r#"query($id:ID!,$memberFirst:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1389        relationship_events_variable!(),
1390        r#"){
1391      node(id:$id){__typename ...BoardIssue
1392        ... on Issue{blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}
1393          subIssues(first:$memberFirst,after:$after){
1394          pageInfo{hasNextPage endCursor}
1395          nodes{__typename ...BoardIssue ... on Issue{
1396            blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}
1397          }}
1398        }}}
1399    }"#,
1400        board_issue!(),
1401        related_issue!()
1402    );
1403
1404    /// Everything this source reads about one issue comment, wherever it reaches one.
1405    ///
1406    /// A macro for the reason [`board_issue!`] is one: a comment listed, a comment just added
1407    /// and a comment just edited are handed to one mapper, so they are selected by one
1408    /// spelling. `author` is `Actor`, which GitHub answers `null` for an account that no
1409    /// longer exists, and `login` is the one member every kind of actor carries; `__typename`
1410    /// says whether it is a `Bot`, whose `login` GitHub's own pages spell with `[bot]` after it.
1411    macro_rules! issue_comment {
1412        () => {
1413            "id author{__typename login} createdAt updatedAt body url"
1414        };
1415    }
1416
1417    /// What a read of the board's own `items` selects of each item's content.
1418    ///
1419    /// A macro for the reason [`board_item_values!`] is one: [`BOARD`] and [`ORIGIN_LOOKUP`]
1420    /// both walk `ProjectV2.items` and hand each item to one resolver, so they select its
1421    /// content by one spelling.
1422    macro_rules! board_item_content {
1423        () => { board_item_content!("") };
1424        ($comments:expr) => {
1425            concat!(r#" content{
1426        ... 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#"}
1427        ... on PullRequest{__typename id}
1428        ... on DraftIssue{__typename id title body createdAt updatedAt}
1429      }"#)
1430        };
1431    }
1432
1433    macro_rules! board_listing {
1434        ($variables:expr, $comments:expr) => { concat!(
1435        r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$nestedFirst:Int!,$duplicates:Boolean!"#,
1436        relationship_events_variable!(), $variables,
1437        r#"){
1438      owner:repositoryOwner(login:$owner){
1439        ... on ProjectV2Owner{projectV2(number:$number){...Board}}
1440      }
1441    } fragment Board on ProjectV2 { id title
1442      fields(first:$nestedFirst){nodes{
1443        ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1444        ... on ProjectV2Field{__typename id name dataType}
1445      }pageInfo{hasNextPage}}
1446      items(first:$first,after:$after){nodes{id updatedAt "#,
1447        board_item_values!(),
1448        board_item_content!($comments),
1449        r#"} pageInfo{hasNextPage endCursor}}
1450    }"#
1451    ) };
1452    }
1453
1454    /// Reads the board's fields and one page of its items.
1455    pub const BOARD: &str = board_listing!("", "");
1456
1457    /// A board page carrying each issue's first comment page in the same request.
1458    pub const BOARD_WITH_COMMENTS: &str = concat!(
1459        board_listing!(
1460            ",$commentFirst:Int!",
1461            concat!(
1462                "comments(first:$commentFirst){nodes{",
1463                issue_comment!(),
1464                "}pageInfo{hasNextPage endCursor}} blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}"
1465            )
1466        ),
1467        related_issue!()
1468    );
1469
1470    /// Every carrier of one copy origin, by two reads in one request, and nothing else of
1471    /// the board.
1472    ///
1473    /// **`originItems`** is the board's own items narrowed by its own field filter —
1474    /// `ProjectV2.items(query:)`, which GitHub's schema declares as "Search query for
1475    /// filtering items" — to those whose `onetaskgraph.origin` text field holds the
1476    /// qualified id, quoted. It reads the field every carrier already holds, whichever release
1477    /// wrote it, and matches it exactly: measured on 2026-09-29 against a 394-item board,
1478    /// the quoted, the unquoted and the bare-value spellings each returned exactly the one
1479    /// carrier and a prefix of the value returned none. It is `ProjectV2.items`, so it lags a
1480    /// fresh `addProjectV2ItemById` the way that connection does.
1481    ///
1482    /// **`search`** is the board-scoped issue search for the same id as a quoted phrase in
1483    /// the body, which is where this source mirrors the origin into its metadata slot. GitHub
1484    /// indexes that comment, and the index catches up with a write in a second or two rather
1485    /// than in minutes, so it finds a carrier another process wrote that the first read is
1486    /// still behind on.
1487    ///
1488    /// Each connection pages at `$originFirst`, its own small size — see `ORIGIN_PAGE_SIZE`
1489    /// — and resumes from its own cursor; a connection already walked to its end is resumed
1490    /// from its last cursor, which answers an empty page. Every candidate either read returns
1491    /// is confirmed against its own origin field before it is reported, so a token match of
1492    /// the search or anything else the filter admits never is.
1493    ///
1494    /// The root is aliased `originItems` rather than `owner`, so nothing counting the board's
1495    /// own whole reads counts this one among them.
1496    pub const ORIGIN_LOOKUP: &str = concat!(
1497        r#"query($owner:String!,$number:Int!,$filter:String!,$search:String!,$type:SearchType!,$originFirst:Int!,$itemsAfter:String,$searchAfter:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1498        relationship_events_variable!(),
1499        r#"){
1500      originItems:repositoryOwner(login:$owner){
1501        ... on ProjectV2Owner{projectV2(number:$number){
1502          items(first:$originFirst,after:$itemsAfter,query:$filter){nodes{id updatedAt "#,
1503        board_item_values!(),
1504        board_item_content!(),
1505        r#"} pageInfo{hasNextPage endCursor}}
1506        }}
1507      }
1508      search(query:$search,type:$type,first:$originFirst,after:$searchAfter){
1509        pageInfo{hasNextPage endCursor}
1510        nodes{__typename ...BoardIssue}
1511      }
1512    }"#,
1513        board_issue!()
1514    );
1515
1516    /// Every closed item of the board, by the board's own field filter — what
1517    /// `task status reconcile` reads, and nothing else of the board.
1518    ///
1519    /// **`ProjectV2.items(query:)` narrowed by `$filter`**, which this source binds to
1520    /// `is:closed` alone, so a board whose open items are most of it is not read whole to find
1521    /// the closed ones. It is narrowed rather than trusted: every item it answers is confirmed
1522    /// closed, with a reason and a card that contradict each other, from the item node it
1523    /// already carries, so a filter that also let open items through would cost reads and
1524    /// write nothing wrong.
1525    ///
1526    /// The board's own id and field definitions ride along, as [`BOARD`] carries them, so the
1527    /// option writes that follow need no read of the board. The root is aliased `closedItems`
1528    /// rather than `owner`, so nothing counting the board's own whole reads counts this one
1529    /// among them.
1530    pub const CLOSED_ITEMS: &str = concat!(
1531        r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$filter:String!,$nestedFirst:Int!,$duplicates:Boolean!"#,
1532        relationship_events_variable!(),
1533        r#"){
1534      closedItems:repositoryOwner(login:$owner){
1535        ... on ProjectV2Owner{projectV2(number:$number){id
1536          fields(first:$nestedFirst){nodes{
1537            ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1538            ... on ProjectV2Field{__typename id name dataType}
1539          }pageInfo{hasNextPage}}
1540          items(first:$first,after:$after,query:$filter){nodes{id updatedAt "#,
1541        board_item_values!(),
1542        board_item_content!(),
1543        r#"} pageInfo{hasNextPage endCursor}}
1544        }}
1545      }
1546    }"#
1547    );
1548
1549    /// Every open item of the board, drafts included, by the board's own field filter — what a
1550    /// task listing whose every status category is open reads, and nothing else of the board.
1551    ///
1552    /// **`ProjectV2.items(query:)` narrowed by `$filter`**, which this source binds to
1553    /// `is:open` alone. GitHub's filter reads the issue's state, not its card, so it answers
1554    /// every open issue whatever column its card sits in — an open issue under a terminal card,
1555    /// and one under an option no mapping names, among them — and every draft, which has no
1556    /// state and is never closed; measured on the real board by `spike-store-defects`, it read
1557    /// 466 open items in five requests where the whole board's walk and its issue search took
1558    /// thirty-one. Each item's category is still confirmed in process from its own node, so a
1559    /// filter that let a closed item through would cost a read and keep nothing it should not.
1560    ///
1561    /// The board's own id and field definitions ride along, as [`CLOSED_ITEMS`] carries them,
1562    /// so a status write after it needs no read of the board's fields. The root is aliased
1563    /// `openItems`, so nothing counting the board's whole reads counts this one among them.
1564    pub const OPEN_ITEMS: &str = concat!(
1565        r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$filter:String!,$nestedFirst:Int!,$duplicates:Boolean!"#,
1566        relationship_events_variable!(),
1567        r#"){
1568      openItems:repositoryOwner(login:$owner){
1569        ... on ProjectV2Owner{projectV2(number:$number){id
1570          fields(first:$nestedFirst){nodes{
1571            ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1572            ... on ProjectV2Field{__typename id name dataType}
1573          }pageInfo{hasNextPage}}
1574          items(first:$first,after:$after,query:$filter){nodes{id updatedAt "#,
1575        board_item_values!(),
1576        board_item_content!(),
1577        r#"} pageInfo{hasNextPage endCursor}}
1578        }}
1579      }
1580    }"#
1581    );
1582
1583    /// One alias of [`ISSUES_BY_REFERENCE`]: the issue `$owner<n>/$name<n>#$number<n>` names.
1584    macro_rules! reference_alias {
1585        ($n:literal) => {
1586            concat!(
1587                "\n      r",
1588                stringify!($n),
1589                ":repository(owner:$owner",
1590                stringify!($n),
1591                ",name:$name",
1592                stringify!($n),
1593                "){issue(number:$number",
1594                stringify!($n),
1595                "){...HeldIssue}}"
1596            )
1597        };
1598    }
1599
1600    /// [`REFERENCE_BATCH`](super::REFERENCE_BATCH) issues at once, each by its repository and
1601    /// number — the one read `task status complete` makes of a source, and nothing else of
1602    /// the board: no `items`, no search and no project read.
1603    ///
1604    /// **Its own fragment, lighter than `board_issue!`, and that is what makes fifty
1605    /// references one point.** It selects no labels, and of each board membership only the
1606    /// `Status` value, by name, with `fieldValueByName` — so each alias asks GitHub for one
1607    /// connection, its page of memberships, where the whole fragment asks for five. What a
1608    /// completion writes is a card and, at most, the issue's state, so the labels and the other
1609    /// field values it leaves out are never what it needs; an item read this way is held for
1610    /// that write alone and never answers another read. An issue whose entry for this board is
1611    /// past its first page of memberships is walked with [`ISSUE_BOARD_ITEMS`], exactly as
1612    /// every other read of an issue recovers one.
1613    ///
1614    /// Fixed-size, as [`ISSUE_DETAILS`] is, so there is one document to price: a batch of
1615    /// fewer references binds the slots it has none for to its last one.
1616    pub const ISSUES_BY_REFERENCE: &str = concat!(
1617        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!"#,
1618        relationship_events_variable!(),
1619        r#"){"#,
1620        reference_alias!(0),
1621        reference_alias!(1),
1622        reference_alias!(2),
1623        reference_alias!(3),
1624        reference_alias!(4),
1625        reference_alias!(5),
1626        reference_alias!(6),
1627        reference_alias!(7),
1628        reference_alias!(8),
1629        reference_alias!(9),
1630        reference_alias!(10),
1631        reference_alias!(11),
1632        reference_alias!(12),
1633        reference_alias!(13),
1634        reference_alias!(14),
1635        reference_alias!(15),
1636        reference_alias!(16),
1637        reference_alias!(17),
1638        reference_alias!(18),
1639        reference_alias!(19),
1640        reference_alias!(20),
1641        reference_alias!(21),
1642        reference_alias!(22),
1643        reference_alias!(23),
1644        reference_alias!(24),
1645        reference_alias!(25),
1646        reference_alias!(26),
1647        reference_alias!(27),
1648        reference_alias!(28),
1649        reference_alias!(29),
1650        reference_alias!(30),
1651        reference_alias!(31),
1652        reference_alias!(32),
1653        reference_alias!(33),
1654        reference_alias!(34),
1655        reference_alias!(35),
1656        reference_alias!(36),
1657        reference_alias!(37),
1658        reference_alias!(38),
1659        reference_alias!(39),
1660        reference_alias!(40),
1661        reference_alias!(41),
1662        reference_alias!(42),
1663        reference_alias!(43),
1664        reference_alias!(44),
1665        reference_alias!(45),
1666        reference_alias!(46),
1667        reference_alias!(47),
1668        reference_alias!(48),
1669        reference_alias!(49),
1670        "\n    }",
1671        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}
1672      projectItems(first:$boardItems){nodes{id updatedAt project{id number}
1673        status:fieldValueByName(name:$statusField){... on ProjectV2ItemFieldSingleSelectValue{name field{
1674          ... on ProjectV2SingleSelectField{id name options{id name}}
1675        }}}
1676      }pageInfo{hasNextPage endCursor}}}"#
1677    );
1678
1679    /// The board's own id and field definitions, and not one of its items.
1680    ///
1681    /// What a write needs of the board when the item it writes does not say: the id a field
1682    /// write and `addProjectV2ItemById` address, and the definitions of the `Status` and
1683    /// origin fields. It selects no `items`, so what it costs is the board's field list
1684    /// however many items the board holds — and it decides nothing about which items those
1685    /// are, which is the question a read of one item by its own id answers instead.
1686    ///
1687    /// The root is aliased `boardFields` rather than `owner`, so nothing counting the
1688    /// board's item reads by their root counts this one among them.
1689    pub const BOARD_FIELDS: &str = r#"query($owner:String!,$number:Int!,$nestedFirst:Int!){
1690      boardFields:repositoryOwner(login:$owner){
1691        ... on ProjectV2Owner{projectV2(number:$number){id
1692          fields(first:$nestedFirst){nodes{
1693            ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1694            ... on ProjectV2Field{__typename id name dataType}
1695          }pageInfo{hasNextPage}}
1696        }}
1697      }
1698    }"#;
1699
1700    /// One board draft by its own node id, with the board item it sits in.
1701    ///
1702    /// A draft is not an issue, so [`ISSUE`] reaches it and reads nothing of it; this is the
1703    /// second read that answers it. `DraftIssue.projectV2Items` names the board item a draft
1704    /// is — GitHub links a draft to one item — with the same [`board_item_values!`] the
1705    /// issue fragment reads, so a draft reached by id resolves through the same resolver a
1706    /// board listing hands it to, and nothing has to list the board to find one.
1707    pub const DRAFT: &str = concat!(
1708        r#"query($id:ID!,$nestedFirst:Int!,$boardItems:Int!){
1709      node(id:$id){__typename ... on DraftIssue{id title body createdAt updatedAt
1710        projectV2Items(first:$boardItems){nodes{id project{id number}
1711        "#,
1712        board_item_values!(),
1713        r#"}pageInfo{hasNextPage endCursor}}}}
1714    }"#
1715    );
1716
1717    /// One issue's board memberships alone, walked past the page a read of it carried.
1718    ///
1719    /// The recovery read behind [`GitHubProjectsSource::resolve_issue`](super::GitHubProjectsSource):
1720    /// every document above carries a *page* of `Issue.projectItems`, and an issue on more
1721    /// boards than that page holds may have this board's entry past its end. This asks that
1722    /// one issue for its memberships and nothing else — the caller already holds the issue —
1723    /// so an answer of "this board does not hold it" is only ever given about a connection
1724    /// read to exhaustion.
1725    ///
1726    /// It selects the board item's id, its project number and the same
1727    /// [`board_item_values!`] the fragment does, because what it produces is handed to the
1728    /// very same resolver: an issue recovered this way reports the same title, the same
1729    /// status, the same labels and the same qualified id as one whose entry was on the
1730    /// page.
1731    ///
1732    /// `$first` rather than `$boardItems`: this document reads one issue, so nothing
1733    /// multiplies through it and the membership connection can be walked at
1734    /// [`MAX_PAGE_SIZE`](super::MAX_PAGE_SIZE) — which is what keeps the recovery to one
1735    /// further request for any issue a person really keeps.
1736    pub const ISSUE_BOARD_ITEMS: &str = concat!(
1737        r#"query($id:ID!,$first:Int!,$after:String,$nestedFirst:Int!){
1738      node(id:$id){
1739        ... on Issue{projectItems(first:$first,after:$after){
1740          nodes{id updatedAt project{id number}
1741        "#,
1742        board_item_values!(),
1743        r#"}
1744          pageInfo{hasNextPage endCursor}}}
1745      }
1746    }"#
1747    );
1748    /// Whether the board's Project is public — half of what decides whether a write here can
1749    /// be read by anybody. Needs the `read:project` scope.
1750    pub const PROJECT_VISIBILITY: &str = r#"query($owner:String!,$number:Int!){visibility:repositoryOwner(login:$owner){... on ProjectV2Owner{projectV2(number:$number){public}}}}"#;
1751    /// Resolves the configured repository's node id, which creating an issue requires.
1752    pub const REPOSITORY: &str = r#"query($owner:String!,$name:String!){repository(owner:$owner,name:$name){id nameWithOwner}}"#;
1753    /// What creating an issue needs and has not read yet: the board's own id and field
1754    /// definitions, as [`BOARD_FIELDS`] reads them, and the node id of the repository the
1755    /// issue is created in, as [`REPOSITORY`] reads it — in one request.
1756    ///
1757    /// Sent at the point a create knows which repository it is for, when neither half is
1758    /// already known to this process; a create needing only one of them sends that one's own
1759    /// document. Neither half is kept past the process: a field's option ids are re-minted by
1760    /// `sources fields --apply`, so a copy of them held between runs would write the wrong
1761    /// status.
1762    pub const CREATION_CONTEXT: &str = r#"query($owner:String!,$number:Int!,$nestedFirst:Int!,$repositoryOwner:String!,$repositoryName:String!){
1763      boardFields:repositoryOwner(login:$owner){
1764        ... on ProjectV2Owner{projectV2(number:$number){id
1765          fields(first:$nestedFirst){nodes{
1766            ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1767            ... on ProjectV2Field{__typename id name dataType}
1768          }pageInfo{hasNextPage}}
1769        }}
1770      }
1771      repository(owner:$repositoryOwner,name:$repositoryName){id nameWithOwner}
1772    }"#;
1773    /// Reads both dependency directions for one issue, with each far end's own kind — and
1774    /// the issue's own body, which is where an edge to another source is recorded, so that
1775    /// half of a dependency read needs no second read of the issue or of the board.
1776    pub const ISSUE_DEPENDENCIES: &str = concat!(
1777        r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename
1778      ... on Issue{body
1779        blockedBy(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1780        blocking(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1781      }}}"#,
1782        related_issue!()
1783    );
1784    /// What one item depends on: [`ISSUE_DEPENDENCIES`] narrowed to `blockedBy`, so a
1785    /// dependency read asks GitHub for the one direction it answers. The issue's `body` rides
1786    /// along because its metadata slot is where an edge to another source is recorded — and a
1787    /// board draft's `body` too, with the one board item GitHub links a draft to and, aliased
1788    /// `board`, this board's own id, so a draft's recorded edges are read off this same answer
1789    /// and only when that item is this board's: no draft read and no board read follow it.
1790    ///
1791    /// The draft's board item is asked for under a root of its own, aliased `draft`, rather
1792    /// than beside its `body` under `node`. GitHub counts the type-conditional fragments of
1793    /// one selection as the largest of them — `blockedBy`'s 100 alone, where this workspace's
1794    /// calculation adds the draft's 3 — while separate roots are summed by both, so this is
1795    /// the spelling whose node count GitHub and the calculation agree on. Both price it at
1796    /// one point; the credentialed lane's reconciliation is what holds the two to that.
1797    pub const ISSUE_DEPENDS_ON: &str = concat!(
1798        r#"query($id:ID!,$first:Int!,$after:String,$owner:String!,$number:Int!,$boardItems:Int!){
1799      node(id:$id){__typename
1800      ... on Issue{body
1801        blockedBy(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1802      }
1803      ... on DraftIssue{id body}}
1804      draft:node(id:$id){... on DraftIssue{projectV2Items(first:$boardItems){nodes{project{id number}}pageInfo{hasNextPage}}}}
1805      board:repositoryOwner(login:$owner){... on ProjectV2Owner{projectV2(number:$number){id}}}}"#,
1806        related_issue!()
1807    );
1808    /// What depends on one issue: [`ISSUE_DEPENDENCIES`] with its `blocking` alone. No `body`:
1809    /// the reverse of a recorded edge is derived from the far end, never written down here.
1810    pub const ISSUE_DEPENDED_ON_BY: &str = concat!(
1811        r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename
1812      ... on Issue{
1813        blocking(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1814      }}}"#,
1815        related_issue!()
1816    );
1817    /// Creates one issue. Outside a copy it is created on no board, and [`ADD_TO_BOARD`] files
1818    /// it; inside one, its input names the board in `projectV2Ids` and its project in
1819    /// `parentIssueId`, so this one request files it under both — see
1820    /// [`GitHubProjectsSource::create_filed_issue`](super::GitHubProjectsSource).
1821    pub const CREATE_ISSUE: &str =
1822        r#"mutation($input:CreateIssueInput!){createIssue(input:$input){issue{id number url}}}"#;
1823    /// Puts an existing issue on the configured board.
1824    pub const ADD_TO_BOARD: &str = r#"mutation($input:AddProjectV2ItemByIdInput!){addProjectV2ItemById(input:$input){item{id}}}"#;
1825    /// Updates an issue's visible fields and its open or closed state in one call.
1826    pub const UPDATE_ISSUE: &str =
1827        r#"mutation($input:UpdateIssueInput!){updateIssue(input:$input){issue{id}}}"#;
1828    /// Closes one issue for a reason, the survivor it is a duplicate of included — the one way
1829    /// GitHub records a duplicate's link: `updateIssue`'s `stateInput` carries no survivor, and
1830    /// the REST `state_reason=duplicate` is accepted and records none, both measured by
1831    /// `spike-store-defects`.
1832    pub const CLOSE_ISSUE: &str =
1833        r#"mutation($input:CloseIssueInput!){closeIssue(input:$input){issue{id}}}"#;
1834    /// Updates an existing draft's user-visible fields.
1835    pub const UPDATE_DRAFT: &str = r#"mutation($input:UpdateProjectV2DraftIssueInput!){updateProjectV2DraftIssue(input:$input){draftIssue{id}}}"#;
1836    /// Updates a text or single-select value on one project item.
1837    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}}}}}}}}"#;
1838    /// Writes up to six board fields and clears up to three in one ordered mutation: every
1839    /// aliased field is included by its own boolean, as [`FIELD_WRITE_SLOTS`](super::FIELD_WRITE_SLOTS)
1840    /// and [`FIELD_CLEAR_SLOTS`](super::FIELD_CLEAR_SLOTS) name them, writes before clears.
1841    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}}}"#;
1842    /// Clears one project item's value of one field, which is what a `none` priority is.
1843    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}}}}}}}}"#;
1844    /// Creates one field: a single-select one with its options, or a text one for a projected
1845    /// metadata value. Only the guarded field setup may use this document, and only for a
1846    /// field the board lacks.
1847    pub const CREATE_FIELD: &str = r#"mutation($input:CreateProjectV2FieldInput!){createProjectV2Field(input:$input){projectV2Field{... on ProjectV2SingleSelectField{id name options{id name color description}}}}}"#;
1848    /// Replaces a single-select field's options. Only the guarded field setup — the
1849    /// `status-options` and `fields` operations — may use this document, because GitHub
1850    /// treats the input as the complete option list.
1851    pub const STATUS_OPTIONS_UPDATE: &str = r#"mutation($input:UpdateProjectV2FieldInput!){updateProjectV2Field(input:$input){projectV2Field{... on ProjectV2SingleSelectField{id options{id name color description}}}}}"#;
1852    /// A fresh snapshot of the Status field and every board item's assignment.
1853    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}}}}}}"#;
1854    /// Files one issue under another as a sub-issue, which is what project membership is.
1855    pub const ADD_SUB_ISSUE: &str =
1856        r#"mutation($input:AddSubIssueInput!){addSubIssue(input:$input){issue{id} subIssue{id}}}"#;
1857    /// Takes one issue back out of its parent.
1858    pub const REMOVE_SUB_ISSUE: &str = r#"mutation($input:RemoveSubIssueInput!){removeSubIssue(input:$input){issue{id} subIssue{id}}}"#;
1859    /// Adds GitHub's native issue blocked-by relationship.
1860    pub const ADD_BLOCKED_BY: &str = r#"mutation($input:AddBlockedByInput!){addBlockedBy(input:$input){issue{id} blockingIssue{id}}}"#;
1861    /// One origin of [`ORIGIN_LOOKUPS`]: [`ORIGIN_LOOKUP`]'s two connections for the origin the
1862    /// `$filter<n>` and `$search<n>` of slot `<n>` name, sent only while `$ask<n>` holds.
1863    macro_rules! origin_lookup_alias {
1864        ($n:literal) => {
1865            concat!(
1866                "\n      o",
1867                stringify!($n),
1868                ":repositoryOwner(login:$owner) @include(if:$ask",
1869                stringify!($n),
1870                "){... on ProjectV2Owner{projectV2(number:$number){items(first:$lookupFirst,query:$filter",
1871                stringify!($n),
1872                "){nodes{id updatedAt ",
1873                board_item_values!(),
1874                board_item_content!(),
1875                "} pageInfo{hasNextPage endCursor}}}}}\n      s",
1876                stringify!($n),
1877                ":search(query:$search",
1878                stringify!($n),
1879                ",type:$type,first:$lookupFirst) @include(if:$ask",
1880                stringify!($n),
1881                "){pageInfo{hasNextPage endCursor} nodes{__typename ...BoardIssue}}"
1882            )
1883        };
1884    }
1885
1886    /// [`ORIGIN_LOOKUPS`], with `$extra_variables` declared after its own and `$extra_fields`
1887    /// selected beside them: one spelling of the batched lookup for the documents that send it.
1888    macro_rules! origin_lookups {
1889        ($extra_variables:literal, $extra_fields:literal) => {
1890            concat!(
1891                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!"#,
1892                relationship_events_variable!(),
1893                $extra_variables,
1894                r#"){
1895      boardFields:repositoryOwner(login:$owner){
1896        ... on ProjectV2Owner{projectV2(number:$number){id
1897          fields(first:$nestedFirst){nodes{
1898            ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1899            ... on ProjectV2Field{__typename id name dataType}
1900          }pageInfo{hasNextPage}}
1901        }}
1902      }
1903      repository(owner:$repositoryOwner,name:$repositoryName){id databaseId nameWithOwner}"#,
1904                $extra_fields,
1905                origin_lookup_alias!(0),
1906                origin_lookup_alias!(1),
1907                origin_lookup_alias!(2),
1908                origin_lookup_alias!(3),
1909                origin_lookup_alias!(4),
1910                origin_lookup_alias!(5),
1911                origin_lookup_alias!(6),
1912                origin_lookup_alias!(7),
1913                origin_lookup_alias!(8),
1914                origin_lookup_alias!(9),
1915                "\n    }",
1916                board_issue!()
1917            )
1918        };
1919    }
1920
1921    /// The first page of [`ORIGIN_LOOKUP`] for up to [`ORIGIN_BATCH`](super::ORIGIN_BATCH)
1922    /// origins a copy is about to look for, and everything creating an item then reads —
1923    /// the board's own id and field definitions, as [`CREATION_CONTEXT`] reads them, and the node
1924    /// id and the numeric id of the repository an issue is created in — in one request.
1925    ///
1926    /// What a copy reads before it writes anything, so that finding none of its records on the
1927    /// board and creating every one costs this read and the writes. An origin whose page says
1928    /// there is more is left to its own [`ORIGIN_LOOKUP`]. The repository's numeric id is what an
1929    /// image upload names, so a copy carrying assets needs no `GET /repos/{owner}/{repo}` either.
1930    pub const ORIGIN_LOOKUPS: &str = origin_lookups!("", "");
1931
1932    /// [`ORIGIN_LOOKUPS`], with a page of the members of the project `$project` beside it, each
1933    /// trimmed to what classifying it reads — its id, its parent, its body and its repository,
1934    /// and no connection under it.
1935    ///
1936    /// What a document copy sends where the public boundary screens its write: the document is
1937    /// held to who may read its project, which is its members' classification as much as the
1938    /// project's own, and this request carries both the project — among the origins it asks —
1939    /// and its members. GitHub's own dry run prices it at the one point [`ORIGIN_LOOKUPS`]
1940    /// costs alone (`docs/measurements/board-copy-gaps-2026-10-24/coalesced-members-dry-run`).
1941    pub const ORIGIN_LOOKUPS_WITH_MEMBERS: &str = origin_lookups!(
1942        ",$project:ID!,$memberFirst:Int!",
1943        "\n      members:node(id:$project){... on Issue{subIssues(first:$memberFirst){pageInfo{hasNextPage endCursor} nodes{id body parent{id} repository{nameWithOwner}}}}}"
1944    );
1945
1946    /// One slot `<n>` of a copy's aliased writes: `$<prefix><n>` is its input and `$send<n>`
1947    /// whether it is sent.
1948    macro_rules! write_slot {
1949        ($prefix:literal, $field:literal, $selection:literal, $n:literal) => {
1950            concat!(
1951                " ",
1952                $prefix,
1953                stringify!($n),
1954                ":",
1955                $field,
1956                "(input:$",
1957                $prefix,
1958                stringify!($n),
1959                ") @include(if:$send",
1960                stringify!($n),
1961                "){",
1962                $selection,
1963                "}"
1964            )
1965        };
1966    }
1967
1968    /// The variables of a copy's aliased writes: eleven inputs of `$type` named `$<prefix><n>`,
1969    /// and eleven `$send<n>`.
1970    macro_rules! write_variables {
1971        ($prefix:literal, $type:literal) => {
1972            concat!(
1973                "mutation(",
1974                "$",
1975                $prefix,
1976                "0:",
1977                $type,
1978                "!,$",
1979                $prefix,
1980                "1:",
1981                $type,
1982                "!,$",
1983                $prefix,
1984                "2:",
1985                $type,
1986                "!,$",
1987                $prefix,
1988                "3:",
1989                $type,
1990                "!,$",
1991                $prefix,
1992                "4:",
1993                $type,
1994                "!,$",
1995                $prefix,
1996                "5:",
1997                $type,
1998                "!,$",
1999                $prefix,
2000                "6:",
2001                $type,
2002                "!,$",
2003                $prefix,
2004                "7:",
2005                $type,
2006                "!,$",
2007                $prefix,
2008                "8:",
2009                $type,
2010                "!,$",
2011                $prefix,
2012                "9:",
2013                $type,
2014                "!,$",
2015                $prefix,
2016                "10:",
2017                $type,
2018                "!,",
2019                "$send0:Boolean!,$send1:Boolean!,$send2:Boolean!,$send3:Boolean!,$send4:Boolean!,",
2020                "$send5:Boolean!,$send6:Boolean!,$send7:Boolean!,$send8:Boolean!,$send9:Boolean!,",
2021                "$send10:Boolean!){"
2022            )
2023        };
2024    }
2025
2026    /// A copy's aliased writes of one kind: [`MUTATION_BATCH`](super::MUTATION_BATCH) slots of
2027    /// `$field`, each sent only while its `$send<n>` holds.
2028    macro_rules! write_batch {
2029        ($prefix:literal, $type:literal, $field:literal, $selection:literal) => {
2030            concat!(
2031                write_variables!($prefix, $type),
2032                write_slot!($prefix, $field, $selection, 0),
2033                write_slot!($prefix, $field, $selection, 1),
2034                write_slot!($prefix, $field, $selection, 2),
2035                write_slot!($prefix, $field, $selection, 3),
2036                write_slot!($prefix, $field, $selection, 4),
2037                write_slot!($prefix, $field, $selection, 5),
2038                write_slot!($prefix, $field, $selection, 6),
2039                write_slot!($prefix, $field, $selection, 7),
2040                write_slot!($prefix, $field, $selection, 8),
2041                write_slot!($prefix, $field, $selection, 9),
2042                write_slot!($prefix, $field, $selection, 10),
2043                "}"
2044            )
2045        };
2046    }
2047
2048    /// Creates up to [`MUTATION_BATCH`](super::MUTATION_BATCH) issues in one request, each filed on
2049    /// the board and under its project by the same `createIssue` — its `projectV2Ids` and
2050    /// `parentIssueId` — as [`CREATE_ISSUE`] creates one.
2051    pub const CREATE_ISSUES: &str = write_batch!(
2052        "create",
2053        "CreateIssueInput",
2054        "createIssue",
2055        "issue{id number url}"
2056    );
2057
2058    /// One issue of [`CREATED_BOARD_ITEMS`]: the board items the issue `$id<n>` names is on, with
2059    /// the `Status` value of each, read only while `$read<n>` holds.
2060    macro_rules! created_item_alias {
2061        ($n:literal) => {
2062            concat!(
2063                "\n      i",
2064                stringify!($n),
2065                ":node(id:$id",
2066                stringify!($n),
2067                ") @include(if:$read",
2068                stringify!($n),
2069                "){... on Issue{id projectItems(first:$boardItems){nodes{id project{id} status:fieldValueByName(name:$statusName){... on ProjectV2ItemFieldSingleSelectValue{name}}}}}}"
2070            )
2071        };
2072    }
2073
2074    /// The board item of each issue a copy created, up to
2075    /// [`COPY_DETAIL_BATCH`](super::COPY_DETAIL_BATCH) at a time, with its `Status` as the board
2076    /// set it: what `createIssue`'s `projectV2Ids` files the issue as, which GitHub adds after
2077    /// answering the create, so its id comes from a read made once every create has been sent.
2078    pub const CREATED_BOARD_ITEMS: &str = concat!(
2079        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!){"#,
2080        created_item_alias!(0),
2081        created_item_alias!(1),
2082        created_item_alias!(2),
2083        created_item_alias!(3),
2084        created_item_alias!(4),
2085        created_item_alias!(5),
2086        created_item_alias!(6),
2087        created_item_alias!(7),
2088        created_item_alias!(8),
2089        created_item_alias!(9),
2090        created_item_alias!(10),
2091        created_item_alias!(11),
2092        created_item_alias!(12),
2093        created_item_alias!(13),
2094        created_item_alias!(14),
2095        created_item_alias!(15),
2096        created_item_alias!(16),
2097        created_item_alias!(17),
2098        created_item_alias!(18),
2099        created_item_alias!(19),
2100        created_item_alias!(20),
2101        "\n    }"
2102    );
2103
2104    /// The variables and the aliases of [`WRITE_BATCH`](super::WRITE_BATCH) slots: `$<prefix><n>`
2105    /// is a slot's input and `$<send><n>` whether it is sent, for the slot numbers given.
2106    macro_rules! wide_variables {
2107        ($prefix:literal, $type:literal, $send:literal; $($n:literal)+) => {
2108            concat!($("$", $prefix, stringify!($n), ":", $type, "!,$", $send, stringify!($n), ":Boolean!,",)+)
2109        };
2110    }
2111    macro_rules! wide_slots {
2112        ($prefix:literal, $field:literal, $selection:literal, $send:literal; $($n:literal)+) => {
2113            concat!($(
2114                " ", $prefix, stringify!($n), ":", $field, "(input:$", $prefix, stringify!($n),
2115                ") @include(if:$", $send, stringify!($n), "){", $selection, "}",
2116            )+)
2117        };
2118    }
2119
2120    /// Up to [`WRITE_BATCH`](super::WRITE_BATCH) board field values a copy writes on the items it
2121    /// created, each on its own item, in one ordered request.
2122    pub const WRITE_FIELD_VALUES: &str = concat!(
2123        "mutation(",
2124        wide_variables!("field", "UpdateProjectV2ItemFieldValueInput", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2125        "){",
2126        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),
2127        "}"
2128    );
2129
2130    /// A copy's board field values and its blocked-by edges together, up to
2131    /// [`WRITE_BATCH`](super::WRITE_BATCH) of the two kinds between them, in one ordered request:
2132    /// every field value its `$sendField<n>` sends, then every edge its `$sendBlock<n>` sends.
2133    /// What a copy sends when one request of its writes holds both kinds; one holding a single
2134    /// kind is [`WRITE_FIELD_VALUES`] or [`ADD_BLOCKED_BYS`].
2135    pub const WRITE_FIELDS_AND_EDGES: &str = concat!(
2136        "mutation(",
2137        wide_variables!("field", "UpdateProjectV2ItemFieldValueInput", "sendField"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2138        wide_variables!("block", "AddBlockedByInput", "sendBlock"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2139        "){",
2140        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),
2141        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),
2142        "}"
2143    );
2144
2145    /// Closes up to [`MUTATION_BATCH`](super::MUTATION_BATCH) issues a copy created at a closing
2146    /// status, each with its own `stateInput` and nothing else, once its option is selected.
2147    pub const CLOSE_ISSUES: &str =
2148        write_batch!("close", "UpdateIssueInput", "updateIssue", "issue{id}");
2149
2150    /// Updates up to [`MUTATION_BATCH`](super::MUTATION_BATCH) existing issues a copy rewrites,
2151    /// each with the members its own [`UPDATE_ISSUE`] would have sent, in one request.
2152    pub const UPDATE_ISSUES: &str =
2153        write_batch!("update", "UpdateIssueInput", "updateIssue", "issue{id}");
2154
2155    /// Up to [`WRITE_BATCH`](super::WRITE_BATCH) native blocked-by relationships a copy adds to the
2156    /// issues it created, in one request.
2157    pub const ADD_BLOCKED_BYS: &str = concat!(
2158        "mutation(",
2159        wide_variables!("block", "AddBlockedByInput", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2160        "){",
2161        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),
2162        "}"
2163    );
2164
2165    /// Removes one native issue blocked-by relationship.
2166    pub const REMOVE_BLOCKED_BY: &str = r#"mutation($input:RemoveBlockedByInput!){removeBlockedBy(input:$input){issue{id} blockingIssue{id}}}"#;
2167    /// Deletes one issue, which takes its board item with it.
2168    ///
2169    /// The engine sends this in one situation only: undoing a copy that could not finish,
2170    /// over the items that same copy created. Deleting the issue removes the board item
2171    /// too, so there is no second `deleteProjectV2Item` to keep in step with it.
2172    pub const DELETE_ISSUE: &str =
2173        r#"mutation($input:DeleteIssueInput!){deleteIssue(input:$input){repository{id}}}"#;
2174    /// Deletes up to [`DELETE_BATCH`](super::DELETE_BATCH) issues in one request, each as
2175    /// [`DELETE_ISSUE`] deletes one: what a write that created several issues and was refused
2176    /// part way sends to take them back.
2177    pub const DELETE_ISSUES: &str = concat!(
2178        "mutation(",
2179        wide_variables!("delete", "DeleteIssueInput", "send"; 0 1 2 3 4),
2180        "){",
2181        wide_slots!("delete", "deleteIssue", "repository{id}", "send"; 0 1 2 3 4),
2182        "}"
2183    );
2184
2185    /// One task's comments: a page of its issue's own `comments` connection.
2186    ///
2187    /// **No `orderBy`, and that is what makes the page oldest first.** GitHub's only
2188    /// `IssueCommentOrder` field is `UPDATED_AT`, which would move a comment to the end of the
2189    /// list every time somebody edited it; left unordered the connection answers in the order
2190    /// the comments were written, which is the order GitHub documents for the same collection
2191    /// over REST — ascending id. Nothing multiplies through it, so `$first` is the whole of its
2192    /// node count and the caller's own page size is pushed straight down.
2193    pub const ISSUE_COMMENTS: &str = concat!(
2194        r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename ... on Issue{comments(first:$first,after:$after){nodes{"#,
2195        issue_comment!(),
2196        r#"}pageInfo{hasNextPage endCursor}}}}}"#
2197    );
2198    /// One issue by its own node id, with a page of its comments: what `task show` and a
2199    /// comment listing read, in one request.
2200    ///
2201    /// [`ISSUE`] and [`ISSUE_COMMENTS`] in one document, rather than one then the other. The
2202    /// comments are selected here and **not** on the shared `board_issue!` fragment, which
2203    /// [`SEARCH_ISSUES`] and [`SUB_ISSUES`] nest under a page of a hundred issues: a comment
2204    /// connection there would multiply through both of those documents' price, and neither
2205    /// needs one.
2206    pub const ISSUE_DETAIL: &str = concat!(
2207        r#"query($id:ID!,$first:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2208        relationship_events_variable!(),
2209        r#"){
2210      node(id:$id){__typename ...BoardIssue ... on Issue{comments(first:$first,after:$after){nodes{"#,
2211        issue_comment!(),
2212        r#"}pageInfo{hasNextPage endCursor}}}}
2213    }"#,
2214        board_issue!()
2215    );
2216
2217    /// One alias of [`ISSUE_DETAILS`]: the item a batch's `$id<n>` names, with the first
2218    /// page of its comments when `$comments` asks for them.
2219    macro_rules! issue_details_alias {
2220        ($n:literal) => {
2221            concat!(
2222                "\n      i",
2223                stringify!($n),
2224                ":node(id:$id",
2225                stringify!($n),
2226                "){__typename ...BoardIssue ... on Issue{comments(first:$first) @include(if:$comments){nodes{",
2227                issue_comment!(),
2228                "}pageInfo{hasNextPage endCursor}}}}"
2229            )
2230        };
2231    }
2232
2233    /// [`ISSUE_DETAIL`] for [`DETAIL_BATCH`](super::DETAIL_BATCH) items at once, each by its
2234    /// own node id, as one fixed-size document of aliased `node(id:)` fields.
2235    ///
2236    /// **Aliased `node(id:)` rather than `nodes(ids:)`, and that is what keeps its price
2237    /// honest.** The `github-graphql-node-count` model this workspace prices with treats a
2238    /// field that supplies neither `first` nor `last` as free, and `nodes(ids:)` supplies
2239    /// neither — so every connection under it would be priced at nothing and the pin in
2240    /// `tests/point_cost.rs` would understate what GitHub charges. Each alias here is the
2241    /// one-item read the model already prices, so the batch costs what its aliases cost.
2242    ///
2243    /// **Fixed-size, so there is one document to price.** A batch of fewer items binds the
2244    /// slots it has no item for to the last item it does, and reads that item again; the
2245    /// price is the document's, whatever its variables, so a short batch costs what a full
2246    /// one does and nothing more.
2247    pub const ISSUE_DETAILS: &str = concat!(
2248        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!"#,
2249        relationship_events_variable!(),
2250        r#"){"#,
2251        issue_details_alias!(0),
2252        issue_details_alias!(1),
2253        issue_details_alias!(2),
2254        issue_details_alias!(3),
2255        issue_details_alias!(4),
2256        issue_details_alias!(5),
2257        issue_details_alias!(6),
2258        issue_details_alias!(7),
2259        issue_details_alias!(8),
2260        issue_details_alias!(9),
2261        issue_details_alias!(10),
2262        issue_details_alias!(11),
2263        issue_details_alias!(12),
2264        issue_details_alias!(13),
2265        issue_details_alias!(14),
2266        issue_details_alias!(15),
2267        issue_details_alias!(16),
2268        issue_details_alias!(17),
2269        issue_details_alias!(18),
2270        issue_details_alias!(19),
2271        issue_details_alias!(20),
2272        issue_details_alias!(21),
2273        issue_details_alias!(22),
2274        issue_details_alias!(23),
2275        "\n    }",
2276        board_issue!()
2277    );
2278
2279    /// One alias of [`ISSUE_COPY_DETAILS`]: the item a batch's `$id<n>` names, with the first
2280    /// page of its comments and the issues it is blocked by.
2281    macro_rules! issue_copy_details_alias {
2282        ($n:literal) => {
2283            concat!(
2284                "\n      i",
2285                stringify!($n),
2286                ":node(id:$id",
2287                stringify!($n),
2288                "){__typename ...BoardIssue ... on Issue{comments(first:$first){nodes{",
2289                issue_comment!(),
2290                "}pageInfo{hasNextPage endCursor}} blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}}}"
2291            )
2292        };
2293    }
2294
2295    /// [`ISSUE_DETAILS`] as a copy reads the tasks it carries: each item with the first page of
2296    /// its comments and its `blockedBy` — the edges a copy reads of every task next, which
2297    /// [`ISSUE`] carries and [`ISSUE_DETAILS`] does not — [`COPY_DETAIL_BATCH`](super::COPY_DETAIL_BATCH)
2298    /// at a time, so a copy of a changed task costs this read and nothing else.
2299    ///
2300    /// A document of its own rather than a widening of [`ISSUE_DETAILS`], whose batch size is
2301    /// what `task show-many` is priced by and which reads no edge.
2302    ///
2303    /// `children`, read only while `$children` holds, is which issues the issue `$project` has
2304    /// as sub-issues — each one's id and title, the page `$nestedFirst` allows — so that a
2305    /// project copy, which reads its project and every task at once, knows from this same read
2306    /// which tasks the project holds at the destination, and its orphan check is answered by it
2307    /// rather than by a listing of the project.
2308    pub const ISSUE_COPY_DETAILS: &str = concat!(
2309        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!"#,
2310        relationship_events_variable!(),
2311        r#"){"#,
2312        issue_copy_details_alias!(0),
2313        issue_copy_details_alias!(1),
2314        issue_copy_details_alias!(2),
2315        issue_copy_details_alias!(3),
2316        issue_copy_details_alias!(4),
2317        issue_copy_details_alias!(5),
2318        issue_copy_details_alias!(6),
2319        issue_copy_details_alias!(7),
2320        issue_copy_details_alias!(8),
2321        issue_copy_details_alias!(9),
2322        issue_copy_details_alias!(10),
2323        issue_copy_details_alias!(11),
2324        issue_copy_details_alias!(12),
2325        issue_copy_details_alias!(13),
2326        issue_copy_details_alias!(14),
2327        issue_copy_details_alias!(15),
2328        issue_copy_details_alias!(16),
2329        issue_copy_details_alias!(17),
2330        issue_copy_details_alias!(18),
2331        issue_copy_details_alias!(19),
2332        issue_copy_details_alias!(20),
2333        "\n      children:node(id:$project) @include(if:$children){... on Issue{id subIssues(first:$nestedFirst){nodes{id title} pageInfo{hasNextPage}}}}",
2334        "\n    }",
2335        board_issue!(),
2336        related_issue!()
2337    );
2338
2339    /// Which issue one comment is on, read before that comment is edited or removed.
2340    ///
2341    /// GitHub's comment mutations take the comment's id and nothing else, so without this a
2342    /// comment id given against the wrong task would change a comment on another issue.
2343    pub const COMMENT_ISSUE: &str =
2344        r#"query($id:ID!){node(id:$id){__typename ... on IssueComment{id body issue{id}}}}"#;
2345    /// Adds one comment to an issue, signed as the account the token belongs to.
2346    pub const ADD_COMMENT: &str = concat!(
2347        r#"mutation($input:AddCommentInput!){addComment(input:$input){subject{id} commentEdge{node{"#,
2348        issue_comment!(),
2349        r#"}}}}"#
2350    );
2351    /// Replaces the body of one issue comment.
2352    pub const UPDATE_COMMENT: &str = concat!(
2353        r#"mutation($input:UpdateIssueCommentInput!){updateIssueComment(input:$input){issueComment{"#,
2354        issue_comment!(),
2355        r#"}}}"#
2356    );
2357    /// Removes one issue comment. Its payload carries nothing about the comment it removed.
2358    pub const DELETE_COMMENT: &str = r#"mutation($input:DeleteIssueCommentInput!){deleteIssueComment(input:$input){clientMutationId}}"#;
2359
2360    /// The variables of the search slots `<n>` of [`SEARCH_BATCH`]: its search, where it
2361    /// resumes, its page size and whether it is asked.
2362    macro_rules! search_batch_variables {
2363        ($($n:literal)+) => {
2364            concat!($(
2365                ",$search", stringify!($n), ":String!,$after", stringify!($n),
2366                ":String,$first", stringify!($n), ":Int!,$ask", stringify!($n), ":Boolean!",
2367            )+)
2368        };
2369    }
2370    /// The search slots `<n>` of [`SEARCH_BATCH`]: [`SEARCH_ISSUES`]'s one connection, aliased
2371    /// `s<n>`, sent only while `$ask<n>` holds — each hit's scalar fields alone, and no
2372    /// connection beneath a row, so GitHub prices the slot as the one connection it is however
2373    /// many rows it asks for.
2374    macro_rules! search_batch_slots {
2375        ($($n:literal)+) => {
2376            concat!($(
2377                "\n      s", stringify!($n), ":search(query:$search", stringify!($n),
2378                ",type:$type,first:$first", stringify!($n), ",after:$after", stringify!($n),
2379                ") @include(if:$ask", stringify!($n),
2380                "){pageInfo{hasNextPage endCursor} nodes{", search_hit!(), "}}",
2381            )+)
2382        };
2383    }
2384    /// What one hit of a [`SEARCH_BATCH`] search slot carries: its scalar fields and its
2385    /// repository's name — never a connection, so no field of it is priced per row. Every task
2386    /// a batched find answers is read whole afterwards, through [`ISSUE_DETAILS`].
2387    macro_rules! search_hit {
2388        () => {
2389            "__typename ... on Issue{id number title state updatedAt repository{nameWithOwner}}"
2390        };
2391    }
2392    /// The variables of the origin slots `<n>` of [`SEARCH_BATCH`]: the board's field filter
2393    /// naming the origin, where its items resume, their page size and whether it is asked.
2394    macro_rules! origin_batch_variables {
2395        ($($n:literal)+) => {
2396            concat!($(
2397                ",$filter", stringify!($n), ":String!,$itemsAfter", stringify!($n),
2398                ":String,$itemsFirst", stringify!($n), ":Int!,$origin", stringify!($n),
2399                ":Boolean!",
2400            )+)
2401        };
2402    }
2403    /// The origin slots `<n>` of [`SEARCH_BATCH`]: [`ORIGIN_LOOKUP`]'s board half, the board's
2404    /// own items through its field filter, aliased `o<n>`, sent only while `$origin<n>` holds —
2405    /// each item's id and its content's kind and id alone, read whole afterwards as a search
2406    /// hit is.
2407    macro_rules! origin_batch_slots {
2408        ($($n:literal)+) => {
2409            concat!($(
2410                "\n      o", stringify!($n), ":repositoryOwner(login:$owner) @include(if:$origin",
2411                stringify!($n),
2412                "){... on ProjectV2Owner{projectV2(number:$number){items(first:$itemsFirst",
2413                stringify!($n), ",after:$itemsAfter", stringify!($n), ",query:$filter",
2414                stringify!($n), "){nodes{id content{__typename ... on Issue{id}}} ",
2415                "pageInfo{hasNextPage endCursor}}}}}",
2416            )+)
2417        };
2418    }
2419
2420    /// Up to [`SEARCH_BATCH`](super::SEARCH_BATCH) board-scoped issue searches in one request,
2421    /// each [`SEARCH_ISSUES`]'s connection in an aliased `s<n>` field with its own query, page
2422    /// size and cursor, and beside them up to
2423    /// [`SEARCH_BATCH_ORIGINS`](super::SEARCH_BATCH_ORIGINS) origin lookups' board halves —
2424    /// [`ORIGIN_LOOKUP`]'s `items` filtered by the origin field — in aliased `o<n>` fields, each
2425    /// origin's issue search in a search slot of its own.
2426    ///
2427    /// What `task find` asks a board, every search a page at a time: one request a round,
2428    /// rather than one per search. A slot not asked is left out by `@include`, its page size
2429    /// bound to one; GitHub answers an error about one slot at that slot's path, and the other
2430    /// slots are answered beside it.
2431    ///
2432    /// **It reads which issues match, never the issues themselves.** Every row is its scalar
2433    /// fields alone, so GitHub prices each slot as one connection whatever its page size, and a
2434    /// round of twenty searches of a hundred rows each costs one point — where one page of the
2435    /// whole issue fragment cost a point per twenty rows, every row's labels and board field
2436    /// values priced whether or not that hit was kept. The distinct hits of a whole find are
2437    /// then read once each, [`DETAIL_BATCH`](super::DETAIL_BATCH) at a time, by
2438    /// [`ISSUE_DETAILS`], which every field a find answers comes from.
2439    pub const SEARCH_BATCH: &str = concat!(
2440        r#"query($owner:String!,$number:Int!,$type:SearchType!"#,
2441        search_batch_variables!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19),
2442        origin_batch_variables!(0 1 2 3 4),
2443        "){",
2444        search_batch_slots!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19),
2445        origin_batch_slots!(0 1 2 3 4),
2446        "\n    }"
2447    );
2448
2449    /// The comment slots `<n>` of [`ADD_COMMENTS`]: [`ADD_COMMENT`]'s mutation, aliased
2450    /// `comment<n>`, sent only while `$send<n>` holds.
2451    macro_rules! comment_slots {
2452        ($($n:literal)+) => {
2453            concat!($(
2454                " comment", stringify!($n), ":addComment(input:$comment", stringify!($n),
2455                ") @include(if:$send", stringify!($n), "){subject{id} commentEdge{node{",
2456                issue_comment!(), "}}}",
2457            )+)
2458        };
2459    }
2460
2461    /// Adds up to [`COMMENT_BATCH`](super::COMMENT_BATCH) comments in one request, each as
2462    /// [`ADD_COMMENT`] adds one, in order: what `task comment add-many` sends. GitHub runs each
2463    /// alias on its own and answers one it refused at its own path, beside the others.
2464    pub const ADD_COMMENTS: &str = concat!(
2465        "mutation(",
2466        wide_variables!("comment", "AddCommentInput", "send"; 0 1 2 3 4 5 6 7 8 9 10),
2467        "){",
2468        comment_slots!(0 1 2 3 4 5 6 7 8 9 10),
2469        "}"
2470    );
2471
2472    /// Many tasks' targeted updates, each as [`UPDATE_FIELDS`] and [`UPDATE_ISSUE`] write one:
2473    /// up to [`TASK_FIELD_BATCH`](super::TASK_FIELD_BATCH) board field values in `field<n>`,
2474    /// [`MUTATION_BATCH`](super::MUTATION_BATCH) field clears in `clear<n>`, and as many
2475    /// `updateIssue`s in `update<n>`, each sent only while its own `send…<n>` holds.
2476    ///
2477    /// What `task update-many` sends, in two requests at most: every item's field values and
2478    /// clears first, then every issue update of an item whose fields all landed — the order one
2479    /// item's update keeps, so a refusal part way leaves an item's body as it stood.
2480    ///
2481    /// Each `update<n>` selects the issue it updated as a read of it does, so its response spells
2482    /// the change token the task holds after its batch's writes — the version `update-many`
2483    /// answers — with no read after them. Its page sizes are bound by `$nestedFirst` and
2484    /// `$boardItems`, as every read's are.
2485    pub const WRITE_TASKS: &str = concat!(
2486        "mutation(",
2487        wide_variables!("field", "UpdateProjectV2ItemFieldValueInput", "sendField"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2488        wide_variables!("clear", "ClearProjectV2ItemFieldValueInput", "sendClear"; 0 1 2 3 4 5 6 7 8 9 10),
2489        wide_variables!("update", "UpdateIssueInput", "sendUpdate"; 0 1 2 3 4 5 6 7 8 9 10),
2490        r#"$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2491        relationship_events_variable!(),
2492        "){",
2493        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),
2494        wide_slots!("clear", "clearProjectV2ItemFieldValue", "projectV2Item{id}", "sendClear"; 0 1 2 3 4 5 6 7 8 9 10),
2495        wide_slots!("update", "updateIssue", "issue{id ...BoardIssue}", "sendUpdate"; 0 1 2 3 4 5 6 7 8 9 10),
2496        "}",
2497        board_issue!()
2498    );
2499
2500    /// One alias of [`ISSUE_RELATIONS`]: the item a batch's `$id<n>` names, as a read of it by
2501    /// its own id reads it, with a page of its sub-issues' ids.
2502    macro_rules! issue_relations_alias {
2503        ($n:literal) => {
2504            concat!(
2505                "\n      i",
2506                stringify!($n),
2507                ":node(id:$id",
2508                stringify!($n),
2509                "){__typename ...BoardIssue ... on Issue{subIssues(first:$first){nodes{id}pageInfo{hasNextPage}}}}"
2510            )
2511        };
2512    }
2513
2514    /// [`ISSUE_DETAILS`] with each issue's sub-issues in place of its comments: what `task
2515    /// relations` and a link write read of [`DETAIL_BATCH`](super::DETAIL_BATCH) tasks at once
2516    /// on a source reading sub-issues as children — each task whole, its parent and the ids of up
2517    /// to `$first` of its children.
2518    pub const ISSUE_RELATIONS: &str = concat!(
2519        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!"#,
2520        relationship_events_variable!(),
2521        r#"){"#,
2522        issue_relations_alias!(0),
2523        issue_relations_alias!(1),
2524        issue_relations_alias!(2),
2525        issue_relations_alias!(3),
2526        issue_relations_alias!(4),
2527        issue_relations_alias!(5),
2528        issue_relations_alias!(6),
2529        issue_relations_alias!(7),
2530        issue_relations_alias!(8),
2531        issue_relations_alias!(9),
2532        issue_relations_alias!(10),
2533        issue_relations_alias!(11),
2534        issue_relations_alias!(12),
2535        issue_relations_alias!(13),
2536        issue_relations_alias!(14),
2537        issue_relations_alias!(15),
2538        issue_relations_alias!(16),
2539        issue_relations_alias!(17),
2540        issue_relations_alias!(18),
2541        issue_relations_alias!(19),
2542        issue_relations_alias!(20),
2543        issue_relations_alias!(21),
2544        issue_relations_alias!(22),
2545        issue_relations_alias!(23),
2546        "\n    }",
2547        board_issue!()
2548    );
2549
2550    /// Up to [`RELATION_BATCH`](super::RELATION_BATCH) parent writes in one request:
2551    /// `parent<n>` an `addSubIssue` (a re-parent carrying `replaceParent: true`) and `unparent<n>`
2552    /// a `removeSubIssue`, each sent only while its own `send…<n>` holds. GitHub runs each alias
2553    /// on its own and answers one it refused — a cycle, a depth or children limit — at its own
2554    /// path, beside the others.
2555    pub const SET_PARENTS: &str = concat!(
2556        "mutation(",
2557        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),
2558        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),
2559        "){",
2560        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),
2561        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),
2562        "}"
2563    );
2564
2565    /// Up to [`RELATION_BATCH`](super::RELATION_BATCH) `relates-to` relations added in one
2566    /// request, each `relate<n>` sent only while `$send<n>` holds: what a link of a type a
2567    /// source mirrors natively writes beside its metadata.
2568    pub const ADD_RELATES_TO: &str = concat!(
2569        "mutation(",
2570        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),
2571        "){",
2572        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),
2573        "}"
2574    );
2575
2576    /// [`ADD_RELATES_TO`]'s removal: up to [`RELATION_BATCH`](super::RELATION_BATCH)
2577    /// `relates-to` relations removed in one request.
2578    pub const REMOVE_RELATES_TO: &str = concat!(
2579        "mutation(",
2580        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),
2581        "){",
2582        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),
2583        "}"
2584    );
2585
2586    /// One alias of [`RELATES_TO_READS`]: the issue `$id<n>` names and the ids of up to
2587    /// `$first` of the issues it relates to.
2588    macro_rules! relates_to_alias {
2589        ($n:literal) => {
2590            concat!(
2591                "\n      r",
2592                stringify!($n),
2593                ":node(id:$id",
2594                stringify!($n),
2595                "){... on Issue{id relatesTo(first:$first){nodes{id}pageInfo{hasNextPage}}}}"
2596            )
2597        };
2598    }
2599
2600    /// What [`DETAIL_BATCH`](super::DETAIL_BATCH) issues relate to, one alias each: read
2601    /// after a relation write whose answer never arrived, so each relation is answered from what
2602    /// GitHub holds rather than sent again blindly.
2603    pub const RELATES_TO_READS: &str = concat!(
2604        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!){"#,
2605        relates_to_alias!(0),
2606        relates_to_alias!(1),
2607        relates_to_alias!(2),
2608        relates_to_alias!(3),
2609        relates_to_alias!(4),
2610        relates_to_alias!(5),
2611        relates_to_alias!(6),
2612        relates_to_alias!(7),
2613        relates_to_alias!(8),
2614        relates_to_alias!(9),
2615        relates_to_alias!(10),
2616        relates_to_alias!(11),
2617        relates_to_alias!(12),
2618        relates_to_alias!(13),
2619        relates_to_alias!(14),
2620        relates_to_alias!(15),
2621        relates_to_alias!(16),
2622        relates_to_alias!(17),
2623        relates_to_alias!(18),
2624        relates_to_alias!(19),
2625        relates_to_alias!(20),
2626        relates_to_alias!(21),
2627        relates_to_alias!(22),
2628        relates_to_alias!(23),
2629        "\n    }"
2630    );
2631
2632    /// What a mutation of a write the store's cache expects selects of the issue it wrote:
2633    /// everything [`ISSUE_DETAIL`] reads of it, so its response shows the task whole — its
2634    /// change token's every part and the first page of its comments.
2635    ///
2636    /// Sent **only** while that write runs, in place of the document named beside each
2637    /// below, so every other write's documents, prices and request counts are what they
2638    /// were. GitHub's token waits for a task to settle (`change_token::SETTLED`), and a
2639    /// mutation's response is stamped seconds after the change it made, so against GitHub
2640    /// itself a response rarely determines a version; the cache is then left unserveable
2641    /// for the task, and its next read refreshes it.
2642    macro_rules! whole_issue {
2643        () => {
2644            concat!(
2645                r#"__typename ...BoardIssue ... on Issue{comments(first:$first){nodes{"#,
2646                issue_comment!(),
2647                r#"}pageInfo{hasNextPage endCursor}}}"#
2648            )
2649        };
2650    }
2651
2652    /// The variables every document of `whole_issue!` declares beside its own.
2653    macro_rules! whole_variables {
2654        () => {
2655            concat!(
2656                r#",$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2657                relationship_events_variable!()
2658            )
2659        };
2660    }
2661
2662    /// [`ADD_COMMENT`], selecting the whole issue commented on.
2663    pub const ADD_COMMENT_WHOLE: &str = concat!(
2664        r#"mutation($input:AddCommentInput!"#,
2665        whole_variables!(),
2666        r#"){addComment(input:$input){subject{id "#,
2667        whole_issue!(),
2668        r#"} commentEdge{node{"#,
2669        issue_comment!(),
2670        r#"}}}}"#,
2671        board_issue!()
2672    );
2673    /// [`UPDATE_COMMENT`], selecting the whole issue the comment is on.
2674    pub const UPDATE_COMMENT_WHOLE: &str = concat!(
2675        r#"mutation($input:UpdateIssueCommentInput!"#,
2676        whole_variables!(),
2677        r#"){updateIssueComment(input:$input){issueComment{"#,
2678        issue_comment!(),
2679        r#" issue{"#,
2680        whole_issue!(),
2681        r#"}}}}"#,
2682        board_issue!()
2683    );
2684    /// [`UPDATE_ISSUE`], selecting the whole issue updated.
2685    pub const UPDATE_ISSUE_WHOLE: &str = concat!(
2686        r#"mutation($input:UpdateIssueInput!"#,
2687        whole_variables!(),
2688        r#"){updateIssue(input:$input){issue{id "#,
2689        whole_issue!(),
2690        r#"}}}"#,
2691        board_issue!()
2692    );
2693    /// [`UPDATE_FIELD`], selecting the whole issue behind the board item written.
2694    pub const UPDATE_FIELD_WHOLE: &str = concat!(
2695        r#"mutation($input:UpdateProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
2696        whole_variables!(),
2697        r#"){updateProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{"#,
2698        whole_issue!(),
2699        r#"}}}}"#,
2700        board_issue!()
2701    );
2702    /// [`CLEAR_FIELD`], selecting the whole issue behind the board item cleared.
2703    pub const CLEAR_FIELD_WHOLE: &str = concat!(
2704        r#"mutation($input:ClearProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
2705        whole_variables!(),
2706        r#"){clearProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{"#,
2707        whole_issue!(),
2708        r#"}}}}"#,
2709        board_issue!()
2710    );
2711
2712    /// The variables every document selecting [`board_issue_fields!`] inline declares beside
2713    /// its own.
2714    macro_rules! token_variables {
2715        () => {
2716            concat!(
2717                r#",$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2718                relationship_events_variable!()
2719            )
2720        };
2721    }
2722
2723    /// [`UPDATE_ISSUE`], selecting what a read of the issue updated selects — every part of its
2724    /// change token, and no comment — inline, so its root fields are the plain document's.
2725    ///
2726    /// What a targeted update sends in the plain document's place, so the version it answers
2727    /// is the one its own last response spells (`GitHubProjectsSource::written_tokens`). It
2728    /// costs the one point the plain document does.
2729    pub const UPDATE_ISSUE_TOKEN: &str = concat!(
2730        r#"mutation($input:UpdateIssueInput!"#,
2731        token_variables!(),
2732        r#"){updateIssue(input:$input){issue{"#,
2733        board_issue_fields!(),
2734        r#"}}}"#
2735    );
2736    /// [`UPDATE_FIELD`], selecting the issue behind the board item written as
2737    /// [`UPDATE_ISSUE_TOKEN`] selects the issue it updates.
2738    pub const UPDATE_FIELD_TOKEN: &str = concat!(
2739        r#"mutation($input:UpdateProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
2740        token_variables!(),
2741        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{"#,
2742        board_issue_fields!(),
2743        r#"}}}}}"#
2744    );
2745    /// [`CLEAR_FIELD`], selecting the issue behind the board item cleared as
2746    /// [`UPDATE_ISSUE_TOKEN`] selects the issue it updates.
2747    pub const CLEAR_FIELD_TOKEN: &str = concat!(
2748        r#"mutation($input:ClearProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
2749        token_variables!(),
2750        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{"#,
2751        board_issue_fields!(),
2752        r#"}}}}}"#
2753    );
2754
2755    /// The document a targeted update sends in `document`'s place, when it has one: the twin
2756    /// whose answer spells the change token of the issue written.
2757    #[must_use]
2758    pub fn token_twin(document: &str) -> Option<&'static str> {
2759        [
2760            (UPDATE_ISSUE, UPDATE_ISSUE_TOKEN),
2761            (UPDATE_FIELD, UPDATE_FIELD_TOKEN),
2762            (CLEAR_FIELD, CLEAR_FIELD_TOKEN),
2763        ]
2764        .into_iter()
2765        .find(|(plain, _)| *plain == document)
2766        .map(|(_, token)| token)
2767    }
2768
2769    /// The document sent in `document`'s place while a write the store's cache expects runs,
2770    /// when it has one.
2771    #[must_use]
2772    pub fn whole_twin(document: &str) -> Option<&'static str> {
2773        [
2774            (ADD_COMMENT, ADD_COMMENT_WHOLE),
2775            (UPDATE_COMMENT, UPDATE_COMMENT_WHOLE),
2776            (UPDATE_ISSUE, UPDATE_ISSUE_WHOLE),
2777            (UPDATE_FIELD, UPDATE_FIELD_WHOLE),
2778            (CLEAR_FIELD, CLEAR_FIELD_WHOLE),
2779        ]
2780        .into_iter()
2781        .find(|(plain, _)| *plain == document)
2782        .map(|(_, whole)| whole)
2783    }
2784
2785    /// The node id of one person by their login, as the aliased field `u0` answering `$login0`:
2786    /// what an assignee write names a person by, since `assigneeIds` takes node ids and a person
2787    /// is named by login.
2788    ///
2789    /// The inventoried form of the lookup. What is sent is this document sized to the call
2790    /// ([`user_ids`]): one `u<n>:user(login:$login<n>)` field per person the call names that
2791    /// this process has not resolved, so one request answers every one of them. GitHub answers a
2792    /// login it does not know with `null` at that alias beside a `NOT_FOUND` error naming it,
2793    /// and the others' ids beside them.
2794    pub const USER_IDS: &str = "query($login0:String!){ u0:user(login:$login0){id login}}";
2795
2796    /// [`USER_IDS`] for `people` logins — `$login0` to `$login<people - 1>`, each answered at
2797    /// its own alias — and [`USER_IDS`] itself for one.
2798    #[must_use]
2799    pub fn user_ids(people: usize) -> String {
2800        let people = people.max(1);
2801        let declared: Vec<String> = (0..people)
2802            .map(|slot| format!("$login{slot}:String!"))
2803            .collect();
2804        let fields: Vec<String> = (0..people)
2805            .map(|slot| format!("u{slot}:user(login:$login{slot}){{id login}}"))
2806            .collect();
2807        format!("query({}){{ {}}}", declared.join(","), fields.join(" "))
2808    }
2809
2810    /// The document a request sending `document` with `variables` really sends: [`USER_IDS`]
2811    /// sized to the logins `variables` binds, and every other document as it is.
2812    #[must_use]
2813    pub fn sized<'a>(
2814        document: &'a str,
2815        variables: &serde_json::Value,
2816    ) -> std::borrow::Cow<'a, str> {
2817        if document != USER_IDS {
2818            return std::borrow::Cow::Borrowed(document);
2819        }
2820        let people = (0..)
2821            .take_while(|slot| variables.get(format!("login{slot}")).is_some())
2822            .count();
2823        std::borrow::Cow::Owned(user_ids(people))
2824    }
2825
2826    /// The inventoried document `document` is an instance of: [`USER_IDS`] for any lookup
2827    /// [`user_ids`] sized, and `document` itself otherwise.
2828    #[must_use]
2829    pub fn inventoried(document: &str) -> &str {
2830        let people = document.matches(":user(login:$login").count();
2831        if people > 0 && user_ids(people) == document {
2832            USER_IDS
2833        } else {
2834            document
2835        }
2836    }
2837
2838    /// The selection every read this source sends carries so GitHub reports what that very
2839    /// request cost: `rateLimit { cost }` executed (`dryRun: false`), under an alias of its own,
2840    /// so it never collides with the unaliased `rateLimit(dryRun: true)` probe the credentialed
2841    /// lane adds to price a document without running it. `rateLimit` is one object of scalars
2842    /// and no connection, so it adds nothing to the document's node count or its price — GitHub
2843    /// prices a read the same with it and without it — which is why it rides on every read.
2844    const REPORTED_COST: &str = "actualCost:rateLimit(dryRun:false){cost} ";
2845    /// The alias [`REPORTED_COST`] answers under.
2846    const REPORTED_COST_ALIAS: &str = "actualCost";
2847
2848    /// `document` as this source sends it, selecting what GitHub charged the request:
2849    /// [`REPORTED_COST`] as the first field of its operation — or `None` for a mutation, whose
2850    /// `rateLimit` GitHub offers no way to select, and for a document already selecting one.
2851    ///
2852    /// A rewrite of the one text sent, at the one place a document leaves for GitHub, rather
2853    /// than a second set of documents: every constant here stays the document it prices as, and
2854    /// [`without_reported_cost`] is the exact inverse a loopback board answers a document by.
2855    #[must_use]
2856    pub fn with_reported_cost(document: &str) -> Option<String> {
2857        if super::is_mutation(document) || document.contains("rateLimit") {
2858            return None;
2859        }
2860        let root = document.find('{')?;
2861        Some(format!(
2862            "{}{REPORTED_COST}{}",
2863            &document[..=root],
2864            &document[root + 1..]
2865        ))
2866    }
2867
2868    /// `document` as [`with_reported_cost`] spelled it, back as the document it was written as
2869    /// — or `None` for a document it did not rewrite.
2870    #[must_use]
2871    pub fn without_reported_cost(document: &str) -> Option<String> {
2872        let plain = document.replacen(REPORTED_COST, "", 1);
2873        // Only what `with_reported_cost` spelled: a caller's own document selecting the alias
2874        // beside a dry-run probe, which that never spells, is left as it is.
2875        (with_reported_cost(&plain).as_deref() == Some(document)).then_some(plain)
2876    }
2877
2878    /// What GitHub said a request [`with_reported_cost`] spelled cost, in points, read from the
2879    /// response's `data` — or `None` where it said nothing.
2880    #[must_use]
2881    pub fn reported_cost(data: &serde_json::Value) -> Option<u64> {
2882        data.get(REPORTED_COST_ALIAS)
2883            .and_then(|cost| cost.get("cost"))
2884            .and_then(serde_json::Value::as_u64)
2885    }
2886
2887    /// `data` without the field [`with_reported_cost`] selects, so what a document answered is
2888    /// read as the document it was written as.
2889    pub fn forget_reported_cost(data: &mut serde_json::Value) {
2890        if let Some(object) = data.as_object_mut() {
2891            object.remove(REPORTED_COST_ALIAS);
2892        }
2893    }
2894
2895    /// The answer a loopback board gives the field [`with_reported_cost`] selects: `data` with
2896    /// GitHub's report of `cost` points beside what the document asked.
2897    pub fn answer_reported_cost(data: &mut serde_json::Value, cost: u64) {
2898        if let Some(object) = data.as_object_mut() {
2899            object.insert(
2900                REPORTED_COST_ALIAS.to_owned(),
2901                serde_json::json!({ "cost": cost }),
2902            );
2903        }
2904    }
2905
2906    /// The selection of an issue's — or a draft's — assignees, as a source opted in to them
2907    /// (`config.assignees: true`) adds it to every document that reads one; see
2908    /// [`with_assignees`].
2909    const ASSIGNEES: &str = " assignees(first:$assigneeFirst){nodes{id login}}";
2910    /// The variable [`ASSIGNEES`] pages by, declared with its value as its default — the most
2911    /// people GitHub assigns one issue — so no caller binds it, and inserted first among a
2912    /// document's variables.
2913    const ASSIGNEE_VARIABLE: &str = "$assigneeFirst:Int!=10 ";
2914
2915    /// The default [`ASSIGNEE_VARIABLE`] declares, read out of that declaration: what a request
2916    /// spelled with assignees is priced at.
2917    pub(crate) fn assignee_first() -> u32 {
2918        ASSIGNEE_VARIABLE
2919            .trim()
2920            .rsplit('=')
2921            .next()
2922            .and_then(|default| default.parse().ok())
2923            .expect("the assignee variable declares a numeric default")
2924    }
2925    /// [`ASSIGNEE_VARIABLE`] for a document declaring no variables of its own.
2926    const ASSIGNEE_VARIABLES: &str = "($assigneeFirst:Int!=10)";
2927    /// Where [`ASSIGNEES`] goes: straight after each of these, wherever an issue or a draft is
2928    /// read — what every read of an issue selects of it — and inside the answer of each
2929    /// `createIssue` and `updateIssue`, so a write's own answer says whom GitHub assigned.
2930    const ASSIGNEE_MARKERS: [&str; 2] = [
2931        "commentCount:comments{totalCount}",
2932        "title body createdAt updatedAt",
2933    ];
2934
2935    /// `document` as a source opted in to assignees sends it: [`ASSIGNEES`] selected wherever
2936    /// it reads an issue or a draft and in every `createIssue` and `updateIssue` answer, with the
2937    /// variable it pages by declared — or `None` when it reads and writes neither, and is sent
2938    /// as written.
2939    ///
2940    /// A rewrite of the one text sent rather than a second set of documents, so a source that
2941    /// has not opted in sends every document byte for byte as it did, and an opted-in one rides
2942    /// its assignees on the very reads and writes it already makes. [`without_assignees`] is its
2943    /// exact inverse, which the loopback board answers a document by.
2944    #[must_use]
2945    pub fn with_assignees(document: &str) -> Option<String> {
2946        let mut spelled = String::with_capacity(document.len() + 256);
2947        let mut inserted = false;
2948        let mut rest = document;
2949        while !rest.is_empty() {
2950            // The earliest place one is due, of every kind.
2951            let next = ASSIGNEE_MARKERS
2952                .iter()
2953                .filter_map(|marker| rest.find(marker).map(|at| (at + marker.len(), true)))
2954                .chain(["createIssue(", "updateIssue("].iter().filter_map(|write| {
2955                    let at = rest.find(write)?;
2956                    let open = at + rest[at..].find('{')?;
2957                    rest[open..]
2958                        .starts_with("{issue{id")
2959                        .then_some((open + "{issue{id".len(), true))
2960                        .or(Some((open, false)))
2961                }))
2962                .min_by_key(|(at, _)| *at);
2963            let Some((at, insert)) = next else {
2964                spelled.push_str(rest);
2965                break;
2966            };
2967            spelled.push_str(&rest[..at]);
2968            if insert {
2969                spelled.push_str(ASSIGNEES);
2970                inserted = true;
2971            }
2972            rest = &rest[at..];
2973            if !insert {
2974                // A write whose answer reads no issue's id first: past its opening brace.
2975                spelled.push('{');
2976                rest = &rest[1..];
2977            }
2978        }
2979        if !inserted {
2980            return None;
2981        }
2982        let open = spelled.find('(');
2983        let body = spelled.find('{');
2984        Some(match (open, body) {
2985            (Some(open), Some(body)) if open < body => {
2986                format!(
2987                    "{}{ASSIGNEE_VARIABLE}{}",
2988                    &spelled[..=open],
2989                    &spelled[open + 1..]
2990                )
2991            }
2992            (_, Some(body)) => format!(
2993                "{}{ASSIGNEE_VARIABLES}{}",
2994                &spelled[..body],
2995                &spelled[body..]
2996            ),
2997            _ => return None,
2998        })
2999    }
3000
3001    /// `document` as [`with_assignees`] spelled it, back as the document it was written as — or
3002    /// `None` for a document it did not rewrite.
3003    #[must_use]
3004    pub fn without_assignees(document: &str) -> Option<String> {
3005        if !document.contains(ASSIGNEES) {
3006            return None;
3007        }
3008        let plain = document.replace(ASSIGNEES, "");
3009        Some(if plain.contains(ASSIGNEE_VARIABLES) {
3010            plain.replacen(ASSIGNEE_VARIABLES, "", 1)
3011        } else {
3012            plain.replacen(ASSIGNEE_VARIABLE, "", 1)
3013        })
3014    }
3015
3016    /// Every document above, with what this source is doing when it sends one.
3017    ///
3018    /// One list rather than a `match` beside the constants: a rate-limit diagnostic has to
3019    /// name the call that was refused, and a `match` with a catch-all arm would answer a
3020    /// document added later with "talking to GitHub" and never say so.
3021    ///
3022    /// `documents_are_all_inventoried` reads this file back and fails naming any `pub
3023    /// const` here that this list omits, so the two cannot part — which is the same guard
3024    /// `CATEGORIES` carries, in the one shape available to a set of `&str` constants.
3025    pub const DOCUMENTS: [(&str, &str); 71] = [
3026        (USER_IDS, "looking up the people an assignee write names"),
3027        (
3028            ISSUE_RELATIONS,
3029            "reading several issues with their parents and sub-issues",
3030        ),
3031        (SET_PARENTS, "writing several issues' parents"),
3032        (ADD_RELATES_TO, "adding several relates-to relations"),
3033        (REMOVE_RELATES_TO, "removing several relates-to relations"),
3034        (
3035            RELATES_TO_READS,
3036            "reading what several issues relate to after a relation write went unanswered",
3037        ),
3038        (
3039            ISSUES_BY_CREATION,
3040            "listing a repository's issues newest first for a create key",
3041        ),
3042        (SEARCH_ISSUES, "searching this board's issues"),
3043        (ISSUE, "reading one issue"),
3044        (
3045            DOCUMENT_IN_PROJECT,
3046            "reading one document with its project and the project's members",
3047        ),
3048        (
3049            ISSUE_BOARD_ITEMS,
3050            "reading one issue's board memberships past the page it came with",
3051        ),
3052        (SUB_ISSUES, "reading a project's tasks"),
3053        (BOARD, "reading the board"),
3054        (
3055            BOARD_WITH_COMMENTS,
3056            "reading a board page with first comments",
3057        ),
3058        (ORIGIN_LOOKUP, "looking up the items copied from one origin"),
3059        (CLOSED_ITEMS, "reading the board's closed items"),
3060        (OPEN_ITEMS, "reading the board's open items"),
3061        (CLOSE_ISSUE, "closing an issue as a duplicate"),
3062        (
3063            ISSUES_BY_REFERENCE,
3064            "reading a batch of issues by their references",
3065        ),
3066        (BOARD_FIELDS, "reading the board's fields"),
3067        (DRAFT, "reading one draft"),
3068        (REPOSITORY, "reading the destination repository"),
3069        (
3070            PROJECT_VISIBILITY,
3071            "reading whether the board's project is public",
3072        ),
3073        (
3074            CREATION_CONTEXT,
3075            "reading the board's fields and the destination repository",
3076        ),
3077        (ISSUE_DEPENDENCIES, "reading an issue's dependencies"),
3078        (ISSUE_DEPENDS_ON, "reading what an item depends on"),
3079        (ISSUE_DEPENDED_ON_BY, "reading what depends on an issue"),
3080        (CREATE_ISSUE, "creating an issue"),
3081        (
3082            ORIGIN_LOOKUPS,
3083            "looking up the items copied from several origins, and what creating one reads",
3084        ),
3085        (
3086            ORIGIN_LOOKUPS_WITH_MEMBERS,
3087            "looking up the items copied from several origins, with a project's members",
3088        ),
3089        (CREATE_ISSUES, "creating several issues together"),
3090        (
3091            CREATED_BOARD_ITEMS,
3092            "reading the board items of the issues a copy created",
3093        ),
3094        (
3095            WRITE_FIELD_VALUES,
3096            "writing board fields of the items a copy created",
3097        ),
3098        (
3099            WRITE_FIELDS_AND_EDGES,
3100            "writing board fields and dependencies of the items a copy created",
3101        ),
3102        (CLOSE_ISSUES, "closing the issues a copy created"),
3103        (UPDATE_ISSUES, "updating several issues together"),
3104        (ADD_BLOCKED_BYS, "recording several dependencies together"),
3105        (ADD_TO_BOARD, "adding an issue to the board"),
3106        (UPDATE_ISSUE, "updating an issue"),
3107        (UPDATE_DRAFT, "updating a draft item"),
3108        (UPDATE_FIELD, "writing a board field"),
3109        (UPDATE_FIELDS, "writing board fields together"),
3110        (CLEAR_FIELD, "clearing a board field"),
3111        (
3112            CREATE_FIELD,
3113            "creating a board single-select field with its options",
3114        ),
3115        (
3116            STATUS_OPTIONS_SNAPSHOT,
3117            "snapshotting board Status options and assignments",
3118        ),
3119        (
3120            STATUS_OPTIONS_UPDATE,
3121            "safely replacing the board Status option list",
3122        ),
3123        (ADD_SUB_ISSUE, "filing an issue under its project"),
3124        (REMOVE_SUB_ISSUE, "taking an issue out of its project"),
3125        (ADD_BLOCKED_BY, "recording a dependency"),
3126        (REMOVE_BLOCKED_BY, "removing a dependency"),
3127        (DELETE_ISSUE, "deleting an issue"),
3128        (DELETE_ISSUES, "deleting several issues together"),
3129        (ISSUE_COMMENTS, "reading a task's comments"),
3130        (ISSUE_DETAIL, "reading one issue with its comments"),
3131        (
3132            ISSUE_DETAILS,
3133            "reading a batch of issues with their comments",
3134        ),
3135        (
3136            ISSUE_COPY_DETAILS,
3137            "reading a batch of issues with their comments and dependencies for a copy",
3138        ),
3139        (COMMENT_ISSUE, "reading which issue a comment is on"),
3140        (ADD_COMMENT, "adding a comment"),
3141        (UPDATE_COMMENT, "editing a comment"),
3142        (DELETE_COMMENT, "deleting a comment"),
3143        (
3144            SEARCH_BATCH,
3145            "searching this board's issues several ways at once",
3146        ),
3147        (ADD_COMMENTS, "adding several comments together"),
3148        (WRITE_TASKS, "updating several tasks together"),
3149        (
3150            ADD_COMMENT_WHOLE,
3151            "adding a comment, answered with the whole issue",
3152        ),
3153        (
3154            UPDATE_COMMENT_WHOLE,
3155            "editing a comment, answered with the whole issue",
3156        ),
3157        (
3158            UPDATE_ISSUE_WHOLE,
3159            "updating an issue, answered with it whole",
3160        ),
3161        (
3162            UPDATE_FIELD_WHOLE,
3163            "writing a board field, answered with the whole issue",
3164        ),
3165        (
3166            CLEAR_FIELD_WHOLE,
3167            "clearing a board field, answered with the whole issue",
3168        ),
3169        (
3170            UPDATE_ISSUE_TOKEN,
3171            "updating an issue, answered with its version",
3172        ),
3173        (
3174            UPDATE_FIELD_TOKEN,
3175            "writing a board field, answered with the issue's version",
3176        ),
3177        (
3178            CLEAR_FIELD_TOKEN,
3179            "clearing a board field, answered with the issue's version",
3180        ),
3181    ];
3182}
3183
3184/// One aliased mutation field of [`graphql::UPDATE_FIELDS`]: the key its answer comes back
3185/// under, the variable carrying its input, and the boolean variable that includes it.
3186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3187pub struct FieldSlot {
3188    /// The key of the answer's `data` this field's payload is under.
3189    pub alias: &'static str,
3190    /// The variable carrying this field's input.
3191    pub variable: &'static str,
3192    /// The boolean variable whose `true` sends this field.
3193    pub include: &'static str,
3194}
3195
3196/// The value writes [`graphql::UPDATE_FIELDS`] carries, in the order GitHub runs them.
3197pub const FIELD_WRITE_SLOTS: [FieldSlot; 6] = [
3198    FieldSlot {
3199        alias: "updateProjectV2ItemFieldValue",
3200        variable: "input",
3201        include: "writeFirst",
3202    },
3203    FieldSlot {
3204        alias: "second",
3205        variable: "second",
3206        include: "writeSecond",
3207    },
3208    FieldSlot {
3209        alias: "third",
3210        variable: "third",
3211        include: "writeThird",
3212    },
3213    FieldSlot {
3214        alias: "fourth",
3215        variable: "fourth",
3216        include: "writeFourth",
3217    },
3218    FieldSlot {
3219        alias: "fifth",
3220        variable: "fifth",
3221        include: "writeFifth",
3222    },
3223    FieldSlot {
3224        alias: "sixth",
3225        variable: "sixth",
3226        include: "writeSixth",
3227    },
3228];
3229
3230/// The clears [`graphql::UPDATE_FIELDS`] carries, run after every write of the same request.
3231pub const FIELD_CLEAR_SLOTS: [FieldSlot; 3] = [
3232    FieldSlot {
3233        alias: "cleared",
3234        variable: "clear",
3235        include: "writeClear",
3236    },
3237    FieldSlot {
3238        alias: "clearedSecond",
3239        variable: "clearSecond",
3240        include: "writeClearSecond",
3241    },
3242    FieldSlot {
3243        alias: "clearedThird",
3244        variable: "clearThird",
3245        include: "writeClearThird",
3246    },
3247];
3248
3249/// Which of GitHub's two rate limiters refused a request.
3250///
3251/// Waiting is the whole answer to the primary budget, and polling is what *extends* the
3252/// secondary one — so an operator told the wrong one takes the wrong next step, which is
3253/// the whole reason this is carried rather than collapsed into "rate limited".
3254#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3255enum Limiter {
3256    /// The hourly API budget, which `gh api rate_limit` reports and a wait answers.
3257    Primary,
3258    /// The burst limiter over content-generating requests, which nothing reports.
3259    Secondary,
3260}
3261
3262/// The wordings GitHub answers a secondary rate limit with.
3263///
3264/// It sends them under a forbidden status, under a too-many-requests status, and inside
3265/// the `errors` of a *successful* response, which is why the text is what this matches on
3266/// rather than the status. `abuse detection` is the wording GitHub used before the
3267/// limiter was renamed and still returns from some endpoints; `submitted too quickly` is
3268/// what a burst of content creation is refused with.
3269///
3270/// This is GitHub's vocabulary rather than this source's, so it is pinned rather than
3271/// remembered: `tests/fixtures/rate-limits.json` records where each wording was read and
3272/// when, and the drift gate reconciles the two lists both ways. Public for that gate
3273/// alone — a caller has no use for it, and matching on a refusal is this source's job.
3274pub const SECONDARY_WORDINGS: [&str; 5] = [
3275    "secondary rate limit",
3276    "temporarily blocked from content creation",
3277    "abuse detection",
3278    "submitted too quickly",
3279    "exceeded a secondary",
3280];
3281
3282/// The wordings GitHub answers an exhausted primary budget with.
3283///
3284/// `rate_limited` is the `type` its GraphQL error carries, which is read as a field rather
3285/// than looked for in the response text. `api rate limit already exceeded` is what GraphQL
3286/// answers a request made once the hour's budget is spent — "API rate limit already exceeded
3287/// for user ID …" in the `errors` of an HTTP 200, with no `type` — and neither of the other
3288/// two phrases is a substring of it, so without it that answer read as a refusal that will
3289/// never lift. Pinned and gated exactly as [`SECONDARY_WORDINGS`] is, and public for the same
3290/// one reason.
3291pub const PRIMARY_WORDINGS: [&str; 4] = [
3292    "api rate limit exceeded",
3293    "api rate limit already exceeded",
3294    "rate limit exceeded",
3295    "rate_limited",
3296];
3297
3298/// The wordings GitHub answers a write that collided with another change to the same
3299/// ordering with, in the `errors` of an HTTP 200: "Your attempt to move this item created a
3300/// temporary conflict. Please try again." The write did not take effect and GitHub asks for it
3301/// again, so it is retried on the same growing schedule a rate limit without a hint is, within
3302/// the same retry budget — except a `createIssue`, whose answer cannot say the issue was not
3303/// made, and which is therefore reported rather than replayed into a duplicate.
3304///
3305/// Observed rather than documented, so it is pinned exactly as [`SECONDARY_WORDINGS`] is:
3306/// `tests/fixtures/rate-limits.json` records where it was read under `conflict.observed`, and
3307/// the same drift gate reconciles the two both ways. Public for that gate alone.
3308pub const CONFLICT_WORDINGS: [&str; 1] = ["created a temporary conflict"];
3309
3310/// What a response *says about itself*, which is the only place a refusal can be read.
3311///
3312/// Deliberately not the whole response body. A board is a place people write about their
3313/// own work, and a task on it titled "the secondary rate limit" would, matched across the
3314/// raw text, turn a perfectly good answer into a refusal this source then waited out and
3315/// reported. So the item data is never read: what is read is GitHub's own REST-style
3316/// `message` envelope, which is what a forbidden status carries, and the `message` and
3317/// `type` of each GraphQL error, which is where a *successful* response says it.
3318///
3319/// A body that is not JSON at all has nothing structured to read, so only a failing
3320/// response's own text is taken — a successful response that is not JSON is malformed
3321/// rather than refused, and [`GitHubProjectsSource::answer`] says so.
3322fn refusal_wording(status: StatusCode, body: &str) -> String {
3323    let Ok(parsed) = serde_json::from_str::<Value>(body) else {
3324        return if status.is_success() {
3325            String::new()
3326        } else {
3327            body.to_owned()
3328        };
3329    };
3330    let mut said: Vec<&str> = parsed
3331        .get("message")
3332        .and_then(Value::as_str)
3333        .into_iter()
3334        .collect();
3335    if let Some(errors) = parsed.get("errors").and_then(Value::as_array) {
3336        for error in errors {
3337            said.extend(
3338                ["message", "type"]
3339                    .into_iter()
3340                    .filter_map(|key| error.get(key).and_then(Value::as_str)),
3341            );
3342        }
3343    }
3344    said.join("; ")
3345}
3346
3347impl Limiter {
3348    /// Which limiter refused this response, or `None` when none of them did.
3349    ///
3350    /// The wording is read first and the status only decides what carries none of it,
3351    /// because GitHub answers a secondary limit with a forbidden status far more often
3352    /// than with too-many-requests — while a forbidden status saying nothing about a limit
3353    /// really is a credential this token lacks.
3354    ///
3355    /// A response is a refusal because of its status or its own wording. A spent budget
3356    /// only ever explains one; it never turns an answer into a refusal.
3357    fn classify(status: StatusCode, budget_exhausted: bool, body: &str) -> Option<Self> {
3358        let normalized = refusal_wording(status, body).to_ascii_lowercase();
3359        if SECONDARY_WORDINGS
3360            .iter()
3361            .any(|wording| normalized.contains(wording))
3362        {
3363            return Some(Self::Secondary);
3364        }
3365        if status == StatusCode::TOO_MANY_REQUESTS {
3366            return Some(Self::Primary);
3367        }
3368        // An exhausted budget *explains* a response that failed; it does not make one that
3369        // succeeded into a failure. GitHub sets `x-ratelimit-remaining: 0` on the last
3370        // request the budget allowed as well as on the ones it then refuses, so reading
3371        // the header alone threw away a good answer — and, once refusals were retried,
3372        // replayed a request that had already taken effect.
3373        if !status.is_success() && budget_exhausted {
3374            return Some(Self::Primary);
3375        }
3376        // A successful response saying it: GitHub reports a GraphQL rate limit in the
3377        // `errors` of an HTTP 200, where nothing about the status says so at all.
3378        if status.is_success()
3379            && PRIMARY_WORDINGS
3380                .iter()
3381                .any(|wording| normalized.contains(wording))
3382        {
3383            return Some(Self::Primary);
3384        }
3385        None
3386    }
3387
3388    /// What this limiter is called where an operator can look it up.
3389    const fn name(self) -> &'static str {
3390        match self {
3391            Self::Primary => "GitHub's primary API rate limit",
3392            Self::Secondary => "GitHub's secondary rate limit",
3393        }
3394    }
3395
3396    /// What the endpoint an operator would go and check says about this limiter.
3397    const fn where_to_look(self) -> &'static str {
3398        match self {
3399            Self::Primary => {
3400                "That is the budget `gh api rate_limit` reports, so that endpoint says when it \
3401                 comes back."
3402            }
3403            Self::Secondary => {
3404                "That limiter is not the primary API budget: `gh api rate_limit` reports the \
3405                 primary budget and does not report this one, so budget showing there says \
3406                 nothing about this refusal, and every further attempt extends it."
3407            }
3408        }
3409    }
3410
3411    /// The next step this limiter actually calls for.
3412    const fn what_to_do(self) -> &'static str {
3413        match self {
3414            Self::Primary => {
3415                "wait for the reset `gh api rate_limit` reports, then run the command again."
3416            }
3417            Self::Secondary => {
3418                "leave this board alone for a few minutes, then run the command again — or \
3419                 raise pacing.min_mutation_interval_ms on this source so it writes more slowly."
3420            }
3421        }
3422    }
3423}
3424
3425/// One rate-limit refusal, and the wait GitHub asked for if it asked for one.
3426#[derive(Debug, Clone, Copy)]
3427struct Limited {
3428    limiter: Limiter,
3429    hint: Option<u64>,
3430    /// Which header the hint came from: `retry-after`, or an exhausted primary budget's
3431    /// `x-ratelimit-reset`.
3432    hinted_by: Hint,
3433}
3434
3435/// Where a refusal's hint came from, which is what its wait is named after.
3436#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3437enum Hint {
3438    /// `retry-after`, or no hint at all.
3439    RetryAfter,
3440    /// An exhausted primary budget's `x-ratelimit-reset`.
3441    PrimaryReset,
3442}
3443
3444impl Limited {
3445    /// The wait this refusal is answered with, when the backing-off schedule is at `backoff`,
3446    /// and the cause it is named by: the hint, raised to the schedule's own next wait —
3447    /// GitHub really does send `retry-after: 0`, and retrying at once is the one move that
3448    /// extends a secondary limit — or the schedule alone when there is none.
3449    fn wait(self, backoff: Duration) -> (Duration, WaitCause) {
3450        match (self.hint, self.hinted_by) {
3451            (Some(hint), Hint::RetryAfter) => (
3452                Duration::from_secs(hint).max(backoff),
3453                pacing::cause::RETRY_AFTER,
3454            ),
3455            (Some(hint), Hint::PrimaryReset) => (
3456                Duration::from_secs(hint).max(backoff),
3457                pacing::cause::PRIMARY_RESET,
3458            ),
3459            (None, _) => (backoff, pacing::cause::BACKOFF),
3460        }
3461    }
3462
3463    /// What the caller is told once this source has waited as long as it may.
3464    ///
3465    /// Both limiters report as [`SourceError::RateLimited`], because that is what
3466    /// happened: the kind a caller matches on says a rate limit refused this, and nothing
3467    /// about *which* limiter it was makes it a different kind of failure. What differs is
3468    /// the operator's next step, and that is what the message carries — a secondary
3469    /// refusal read as a primary one sends an operator to `gh api rate_limit`, where the
3470    /// budget looks fine, and then back to retry the very burst that was refused.
3471    fn exhausted(
3472        self,
3473        doing: &str,
3474        waits: u32,
3475        waited: Duration,
3476        needed: Duration,
3477        budget: Duration,
3478    ) -> SourceError {
3479        SourceError::RateLimited {
3480            retry_after_seconds: self.hint,
3481            message: Some(format!(
3482                "{} refused this source while {doing}; it waited {} out over {} and was refused \
3483                 again, and the next wait of {} would take it past the {} one call may spend \
3484                 waiting. {} next: {}",
3485                self.limiter.name(),
3486                plural(waits, "refusal"),
3487                seconds(waited),
3488                seconds(needed),
3489                seconds(budget),
3490                self.limiter.where_to_look(),
3491                self.limiter.what_to_do(),
3492            )),
3493        }
3494    }
3495}
3496
3497/// One HTTP attempt's result, with what its response said about the rate limit.
3498///
3499/// The two travel together so the record and the outcome are written from the same place:
3500/// what a response said about the budget is only readable while that response is in hand,
3501/// and what the attempt *meant* is only decidable once its body has been read.
3502struct Attempted {
3503    result: Result<Value, Attempt>,
3504    limits: accounting::RateLimit,
3505    /// GitHub's own reported cost for this call, for a document that asked for it.
3506    reported_cost: Option<u64>,
3507    response_outcome: accounting::ResponseOutcome,
3508}
3509
3510/// One attempt's outcome: an error to report, or a rate limit to wait out.
3511enum Attempt {
3512    Failed(SourceError),
3513    Limited(Limited),
3514    /// GitHub refused a write as a temporary conflict and asked for it again — see
3515    /// [`CONFLICT_WORDINGS`]. Carries what GitHub said, for the diagnostic once retrying ends.
3516    Conflicted(String),
3517}
3518
3519fn plural(count: u32, thing: &str) -> String {
3520    if count == 1 {
3521        format!("{count} {thing}")
3522    } else {
3523        format!("{count} {thing}s")
3524    }
3525}
3526
3527fn seconds(duration: Duration) -> String {
3528    format!("{:.1}s", duration.as_secs_f64())
3529}
3530
3531/// The member [`stamp_served`] writes onto every node of a response that says when it last
3532/// changed: the `Date` that response was served at. No GitHub type has a field of this name.
3533const SERVED_AT: &str = "onetaskgraphServedAt";
3534
3535/// Write `served` onto every object of `data` carrying an `updatedAt`, so whatever reads a
3536/// node's time later knows the server's clock on the response that read it — which is what
3537/// decides whether that node's change token is given (see [`change_token::SETTLED`]).
3538fn stamp_served(data: &mut Value, served: &str) {
3539    match data {
3540        Value::Object(members) => {
3541            if members.contains_key("updatedAt") {
3542                members.insert(SERVED_AT.to_owned(), Value::String(served.to_owned()));
3543            }
3544            for member in members.values_mut() {
3545                stamp_served(member, served);
3546            }
3547        }
3548        Value::Array(items) => {
3549            for item in items {
3550                stamp_served(item, served);
3551            }
3552        }
3553        _ => {}
3554    }
3555}
3556
3557/// A header GitHub spells as a whole number of seconds, or `None` when this one is not.
3558///
3559/// A value that is present and unreadable is deliberately *not* an error. `retry-after` is
3560/// allowed by HTTP to be a date rather than a count, an intermediary can rewrite either
3561/// header, and neither is what makes a response a refusal — so the whole cost of one this
3562/// cannot read is that the refusal carries no hint and the backing-off schedule answers it
3563/// instead. Refusing the response over the header would turn a readable refusal into an
3564/// unreadable one, and refusing to *wait* would be the one wrong direction to fail in.
3565fn whole_seconds(value: Option<&reqwest::header::HeaderValue>) -> Option<u64> {
3566    value
3567        .and_then(|value| value.to_str().ok())
3568        .and_then(|value| value.trim().parse::<u64>().ok())
3569}
3570
3571/// A transport failure with every cause beneath it, outermost first.
3572///
3573/// The client's own text for a request it could not complete is `error sending request for
3574/// url (…)`, and the socket error that says why — a refused or reset connection, an exhausted
3575/// port range, a connection closed before its answer — is only in the chain of sources below
3576/// it. Those differ in what to do next, so all of them are kept.
3577pub(crate) fn transport_error(error: &(dyn std::error::Error + 'static)) -> String {
3578    let mut text = error.to_string();
3579    let mut cause = error.source();
3580    while let Some(next) = cause {
3581        let said = next.to_string();
3582        if !text.ends_with(&said) {
3583            text = format!("{text}: {said}");
3584        }
3585        cause = next.source();
3586    }
3587    text
3588}
3589
3590/// Every mutation this source sends creates content — an issue, a board item, a field of
3591/// one, a sub-issue link, a dependency, a comment — or edits or removes content of that
3592/// kind, and no query in [`graphql::DOCUMENTS`] does, so what the secondary limiter counts
3593/// and what the keyword says are the same set. That is what makes the keyword a sound test
3594/// rather than a convenient one: counting an edit or a removal the limiter might not have
3595/// counted costs a wait, and not counting one it did count costs the next fifty minutes.
3596pub(crate) fn is_mutation(query: &str) -> bool {
3597    query.trim_start().starts_with("mutation")
3598}
3599
3600/// What this source was doing, for a diagnostic that has to say so.
3601///
3602/// Read out of [`graphql::DOCUMENTS`], which is the inventory rather than a copy of it, so
3603/// a document added without a description is caught by that list's own gate instead of
3604/// falling through to the vague arm below.
3605fn operation_description(query: &str) -> &'static str {
3606    let query = graphql::inventoried(query);
3607    graphql::DOCUMENTS
3608        .iter()
3609        .find(|(document, _)| *document == query)
3610        .map_or("talking to GitHub", |(_, doing)| *doing)
3611}
3612
3613/// GitHub's published ceiling on content-generating requests in any one minute.
3614///
3615/// Pinned in `tests/fixtures/rate-limits.json` and gated against it, because it is
3616/// GitHub's number rather than this source's. This source paces at it over its window: a
3617/// content-creating request goes out at once while the minute's creations leave room for it,
3618/// and waits until they do otherwise — see the `pacing` module.
3619pub const CONTENT_CREATION_PER_MINUTE: u64 = 80;
3620/// The same ceiling as GitHub publishes it for any one hour, paced over its window as the
3621/// per-minute one is. Pinned beside its sibling so the gate would notice either one moving.
3622pub const CONTENT_CREATION_PER_HOUR: u64 = 500;
3623/// GitHub's published ceiling on secondary points in any one minute: what every GraphQL
3624/// request is charged against, a mutation [`SECONDARY_POINTS_PER_MUTATION`] and a query
3625/// [`SECONDARY_POINTS_PER_QUERY`]. Pinned and paced as [`CONTENT_CREATION_PER_MINUTE`] is.
3626pub const SECONDARY_POINTS_PER_MINUTE: u64 = 2_000;
3627/// The secondary points one GraphQL request carrying a mutation is charged.
3628pub const SECONDARY_POINTS_PER_MUTATION: u64 = 5;
3629/// The secondary points one GraphQL request carrying no mutation is charged.
3630pub const SECONDARY_POINTS_PER_QUERY: u64 = 1;
3631/// The fastest *steady* spacing of content-creating mutations that cannot exceed
3632/// [`CONTENT_CREATION_PER_MINUTE`], in milliseconds: 60000/80 is 750.
3633///
3634/// It is no longer the default. This source paces by GitHub's windows instead, so a copy's
3635/// few dozen writes go out as fast as GitHub answers them while the minute has room, rather
3636/// than 750 ms apart — which was most of a plan copy's wall time. An installation that wants
3637/// mutations spaced as well says so through `pacing.min_mutation_interval_ms`, and this is the
3638/// value that holds a long sustained burst under the per-minute bound by spacing alone.
3639pub const MIN_MUTATION_INTERVAL_MS: u64 = 60_000 / CONTENT_CREATION_PER_MINUTE;
3640/// First wait when a rate-limit refusal carries no hint; each further wait doubles it.
3641///
3642/// A doubling schedule from one second reaches a minute in six waits, which is GitHub's
3643/// own advice for a secondary limit — wait, and wait longer each time — without spending
3644/// the first minute of a transient refusal doing nothing.
3645pub const RETRY_BACKOFF_MS: u64 = 1_000;
3646/// Total time one call may spend waiting out rate limits before it reports a failure.
3647///
3648/// Two minutes is long enough to ride out the refusals a paced copy still collects and
3649/// short enough that a command an operator is watching returns. The bound is what makes
3650/// the wait a wait rather than a hang: a call refused past it ends in a diagnostic naming
3651/// the limiter, not in a process nobody can tell from a wedged one.
3652pub const RETRY_BUDGET_MS: u64 = 120_000;
3653
3654fn default_token_env() -> String {
3655    "GH_PROJECTS_TOKEN".to_owned()
3656}
3657fn default_endpoint() -> String {
3658    "https://api.github.com/graphql".to_owned()
3659}
3660
3661/// The name of a `Status` single-select option on the board.
3662///
3663/// Validated on the way in rather than checked later, so a blank option name — which
3664/// nothing on a board can be — is a state this type cannot hold.
3665#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3666#[serde(try_from = "String")]
3667#[schemars(extend("minLength" = 1))]
3668pub struct ColumnName(String);
3669
3670impl ColumnName {
3671    /// The option name, as the board spells it.
3672    fn as_str(&self) -> &str {
3673        &self.0
3674    }
3675}
3676
3677impl TryFrom<String> for ColumnName {
3678    type Error = String;
3679
3680    fn try_from(name: String) -> Result<Self, Self::Error> {
3681        if name.trim().is_empty() {
3682            return Err("a status_mapping option name cannot be blank".to_owned());
3683        }
3684        Ok(Self(name))
3685    }
3686}
3687
3688/// The two closed states this product can mean.
3689///
3690/// GitHub's `IssueClosedStateReason` also spells `DUPLICATE`, which nothing here ever writes:
3691/// an issue closed as one *reads* `cancelled`, because its work is another issue's, but this
3692/// product never decides on a person's behalf that two issues are the same work.
3693#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, schemars::JsonSchema)]
3694#[serde(rename_all = "kebab-case")]
3695pub enum ClosedState {
3696    /// `COMPLETED` — precisely done.
3697    Completed,
3698    /// `NOT_PLANNED` — precisely cancelled.
3699    NotPlanned,
3700}
3701
3702impl ClosedState {
3703    const fn reason(self) -> &'static str {
3704        match self {
3705            Self::Completed => "COMPLETED",
3706            Self::NotPlanned => "NOT_PLANNED",
3707        }
3708    }
3709}
3710
3711/// Configuration for one GitHub Projects v2 board.
3712///
3713/// It serializes to a document this same type reads back as itself, so a caller writing a
3714/// configuration — a consumer filing onto a board it configures — can build one here rather
3715/// than spell the shape again; an empty `metadata_fields` is left out, as one never set.
3716#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3717#[serde(default, deny_unknown_fields)]
3718pub struct GitHubProjectsConfig {
3719    /// Login of the user or organization which owns the board.
3720    pub owner: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates GitHub's owner grammar before private construction.
3721    /// The project number shown in the board's GitHub URL.
3722    pub project_number: u32, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` bounds this to a positive GraphQL Int.
3723    // 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.
3724    /// `owner/name` of the repository this source creates an issue in when the item's own
3725    /// `repositories` field does not decide it.
3726    ///
3727    /// An item naming exactly one repository is created there — on a source declared
3728    /// `visibility: private`, only when that repository reads private, and otherwise as an
3729    /// item naming none is; a task or a document naming none or several is created in its
3730    /// parent project's repository; and a project, or a task or document with no parent,
3731    /// naming none or several is created here. A board
3732    /// has no repository of its own and `createIssue` requires one, so a write without
3733    /// this is refused naming the field. Reads never need it.
3734    pub repository: Option<String>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates the `owner/name` grammar before private construction.
3735    // llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate]
3736    /// GitHub logins whose repositories this source may create an issue in.
3737    ///
3738    /// Absent or empty, the default, restricts nothing. Otherwise a create whose issue the
3739    /// rule `repository` describes would file in a repository owned by anyone else is refused
3740    /// before anything of it is written — by `task copy`, `task copy --create`, a member
3741    /// create of a project copy and a dry run of each — with the error kind `creation-owner`,
3742    /// naming the repository and these owners. Logins compare case-insensitively, as GitHub
3743    /// compares them. An update of an issue that already exists is never refused by it.
3744    /// `task locate` reports such a refusal as `creates_in.refused` rather than failing.
3745    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3746    // Kept in the schema as `"default": []` although a serialized configuration leaves an empty
3747    // list out, so both SDKs model an absent list as an empty one rather than as `null`.
3748    #[schemars(!skip_serializing_if)]
3749    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.
3750    /// Environment variable containing a fine-grained token with Projects and Issues
3751    /// read/write plus Pull requests read-only access for every repository represented on
3752    /// the board.
3753    #[serde(default = "default_token_env")]
3754    pub token_env: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates the environment-variable grammar.
3755    /// GraphQL endpoint. GitHub Enterprise installations may override it.
3756    #[serde(default = "default_endpoint")]
3757    pub endpoint: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` converts it to the private validated `Url`.
3758    /// Per-instance mapping from a status category to the option of the board's one
3759    /// `Status` field it lands on, for a task and for a project.
3760    ///
3761    /// The shared `StatusMapping` grammar: each value is one option name for both kinds,
3762    /// `null` to disable the category for both, or `{task, project}` naming it per kind,
3763    /// where a kind left out leaves the category unmapped for that kind. A category this
3764    /// does not mention keeps its shipped default for both kinds: `backlog` to "Backlog",
3765    /// `todo` to "Todo", `queued` to "Queued", `in-progress` to "In Progress", `done` to
3766    /// "Done" plus closed as completed, `cancelled` to "Cancelled" plus closed as not
3767    /// planned, and `draft`, `in-review` and `unknown` unmapped. A category it does mention
3768    /// gets no shipped default for a kind it leaves out. `done` and `cancelled` close the issue for
3769    /// either kind. No two categories may name one option for the same kind, ignoring case.
3770    /// `unknown` may name one existing option; every unknown word then lands on it and
3771    /// reads back as `unknown` under its name. Unlike `local-md`, this source cannot keep
3772    /// each unknown word because it never creates board options.
3773    #[serde(default)]
3774    pub status_mapping: StatusMapping,
3775    /// Per-instance mapping from a task's priority to an option of this board's
3776    /// single-select field named `Priority`.
3777    ///
3778    /// Absent, this source holds no priority: every task reads as `none`, and a write of any
3779    /// other priority is refused before it reaches this board. Present, each of `urgent`,
3780    /// `high`, `medium` and `low` it does not mention keeps its shipped default — `Urgent`,
3781    /// `High`, `Medium` and `Low` — and an item with no value in the `Priority` field reads
3782    /// as `none`, so writing `none` clears the value. Option names match case-insensitively;
3783    /// no two levels may name one option. Reads and writes never create the field or an
3784    /// option: `onetaskgraph sources fields <source> --apply` does, and a write naming one
3785    /// the board lacks is refused pointing there.
3786    #[serde(default)]
3787    pub priority_mapping: Option<PriorityMappingConfig>,
3788    /// Caller metadata values this source also writes to board text fields, so the board can
3789    /// filter on them.
3790    ///
3791    /// Absent or empty, nothing is projected. Each entry names a board text `field`, a
3792    /// top-level metadata `key` and an optional `path` of object keys walked inside that key's
3793    /// value. On every item write — create, update and copy, of a task, a project or a
3794    /// document — a string found there is written to the field, an array of strings as one
3795    /// line per element and an object of string values as one `KEY: VALUE` line per entry in
3796    /// byte order of the keys, shortened to whole lines and a count of the rest past the
3797    /// field's 1,024-byte limit; nothing is sent when the field already holds that text;
3798    /// nothing there, or `null`, clears the field when it holds a value; any other JSON type
3799    /// is refused before any mutation. `docs/metadata.md` states the rule. The metadata comment in the
3800    /// issue body stays the one home of the value, and every read reports metadata from it.
3801    /// Reads and writes never create the field: `onetaskgraph sources fields <source>
3802    /// --apply` does, as a text field, and a write to a board lacking it, or holding a
3803    /// non-text field of that name, is refused pointing there.
3804    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3805    // Kept in the schema as `"default": []` although a serialized configuration leaves an empty
3806    // list out, so both SDKs model an absent list as an empty one rather than as `null`.
3807    #[schemars(!skip_serializing_if)]
3808    pub metadata_fields: Vec<MetadataFieldConfig>,
3809    /// How fast this source writes, and how long it waits out a rate-limit refusal.
3810    ///
3811    /// Every field keeps its shipped default when it is absent, and the defaults are
3812    /// GitHub's own published limits rather than taste. See [`Pacing`].
3813    #[serde(default)]
3814    pub pacing: PacingConfig,
3815    /// What an issue's sub-issues mean on this board.
3816    ///
3817    /// `project`, the default, is this source's meaning since it was first written: an issue
3818    /// with sub-issues reads as a project and its sub-issues as that project's tasks. `parent`
3819    /// reads every issue as a task and a sub-issue as a child under the parent relation, which
3820    /// `task parent set-many` writes and `task relations` reads; a project write to such a
3821    /// source is refused naming this setting. The two meanings answer differently for the same
3822    /// issues, so a `parent` source needs a board of its own: two sources naming one board with
3823    /// different `sub_issues` are refused when the configuration is read.
3824    #[serde(default, skip_serializing_if = "SubIssues::is_project")]
3825    pub sub_issues: SubIssues,
3826    /// The link types this source also writes as GitHub's own `relates-to` relation, beside the
3827    /// store's metadata, so they show in the issue's Relationships panel: each type name mapped
3828    /// to `{"native": "relates-to"}`. A type not named here is kept in metadata alone. Any other
3829    /// word — `blocks`, `blocked-by`, `duplicate`, `similar` among them — is refused when the
3830    /// source is built.
3831    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
3832    // Kept in the schema as `"default": {}` although a serialized configuration leaves an empty
3833    // map out, so both SDKs model an absent map as an empty one rather than as `null`.
3834    #[schemars(!skip_serializing_if)]
3835    pub link_types: BTreeMap<String, onetaskgraph_plugin_api::LinkTypeConfig>,
3836    /// Whether this source's tasks carry the GitHub users each issue is assigned to, and
3837    /// take an assignee write. `false`, the default, reads no issue's assignees and writes
3838    /// none: every request this source sends is then exactly what it was before assignees
3839    /// existed. `true` reads each issue's assignees on the reads it already makes, and writes
3840    /// one person or none — by login — in the `createIssue` or `updateIssue` the write already
3841    /// sends, refusing a person GitHub does not know or leaves off the issue.
3842    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3843    // Kept in the schema as `"default": false` although a serialized configuration leaves a
3844    // `false` out, so both SDKs model an absent setting as `false` rather than as `null`.
3845    #[schemars(!skip_serializing_if)]
3846    pub assignees: bool,
3847}
3848
3849/// What an issue's sub-issues mean on a GitHub Projects board: see
3850/// [`GitHubProjectsConfig::sub_issues`].
3851#[derive(
3852    Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema,
3853)]
3854#[serde(rename_all = "kebab-case")]
3855pub enum SubIssues {
3856    /// An issue with sub-issues is a project, and its sub-issues are its tasks.
3857    #[default]
3858    Project,
3859    /// Every issue is a task, and a sub-issue is a child under the parent relation.
3860    Parent,
3861}
3862
3863impl SubIssues {
3864    /// Whether this is the default meaning, which a serialized configuration leaves out.
3865    #[must_use]
3866    pub const fn is_project(&self) -> bool {
3867        matches!(self, Self::Project)
3868    }
3869}
3870
3871/// Which option of the board's `Priority` field each priority lands on.
3872///
3873/// One member per level rather than a map, so a key that is not a level is refused where
3874/// the configuration is read, naming the levels there are. `none` is not a member: it is no
3875/// value in the field, not an option of it.
3876#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3877#[serde(default, deny_unknown_fields)]
3878pub struct PriorityMappingConfig {
3879    /// The option `urgent` lands on; `Urgent` when absent.
3880    pub urgent: Option<PriorityOptionName>,
3881    /// The option `high` lands on; `High` when absent.
3882    pub high: Option<PriorityOptionName>,
3883    /// The option `medium` lands on; `Medium` when absent.
3884    pub medium: Option<PriorityOptionName>,
3885    /// The option `low` lands on; `Low` when absent.
3886    pub low: Option<PriorityOptionName>,
3887}
3888
3889/// The name of an option of the board's `Priority` single-select field.
3890///
3891/// Validated on the way in, for the reason [`ColumnName`] is: nothing on a board can have a
3892/// blank name.
3893#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3894#[serde(try_from = "String")]
3895#[schemars(extend("minLength" = 1))]
3896pub struct PriorityOptionName(String);
3897
3898impl PriorityOptionName {
3899    /// The option name, as the board spells it.
3900    fn as_str(&self) -> &str {
3901        &self.0
3902    }
3903}
3904
3905impl TryFrom<String> for PriorityOptionName {
3906    type Error = String;
3907
3908    fn try_from(name: String) -> Result<Self, Self::Error> {
3909        if name.trim().is_empty() {
3910            return Err("a priority_mapping option name cannot be blank".to_owned());
3911        }
3912        Ok(Self(name))
3913    }
3914}
3915
3916/// The name of the board field a priority is held in.
3917pub const PRIORITY_FIELD: &str = "Priority";
3918
3919/// The four priorities a board option can hold, in the order a new `Priority` field lists
3920/// them. `none` is not among them: it is the field holding no value.
3921///
3922/// This list mirrors `Priority`, so it carries its own drift gate, in the shape [`CATEGORIES`]
3923/// does: [`level_position`] is a wildcard-free match, so a priority added to the shared
3924/// vocabulary fails to compile until it is placed there, and this crate's suite reconciles
3925/// this list and [`PriorityMappingConfig`]'s members against that enum's own derived schema.
3926pub const PRIORITY_LEVELS: [Priority; 4] = [
3927    Priority::Urgent,
3928    Priority::High,
3929    Priority::Medium,
3930    Priority::Low,
3931];
3932
3933/// Where one priority sits in [`PRIORITY_LEVELS`], or `None` for `none`, which is no option;
3934/// see that list for what this pins.
3935#[must_use]
3936pub const fn level_position(priority: Priority) -> Option<usize> {
3937    match priority {
3938        Priority::None => None,
3939        Priority::Urgent => Some(0),
3940        Priority::High => Some(1),
3941        Priority::Medium => Some(2),
3942        Priority::Low => Some(3),
3943    }
3944}
3945
3946/// This instance's complete priority-to-option mapping, read in both directions.
3947///
3948/// One option per level, held in [`PRIORITY_LEVELS`] order, once it is established that no
3949/// two levels name one option.
3950#[derive(Debug, Clone)]
3951struct PriorityMapping {
3952    options: [PriorityOptionName; 4],
3953}
3954
3955impl PriorityMapping {
3956    fn resolve(config: PriorityMappingConfig, instance: &SourceName) -> Result<Self, SourceError> {
3957        let shipped = |name: &str| PriorityOptionName(name.to_owned());
3958        let mapping = Self {
3959            options: [
3960                config.urgent.unwrap_or_else(|| shipped("Urgent")),
3961                config.high.unwrap_or_else(|| shipped("High")),
3962                config.medium.unwrap_or_else(|| shipped("Medium")),
3963                config.low.unwrap_or_else(|| shipped("Low")),
3964            ],
3965        };
3966        for (index, option) in mapping.options.iter().enumerate() {
3967            if let Some(earlier) = mapping.options[..index]
3968                .iter()
3969                .position(|other| other.as_str().eq_ignore_ascii_case(option.as_str()))
3970            {
3971                return Err(SourceError::Config {
3972                    message: format!(
3973                        "priority_mapping of source {instance} sends both {} and {} to the board \
3974                         option {:?}; one option cannot read back as two priorities",
3975                        PRIORITY_LEVELS[earlier],
3976                        PRIORITY_LEVELS[index],
3977                        option.as_str()
3978                    ),
3979                });
3980            }
3981        }
3982        Ok(mapping)
3983    }
3984
3985    /// The option `priority` lands on, or `None` for `none`, which is no option at all.
3986    fn option(&self, priority: Priority) -> Option<&str> {
3987        level_position(priority).map(|index| self.options[index].as_str())
3988    }
3989
3990    /// The priority a board option name reports, or `None` when nothing maps to it.
3991    fn priority_of(&self, option: &str) -> Option<Priority> {
3992        self.options
3993            .iter()
3994            .position(|name| name.as_str().eq_ignore_ascii_case(option))
3995            .map(|index| PRIORITY_LEVELS[index])
3996    }
3997
3998    /// Every mapped option name, in the order a new `Priority` field lists them.
3999    fn names(&self) -> impl Iterator<Item = &str> {
4000        self.options.iter().map(PriorityOptionName::as_str)
4001    }
4002}
4003
4004/// One metadata value this source projects onto a board text field.
4005#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
4006#[serde(deny_unknown_fields)]
4007pub struct MetadataFieldConfig {
4008    /// The name of the board text field the value is written to.
4009    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.
4010    /// The top-level metadata key the value is read from. A key under the reserved
4011    /// `onetaskgraph.` prefix is refused.
4012    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.
4013    /// Object keys walked inside that key's value, outermost first. Absent or empty, the
4014    /// key's own value is the one projected. Left out of a serialized entry when empty.
4015    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4016    // Kept in the schema as `"default": []`, for the reason `metadata_fields`' is.
4017    #[schemars(!skip_serializing_if)]
4018    pub path: Vec<String>,
4019}
4020
4021/// The board fields no metadata value may be projected onto, compared ignoring case: the
4022/// three this source writes itself, and those GitHub owns on every board.
4023// 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.
4024const UNPROJECTABLE_FIELDS: [&str; 13] = [
4025    STATUS_FIELD,
4026    PRIORITY_FIELD,
4027    ORIGIN_FIELD,
4028    "Title",
4029    "Assignees",
4030    "Labels",
4031    "Linked pull requests",
4032    "Milestone",
4033    "Repository",
4034    "Reviewers",
4035    "Parent issue",
4036    "Sub-issues progress",
4037    "Type",
4038];
4039
4040/// One validated [`MetadataFieldConfig`] entry.
4041#[derive(Debug, Clone)]
4042struct MetadataField {
4043    field: ProjectedField,
4044    key: ProjectedKey,
4045    path: Vec<String>,
4046}
4047
4048/// The name of a board text field a metadata value is projected onto: never blank, never one
4049/// this source or GitHub writes, and never one another entry of the same source names.
4050#[derive(Debug, Clone, PartialEq, Eq)]
4051struct ProjectedField(String);
4052
4053/// The top-level metadata key a projected value is read from: never blank, and never under
4054/// the namespace this product reserves.
4055#[derive(Debug, Clone, PartialEq, Eq)]
4056struct ProjectedKey(String);
4057
4058impl std::ops::Deref for ProjectedField {
4059    type Target = str;
4060    fn deref(&self) -> &str {
4061        &self.0
4062    }
4063}
4064
4065impl std::ops::Deref for ProjectedKey {
4066    type Target = str;
4067    fn deref(&self) -> &str {
4068        &self.0
4069    }
4070}
4071
4072/// What one item's metadata says one projected field should hold.
4073#[derive(Debug, Clone, PartialEq, Eq)]
4074enum Projected {
4075    /// A string to hold.
4076    Text(String),
4077    /// Nothing: the key or a step of the path is absent, or the value is `null`.
4078    Nothing,
4079}
4080
4081impl MetadataField {
4082    /// Validate every entry of one instance's `metadata_fields`, refusing the first that
4083    /// cannot stand, naming the source and the entry.
4084    fn resolve(
4085        configured: Vec<MetadataFieldConfig>,
4086        instance: &SourceName,
4087    ) -> Result<Vec<Self>, SourceError> {
4088        let mut resolved: Vec<Self> = Vec::with_capacity(configured.len());
4089        for (index, entry) in configured.into_iter().enumerate() {
4090            let refuse = |why: String| SourceError::Config {
4091                message: format!(
4092                    "metadata_fields[{index}] of source {instance} (field {:?}, key {:?}) {why}",
4093                    entry.field, entry.key
4094                ),
4095            };
4096            if let Some(why) = ProjectedValue::entry_refusal(
4097                &entry.field,
4098                &entry.key,
4099                resolved.iter().map(|other| &*other.field),
4100                "board field",
4101            ) {
4102                return Err(refuse(why));
4103            }
4104            if let Some(owned) = UNPROJECTABLE_FIELDS
4105                .iter()
4106                .find(|owned| owned.eq_ignore_ascii_case(&entry.field))
4107            {
4108                return Err(refuse(format!(
4109                    "names the board field {owned:?}, which this source or GitHub already \
4110                     writes; next: name a text field of your own"
4111                )));
4112            }
4113            resolved.push(Self {
4114                field: ProjectedField(entry.field),
4115                key: ProjectedKey(entry.key),
4116                path: entry.path,
4117            });
4118        }
4119        Ok(resolved)
4120    }
4121
4122    /// The path as a refusal spells it: `[]` for the key's own value.
4123    fn spelled_path(&self) -> String {
4124        serde_json::to_string(&self.path).unwrap_or_else(|_| format!("{:?}", self.path))
4125    }
4126
4127    /// What `metadata` says this field should hold, or the refusal for a value no text field
4128    /// can hold.
4129    fn projected(
4130        &self,
4131        metadata: &BTreeMap<String, Value>,
4132        instance: &SourceName,
4133    ) -> Result<Projected, SourceError> {
4134        let found = match ProjectedValue::read(metadata, &self.key, &self.path) {
4135            Ok(None) => return Ok(Projected::Nothing),
4136            Ok(Some(value)) => return Ok(Projected::Text(field_text(&value))),
4137            Err(found) => found,
4138        };
4139        Err(SourceError::Refused {
4140            message: format!(
4141                "source {instance} projects metadata key {:?} at path {} onto its board text \
4142                 field {:?}, and this item holds {found} there; only a string, an array of \
4143                 strings, an object of string values, null or nothing can be written to a text \
4144                 field; next: store one of those there, or remove the value",
4145                &*self.key,
4146                self.spelled_path(),
4147                &*self.field
4148            ),
4149        })
4150    }
4151}
4152
4153/// The most a ProjectV2 text field holds, in UTF-8 bytes.
4154///
4155/// Spike `spike-sample-ticket` measured it on a live board through this store with ASCII
4156/// values: 1,024 accepted, 1,025 refused whole with `Column value must be a valid value for
4157/// text column`, and nothing on the item changed. GitHub documents neither the limit nor its
4158/// unit, so this source counts UTF-8 bytes — at least as many as characters or UTF-16 units —
4159/// which can only shorten a non-ASCII value earlier than GitHub would, never send one it
4160/// refuses.
4161// 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.
4162pub const TEXT_FIELD_LIMIT: usize = 1024;
4163
4164/// The text a board text field holds for `value`, as `docs/metadata.md` states it: a string as
4165/// itself, an array's elements and an object's `KEY: VALUE` entries — in byte order of the
4166/// keys — one per line, joined by one line feed; and, over [`TEXT_FIELD_LIMIT`], the longest
4167/// prefix of whole lines that fits beside one line feed and the line counting the rest.
4168fn field_text(value: &ProjectedValue) -> String {
4169    let rendered = match value {
4170        ProjectedValue::Text(text) => text.clone(),
4171        ProjectedValue::List(list) => list.join("\n"),
4172        ProjectedValue::Map(map) => map
4173            .iter()
4174            .map(|(key, value)| format!("{key}: {value}"))
4175            .collect::<Vec<_>>()
4176            .join("\n"),
4177    };
4178    if rendered.len() <= TEXT_FIELD_LIMIT {
4179        return rendered;
4180    }
4181    let lines: Vec<&str> = rendered.split('\n').collect();
4182    let elided = |left_out: usize| {
4183        let noun = if left_out == 1 { "line" } else { "lines" };
4184        format!("\u{2026} {left_out} more {noun} in this item's metadata")
4185    };
4186    // The bytes the first `kept` lines take with the line feeds between them.
4187    let mut prefix = 0;
4188    let mut fits = 0;
4189    for (kept, line) in lines.iter().enumerate().map(|(at, line)| (at + 1, line)) {
4190        prefix += line.len() + usize::from(kept > 1);
4191        if kept == lines.len() || prefix + 1 + elided(lines.len() - kept).len() > TEXT_FIELD_LIMIT {
4192            break;
4193        }
4194        fits = kept;
4195    }
4196    if fits == 0 {
4197        return elided(lines.len());
4198    }
4199    format!(
4200        "{}\n{}",
4201        lines[..fits].join("\n"),
4202        elided(lines.len() - fits)
4203    )
4204}
4205
4206/// What one item's `Priority` field says, read through this instance's mapping.
4207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
4208enum HeldPriority {
4209    /// A priority this source reports: an option the mapping names, or no value (`none`).
4210    Read(Priority),
4211    /// An option the mapping does not name, which is never read as a level or as `none`.
4212    Unmapped(String),
4213}
4214
4215/// How fast this source writes, and how long it waits out a rate-limit refusal.
4216///
4217/// Configurable because a GitHub Enterprise installation sets its own limits and an
4218/// operator who has already been refused may want to go slower still — not because the
4219/// defaults are guesses.
4220#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
4221#[serde(default, deny_unknown_fields)]
4222pub struct PacingConfig {
4223    /// Shortest interval between two content-creating mutations, in milliseconds.
4224    ///
4225    /// Zero sends them as fast as they are asked for, which is what a fixture server on
4226    /// loopback wants and what no board on github.com does. At most [`MAX_PACING_MS`].
4227    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.
4228    /// First wait when a rate-limit refusal carries no hint, in milliseconds. Each
4229    /// further wait of the same call doubles it. At most [`MAX_PACING_MS`], and never
4230    /// zero while there is a budget to spend, because a schedule of zero-length waits
4231    /// consumes none of it and so never ends.
4232    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.
4233    /// Total time one call may spend waiting out rate limits, in milliseconds.
4234    ///
4235    /// Zero reports the refusal rather than waiting at all. At most [`MAX_PACING_MS`]:
4236    /// the bound is what makes this a wait rather than a hang.
4237    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.
4238}
4239
4240/// The largest any pacing setting may be, in milliseconds.
4241///
4242/// One hour. GitHub's own harshest published bound on content-generating requests works
4243/// out at one every 7.2 seconds, so an hour is already three orders of magnitude past
4244/// anything a real limit asks for, and past it the settings stop describing pacing at all:
4245/// a wait budget beyond it is the unbounded wait this whole mechanism exists to replace,
4246/// and an interval beyond it is a command that never sends its second mutation. It also
4247/// keeps the clock arithmetic in [`GitHubProjectsSource::reserve_mutation_slot`] inside
4248/// what a `Duration` can hold on every platform.
4249pub const MAX_PACING_MS: u64 = 3_600_000;
4250
4251/// [`PacingConfig`] with every default resolved and every value checked, which is what the
4252/// source holds.
4253///
4254/// Unset, `min_mutation_interval_ms` spaces nothing, and every request is paced by GitHub's
4255/// secondary windows alone — see the `pacing` module; set, it spaces content-creating mutations
4256/// on top of those windows, [`MIN_MUTATION_INTERVAL_MS`] being the spacing that holds a sustained
4257/// burst under the per-minute bound by spacing alone; and zero sends every request as fast as it
4258/// is asked for, windows included.
4259#[derive(Debug, Clone, Copy)]
4260struct Pacing {
4261    /// Whether requests are held for GitHub's secondary windows: always, unless
4262    /// `min_mutation_interval_ms` is set to exactly zero, which has always asked for no
4263    /// pacing at all — what a fixture server on loopback wants and no board on github.com does.
4264    windows: bool,
4265    min_mutation_interval: Duration,
4266    retry_backoff: Duration,
4267    retry_budget: Duration,
4268}
4269
4270impl Pacing {
4271    /// Resolve one instance's pacing, refusing a configuration that would not pace at all.
4272    fn resolve(config: PacingConfig, instance: &SourceName) -> Result<Self, SourceError> {
4273        let bounded = |value: Option<u64>, default: u64, field: &str| match value {
4274            Some(value) if value > MAX_PACING_MS => Err(SourceError::Config {
4275                message: format!(
4276                    "pacing.{field} of source {instance} is {value} ms, and the most any pacing \
4277                     setting may be is {MAX_PACING_MS} ms — an hour, which is already far past \
4278                     GitHub's own harshest published limit"
4279                ),
4280            }),
4281            Some(value) => Ok(Duration::from_millis(value)),
4282            None => Ok(Duration::from_millis(default)),
4283        };
4284        let retry_backoff = bounded(
4285            config.retry_backoff_ms,
4286            RETRY_BACKOFF_MS,
4287            "retry_backoff_ms",
4288        )?;
4289        let retry_budget = bounded(config.retry_budget_ms, RETRY_BUDGET_MS, "retry_budget_ms")?;
4290        if retry_backoff.is_zero() && !retry_budget.is_zero() {
4291            return Err(SourceError::Config {
4292                message: format!(
4293                    "pacing.retry_backoff_ms of source {instance} is 0 while \
4294                     pacing.retry_budget_ms is {} ms; a schedule of zero-length waits spends \
4295                     none of that budget, so it would retry a refusal forever. Set a backoff of \
4296                     at least 1 ms, or set retry_budget_ms to 0 to report a refusal without \
4297                     waiting at all",
4298                    retry_budget.as_millis()
4299                ),
4300            });
4301        }
4302        Ok(Self {
4303            windows: config.min_mutation_interval_ms != Some(0),
4304            min_mutation_interval: bounded(
4305                config.min_mutation_interval_ms,
4306                0,
4307                "min_mutation_interval_ms",
4308            )?,
4309            retry_backoff,
4310            retry_budget,
4311        })
4312    }
4313}
4314
4315/// Factory for [`GitHubProjectsSource`].
4316#[derive(Debug, Clone, Copy, Default)]
4317pub struct Plugin;
4318
4319impl SourcePlugin for Plugin {
4320    fn kind(&self) -> &'static str {
4321        KIND
4322    }
4323    /// The endpoint, the owner and the board's number: what names one board.
4324    fn remote_identity(&self, config: &Value) -> Option<String> {
4325        let config: GitHubProjectsConfig = serde_json::from_value(config.clone()).ok()?;
4326        Some(format!(
4327            "{}\n{}\n{}",
4328            config.endpoint, config.owner, config.project_number
4329        ))
4330    }
4331    fn config_schema(&self) -> Schema {
4332        schema_for!(GitHubProjectsConfig)
4333    }
4334    fn build(
4335        &self,
4336        name: &SourceName,
4337        config: &Value,
4338        secrets: &dyn SecretResolver,
4339    ) -> Result<Box<dyn TaskSource>, SourceError> {
4340        self.build_recording_into(name, config, secrets, Arc::new(Accounting::new()))
4341    }
4342
4343    fn build_with_clock(
4344        &self,
4345        name: &SourceName,
4346        config: &Value,
4347        secrets: &dyn SecretResolver,
4348        clock: SharedClock,
4349    ) -> Result<Box<dyn TaskSource>, SourceError> {
4350        self.build_recording_with_clock(name, config, secrets, Arc::new(Accounting::new()), clock)
4351    }
4352}
4353
4354/// The client `cell` holds, building it with `build` the first time it is asked for.
4355///
4356/// A failed build is the request's failure, with the message the source's construction gave it
4357/// before clients were deferred.
4358// 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`.
4359fn built(
4360    cell: &std::sync::OnceLock<Client>,
4361    build: impl FnOnce() -> Result<Client, SourceError>,
4362) -> Result<&Client, SourceError> {
4363    if let Some(client) = cell.get() {
4364        return Ok(client);
4365    }
4366    let client = build()?;
4367    Ok(cell.get_or_init(|| client))
4368}
4369
4370impl Plugin {
4371    /// Build a source recording every request it sends into an accounting the caller holds.
4372    ///
4373    /// [`SourcePlugin::build`] is this with an accounting of its own, which is what the
4374    /// registry gets. This is for a caller that is also calling GitHub itself and wants one
4375    /// session total rather than two — see [`accounting`] and
4376    /// [`GitHubProjectsSource::recording_into`].
4377    ///
4378    /// # Errors
4379    ///
4380    /// Exactly [`SourcePlugin::build`]'s, with the same source name in front of each:
4381    /// [`SourceError::Config`] for configuration this plugin cannot use and
4382    /// [`SourceError::Auth`] for a credential it cannot find.
4383    pub fn build_recording_into(
4384        &self,
4385        name: &SourceName,
4386        config: &Value,
4387        secrets: &dyn SecretResolver,
4388        ledger: Arc<Accounting>,
4389    ) -> Result<Box<dyn TaskSource>, SourceError> {
4390        self.build_recording_with_clock(name, config, secrets, ledger, system_clock())
4391    }
4392
4393    fn build_recording_with_clock(
4394        &self,
4395        name: &SourceName,
4396        config: &Value,
4397        secrets: &dyn SecretResolver,
4398        ledger: Arc<Accounting>,
4399        clock: SharedClock,
4400    ) -> Result<Box<dyn TaskSource>, SourceError> {
4401        let config: GitHubProjectsConfig =
4402            serde_json::from_value(config.clone()).map_err(|e| SourceError::Config {
4403                message: format!("source {name}: {e}"),
4404            })?;
4405        let prefix = format!("source {name}: ");
4406        let mut source = GitHubProjectsSource::recording_into(name, config, secrets, ledger)
4407            .map_err(|error| match error {
4408                // The shared `StatusMapping::distinct` names the source itself.
4409                SourceError::Config { message } if message.starts_with(&prefix) => {
4410                    SourceError::Config { message }
4411                }
4412                SourceError::Config { message } => SourceError::Config {
4413                    message: format!("{prefix}{message}"),
4414                },
4415                SourceError::Auth { message } => SourceError::Auth {
4416                    message: format!("source {name}: {message}"),
4417                },
4418                other => other,
4419            })?;
4420        source.clock = clock;
4421        Ok(Box::new(source))
4422    }
4423}
4424
4425/// Where a status category lands on this board, once configuration is resolved.
4426#[derive(Debug, Clone, PartialEq, Eq)]
4427enum StatusTarget {
4428    /// Not usable against this instance for this kind, and why.
4429    Disabled(UnmappedStatus),
4430    /// The board's `Status` option of this name.
4431    Column(ColumnName),
4432    /// A closed issue, with both its board option and the reason that says which closed it means.
4433    // 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.
4434    Terminal(ColumnName, ClosedState),
4435}
4436
4437/// Every status category, in the order the vocabulary declares them.
4438///
4439/// This list mirrors `StatusCategory`, so it carries its own drift gate rather than a
4440/// reviewer's attention: [`category_position`] is a wildcard-free match, so a variant
4441/// added to the shared vocabulary fails to compile until it is named there, and this
4442/// crate's suite reconciles this list against that enum's own derived schema, which is
4443/// generated from the variants rather than written beside them. The schema is what
4444/// catches a list left one short — a list checking only the positions it already holds
4445/// would pass while every mapping indexed by the new position panicked.
4446pub const CATEGORIES: [StatusCategory; 9] = [
4447    StatusCategory::Draft,
4448    StatusCategory::Backlog,
4449    StatusCategory::Todo,
4450    StatusCategory::Queued,
4451    StatusCategory::InProgress,
4452    StatusCategory::InReview,
4453    StatusCategory::Done,
4454    StatusCategory::Cancelled,
4455    StatusCategory::Unknown,
4456];
4457
4458/// Where one category sits in [`CATEGORIES`]; see that list for what this pins.
4459#[must_use]
4460pub const fn category_position(category: StatusCategory) -> usize {
4461    match category {
4462        StatusCategory::Draft => 0,
4463        StatusCategory::Backlog => 1,
4464        StatusCategory::Todo => 2,
4465        StatusCategory::Queued => 3,
4466        StatusCategory::InProgress => 4,
4467        StatusCategory::InReview => 5,
4468        StatusCategory::Done => 6,
4469        StatusCategory::Cancelled => 7,
4470        StatusCategory::Unknown => 8,
4471    }
4472}
4473
4474/// The spelling a status category is configured and reported under.
4475fn category_name(category: StatusCategory) -> &'static str {
4476    match category {
4477        StatusCategory::Draft => "draft",
4478        StatusCategory::Backlog => "backlog",
4479        StatusCategory::Todo => "todo",
4480        StatusCategory::Queued => "queued",
4481        StatusCategory::InProgress => "in-progress",
4482        StatusCategory::InReview => "in-review",
4483        StatusCategory::Done => "done",
4484        StatusCategory::Cancelled => "cancelled",
4485        StatusCategory::Unknown => "unknown",
4486    }
4487}
4488
4489/// A shipped default's option name.
4490///
4491/// The literals below are this file's own and non-blank, and they are validated by the
4492/// one constructor a configured name goes through rather than beside it.
4493fn shipped_column(name: &'static str) -> ColumnName {
4494    ColumnName::try_from(name.to_owned()).expect("a shipped default names a board option")
4495}
4496
4497/// The shipped default for one category this instance's `status_mapping` does not mention,
4498/// for either kind.
4499fn shipped_default(category: StatusCategory) -> StatusTarget {
4500    match category {
4501        StatusCategory::Backlog => StatusTarget::Column(shipped_column("Backlog")),
4502        StatusCategory::Todo => StatusTarget::Column(shipped_column("Todo")),
4503        StatusCategory::Queued => StatusTarget::Column(shipped_column("Queued")),
4504        StatusCategory::InProgress => StatusTarget::Column(shipped_column("In Progress")),
4505        StatusCategory::Done => {
4506            StatusTarget::Terminal(shipped_column("Done"), ClosedState::Completed)
4507        }
4508        StatusCategory::Cancelled => {
4509            StatusTarget::Terminal(shipped_column("Cancelled"), ClosedState::NotPlanned)
4510        }
4511        // No board ships a review column, so `in-review` is written and read only where a
4512        // mapping names one, and a board without it reads exactly as before.
4513        StatusCategory::Draft | StatusCategory::InReview | StatusCategory::Unknown => {
4514            StatusTarget::Disabled(UnmappedStatus::Unconfigured)
4515        }
4516    }
4517}
4518
4519/// The two kinds a status is written and read for, each with its own half of the mapping.
4520const STATUS_KINDS: [ItemKind; 2] = [ItemKind::Task, ItemKind::Project];
4521
4522/// This instance's complete category-to-target mapping for each kind, read in both
4523/// directions.
4524///
4525/// One target per category per kind, held at that category's own [`category_position`], so
4526/// a category missing from the mapping, named twice in it, or filed out of order is a state
4527/// this type cannot hold rather than one [`Self::target`] has to defend against. Both kinds'
4528/// targets are options of the board's one `Status` field.
4529#[derive(Debug, Clone)]
4530struct BoardStatuses {
4531    tasks: [StatusTarget; CATEGORIES.len()],
4532    projects: [StatusTarget; CATEGORIES.len()],
4533}
4534
4535impl BoardStatuses {
4536    /// Resolve `configured` against the shipped defaults, refusing two categories one kind
4537    /// would read back from one option.
4538    ///
4539    /// A category the mapping does not mention keeps its shipped default for both kinds; one
4540    /// it does mention is exactly what it configures, so a per-kind object leaves the kind it
4541    /// omits unmapped rather than defaulted.
4542    fn resolve(configured: &StatusMapping, instance: &SourceName) -> Result<Self, SourceError> {
4543        let resolve_kind =
4544            |kind: ItemKind| -> Result<[StatusTarget; CATEGORIES.len()], SourceError> {
4545                // `CATEGORIES[position] == category` for every category — the crate's suite
4546                // asserts it — so mapping the list in order fills each category's own slot.
4547                let mut targets = CATEGORIES.map(shipped_default);
4548                for (slot, category) in targets.iter_mut().zip(CATEGORIES) {
4549                    if !configured.mentions(category) {
4550                        continue;
4551                    }
4552                    *slot = match configured.name_for(category, kind) {
4553                        Err(why) => StatusTarget::Disabled(why),
4554                        Ok(name) => {
4555                            let option = ColumnName::try_from(name.as_str().to_owned())
4556                                .map_err(|message| SourceError::Config { message })?;
4557                            match category {
4558                                StatusCategory::Done => {
4559                                    StatusTarget::Terminal(option, ClosedState::Completed)
4560                                }
4561                                StatusCategory::Cancelled => {
4562                                    StatusTarget::Terminal(option, ClosedState::NotPlanned)
4563                                }
4564                                _ => StatusTarget::Column(option),
4565                            }
4566                        }
4567                    };
4568                }
4569                StatusMapping::distinct(
4570                    instance,
4571                    kind,
4572                    CATEGORIES
4573                        .iter()
4574                        .zip(&targets)
4575                        .filter_map(|(category, target)| target.option().map(|o| (*category, o))),
4576                )?;
4577                Ok(targets)
4578            };
4579        Ok(Self {
4580            tasks: resolve_kind(ItemKind::Task)?,
4581            projects: resolve_kind(ItemKind::Project)?,
4582        })
4583    }
4584
4585    /// Every category's target for `kind`, in category order.
4586    const fn targets(&self, kind: ItemKind) -> &[StatusTarget; CATEGORIES.len()] {
4587        match kind {
4588            ItemKind::Task => &self.tasks,
4589            ItemKind::Project => &self.projects,
4590        }
4591    }
4592
4593    fn target(&self, kind: ItemKind, category: StatusCategory) -> &StatusTarget {
4594        &self.targets(kind)[category_position(category)]
4595    }
4596
4597    /// The category a board option name reports for `kind`, or `None` when nothing of that
4598    /// kind maps to it.
4599    fn category_of(&self, kind: ItemKind, option: &str) -> Option<StatusCategory> {
4600        CATEGORIES.into_iter().find(|category| {
4601            self.target(kind, *category)
4602                .option()
4603                .is_some_and(|name| name.eq_ignore_ascii_case(option))
4604        })
4605    }
4606
4607    /// Every option name either kind maps a category to, each once ignoring case, in
4608    /// category order with a task's name before a project's — what the guarded setup asks
4609    /// the `Status` field to hold.
4610    fn wanted(&self) -> Vec<String> {
4611        let mut wanted: Vec<String> = Vec::new();
4612        for category in CATEGORIES {
4613            for kind in STATUS_KINDS {
4614                if let Some(name) = self.target(kind, category).option()
4615                    && !wanted.iter().any(|held| held.eq_ignore_ascii_case(name))
4616                {
4617                    wanted.push(name.to_owned());
4618                }
4619            }
4620        }
4621        wanted
4622    }
4623
4624    /// The status an item of `kind` reports, from the three things a read of it says: its
4625    /// board `Status` option, whether its issue is closed, and the reason it was closed with.
4626    ///
4627    /// **A closed issue's category follows its closure**, by [`closed_category`]: completed
4628    /// or no reason reads `done`, not planned and duplicate read `cancelled`, and any other
4629    /// reason reads `unknown`. `REOPENED`-while-closed is a state this source can never
4630    /// produce, so it is read permissively rather than refused — reads are faithful, and
4631    /// refusals belong on writes.
4632    ///
4633    /// **Its name follows the closure too, unless the option agrees with it.** The option's
4634    /// own name is kept when this kind's mapping reads that option as the same category, or
4635    /// does not name it at all — so a closed issue in a "Shipped" column reports `done`
4636    /// named `Shipped`. An option the mapping reads as another category contradicts the
4637    /// closure, and so does no option at all: the name is then the option the mapping gives
4638    /// the closure's category, so an issue closed as completed at `Todo` reads `done` named
4639    /// by the board's `done` option, and a destination reading `Todo` as todo is never handed
4640    /// it. An `unknown` closure keeps the option, or `Closed` without one.
4641    ///
4642    /// An open item's option reads through its own kind's mapping, and an option that mapping
4643    /// does not name reads as `Unknown` under its own name.
4644    ///
4645    /// One function of those three rather than of a response, so a narrow status write can
4646    /// answer what a re-read would report by applying it to the state it has just written.
4647    fn status(
4648        &self,
4649        kind: ItemKind,
4650        option: Option<&str>,
4651        closed: bool,
4652        reason: Option<&str>,
4653    ) -> Status {
4654        if closed {
4655            let category = closed_category(reason);
4656            let agrees = option.filter(|option| {
4657                category == StatusCategory::Unknown
4658                    || self
4659                        .category_of(kind, option)
4660                        .is_none_or(|read| read == category)
4661            });
4662            let name = agrees.or_else(|| self.target(kind, category).option());
4663            let fallback = match category {
4664                StatusCategory::Done => "Done",
4665                StatusCategory::Cancelled => "Cancelled",
4666                _ => "Closed",
4667            };
4668            return Status {
4669                category,
4670                name: name.or(option).unwrap_or(fallback).to_owned(),
4671            };
4672        }
4673        let name = option.unwrap_or("Open").to_owned();
4674        Status {
4675            category: self
4676                .category_of(kind, &name)
4677                .unwrap_or(StatusCategory::Unknown),
4678            name,
4679        }
4680    }
4681
4682    /// The option a closed item's `Status` has to hold for its card to agree with its
4683    /// closure, and the category that closure reads as — or `None` when the item is open,
4684    /// its closure reads `unknown`, or its option already agrees.
4685    ///
4686    /// What `task status reconcile` writes: only `done` and `cancelled` closures are brought
4687    /// in line, each to the one option the mapping gives its category — an item with no
4688    /// option, or at one the mapping does not name, included.
4689    fn contradicted(
4690        &self,
4691        kind: ItemKind,
4692        option: Option<&str>,
4693        closed: bool,
4694        reason: Option<&str>,
4695    ) -> Option<(ClosedAs, &str)> {
4696        if !closed {
4697            return None;
4698        }
4699        let closed_as = match closed_category(reason) {
4700            StatusCategory::Done => ClosedAs::Done,
4701            StatusCategory::Cancelled => ClosedAs::Cancelled,
4702            _ => return None,
4703        };
4704        let wanted = self.target(kind, closed_as.category()).option()?;
4705        if option.is_some_and(|option| option.eq_ignore_ascii_case(wanted)) {
4706            return None;
4707        }
4708        Some((closed_as, wanted))
4709    }
4710}
4711
4712/// The category a closed issue reads as, from the reason it was closed with.
4713///
4714/// `COMPLETED`, and no reason at all, is finished work; `NOT_PLANNED` and `DUPLICATE` are both
4715/// work nobody will do here — a duplicate's work is the other issue's — and any other reason
4716/// is one this source cannot read a category from.
4717fn closed_category(reason: Option<&str>) -> StatusCategory {
4718    match reason {
4719        None | Some("COMPLETED") => StatusCategory::Done,
4720        Some("NOT_PLANNED" | "DUPLICATE") => StatusCategory::Cancelled,
4721        Some(_) => StatusCategory::Unknown,
4722    }
4723}
4724
4725impl BoardStatuses {
4726    /// For each kind, the option names it maps a category to that `existing` lacks, ignoring
4727    /// case; a kind lacking none is left out.
4728    fn missing_by_kind(&self, existing: &[StatusOption]) -> Vec<KindMissing> {
4729        STATUS_KINDS
4730            .into_iter()
4731            .filter_map(|kind| {
4732                let missing: Vec<String> = self
4733                    .targets(kind)
4734                    .iter()
4735                    .filter_map(StatusTarget::option)
4736                    .filter(|wanted| {
4737                        !existing
4738                            .iter()
4739                            .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
4740                    })
4741                    .map(str::to_owned)
4742                    .collect();
4743                (!missing.is_empty()).then_some(KindMissing { kind, missing })
4744            })
4745            .collect()
4746    }
4747}
4748
4749impl StatusTarget {
4750    /// The board option this target selects, or `None` for an unmapped one.
4751    fn option(&self) -> Option<&str> {
4752        match self {
4753            Self::Column(name) | Self::Terminal(name, _) => Some(name.as_str()),
4754            Self::Disabled(_) => None,
4755        }
4756    }
4757}
4758
4759// 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.
4760/// One repository this source can create an issue in, as `owner/name`.
4761///
4762/// Every `createIssue` this source sends names one of these: the item's own single
4763/// `repositories` entry — on a source declared private, only when it reads private — else
4764/// its parent project issue's repository, else the configured
4765/// [`GitHubProjectsConfig::repository`]. [`GitHubProjectsSource::creation_target`] makes
4766/// that choice and says what it refuses before `createIssue`.
4767// llmlint: ignore-end[comments_earn_their_place, contracts_have_one_source_or_a_drift_gate]
4768#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
4769#[serde(try_from = "String", into = "String")]
4770struct RepositoryTarget {
4771    owner: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only after `owner/name` validation in `new`.
4772    name: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only after `owner/name` validation in `new`.
4773}
4774
4775impl RepositoryTarget {
4776    fn parse(value: &str) -> Result<Self, SourceError> {
4777        let (owner, name) = value.split_once('/').ok_or_else(|| SourceError::Config {
4778            message: format!(
4779                "repository must be spelled owner/name; {value:?} names no repository"
4780            ),
4781        })?;
4782        if !valid_github_owner(owner) || !valid_github_repository_name(name) {
4783            return Err(SourceError::Config {
4784                message: format!(
4785                    "repository must be spelled owner/name with a GitHub login and one \
4786                     repository name; {value:?} is not"
4787                ),
4788            });
4789        }
4790        Ok(Self {
4791            owner: owner.to_owned(),
4792            name: name.to_owned(),
4793        })
4794    }
4795
4796    /// The one host whose repositories this source creates issues in, spelled once: it is
4797    /// what [`Self::origin`] renders and what [`Self::from_origin`] accepts.
4798    const HOST: &str = "github.com";
4799
4800    fn origin(&self) -> String {
4801        format!("{}/{}/{}", Self::HOST, self.owner, self.name)
4802    }
4803
4804    /// The repository a normalized origin names, or why it is none this source can create
4805    /// an issue in: another host, or more or fewer than `owner/name` under this one.
4806    fn from_origin(origin: &Repository) -> Result<Self, String> {
4807        let not_here = || {
4808            format!(
4809                "{} is not a {}/owner/name repository",
4810                origin.as_str(),
4811                Self::HOST
4812            )
4813        };
4814        let (host, rest) = origin.as_str().split_once('/').ok_or_else(not_here)?;
4815        if host != Self::HOST {
4816            return Err(not_here());
4817        }
4818        Self::parse(rest).map_err(|_| not_here())
4819    }
4820
4821    fn slug(&self) -> String {
4822        format!("{}/{}", self.owner, self.name)
4823    }
4824}
4825
4826/// Read back from a kept context as the `owner/name` it was written as, refused unless
4827/// [`RepositoryTarget::parse`] takes it.
4828impl TryFrom<String> for RepositoryTarget {
4829    type Error = String;
4830
4831    fn try_from(slug: String) -> Result<Self, Self::Error> {
4832        Self::parse(&slug).map_err(|error| error.to_string())
4833    }
4834}
4835
4836impl From<RepositoryTarget> for String {
4837    fn from(target: RepositoryTarget) -> Self {
4838        target.slug()
4839    }
4840}
4841
4842/// How long GitHub's issue search may go on missing a comment after it was made or edited,
4843/// which a read of the comments made since an instant sets its watermark back by: four times the
4844/// thirty seconds the credentialed lane has watched it lag.
4845pub const COMMENT_SEARCH_LAG: std::time::Duration = std::time::Duration::from_secs(120);
4846
4847/// A source which reads GitHub afresh for every operation.
4848pub struct GitHubProjectsSource {
4849    /// This source's configured name, used both to tell a far end naming this source
4850    /// from one naming a system it knows nothing about, and to name the instance a
4851    /// status refusal is about.
4852    name: SourceName,
4853    owner: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after full GitHub-owner validation.
4854    project_number: u32, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after GraphQL-Int validation.
4855    repository: Option<RepositoryTarget>,
4856    /// The logins whose repositories a create may file in; empty restricts nothing.
4857    creation_owners: Vec<String>, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after each entry passes GitHub's login grammar.
4858    endpoint: Url,
4859    token: SecretString,
4860    credential_name: String, // llmlint: ignore[invalid_states_unrepresentable] Private diagnostic value constructed only after environment-name validation.
4861    statuses: BoardStatuses,
4862    /// Where each priority lands on this board, or `None` when this instance holds none.
4863    priorities: Option<PriorityMapping>,
4864    /// The metadata values this instance projects onto board text fields, in configured order.
4865    metadata_fields: Vec<MetadataField>,
4866    /// What this board's sub-issues mean.
4867    sub_issues: SubIssues,
4868    /// The link types this source mirrors as `relates-to`.
4869    link_types: onetaskgraph_plugin_api::LinkTypes,
4870    /// Whether this source's configuration opted in to assignees: every document it sends is
4871    /// then spelled by [`graphql::with_assignees`], and every task it reads carries them.
4872    assignees: bool,
4873    /// The GitHub node id of each person an assignee write of this process has named, by
4874    /// lowercased login — `None` for a login GitHub said it does not know — so a later call
4875    /// naming one sends no lookup. A write that fails, or is answered with other people, has the
4876    /// people it named forgotten when its call ends ([`Self::forgotten`]), so the next call
4877    /// naming them asks GitHub again while the rest of its own call does not.
4878    people: Mutex<BTreeMap<String, Option<String>>>,
4879    /// The node ids of the people a failed or mismatched assignee write of this call named,
4880    /// forgotten from [`Self::people`] when the call ends.
4881    forgotten: Mutex<Vec<String>>,
4882    /// GitHub's own spelling of each login this process looked up, by lowercased login: what a
4883    /// write that assigned a person reports them as, however the caller spelled them.
4884    spellings: Mutex<BTreeMap<String, String>>,
4885    /// Built on the first request rather than with the source, as [`Self::client`] says.
4886    client: std::sync::OnceLock<Client>,
4887    /// Built on the first attachment request, as [`Self::asset_client`] says.
4888    asset_client: std::sync::OnceLock<Client>,
4889    /// The markup the engine handed this source for its bodies' headings, applied to every
4890    /// visible body it composes and stripped from every one it reads back: see
4891    /// [`TaskSource::attach_body_markup`].
4892    body_markup: std::sync::OnceLock<onetaskgraph_plugin_api::SharedBodyMarkup>,
4893    /// Every item this source has created in this command, in the order it created them —
4894    /// dropped by [`TaskSource::end_command`].
4895    ///
4896    /// GitHub's `projectV2.items` is eventually consistent: an issue added to a board with
4897    /// `addProjectV2ItemById` is routinely absent from the very next read of that board, so
4898    /// a copy resolving a dependency on an item it had just created refused it as not
4899    /// found. A board read is completed from this — an item remembered here and absent from
4900    /// the read is added back, because the board really does hold it and only the read is
4901    /// behind.
4902    ///
4903    /// It is not a cache of a user's work: nothing is remembered that this process did not
4904    /// itself just write, it lives and dies with the process, and it is never consulted for
4905    /// an item this source did not create.
4906    created: Mutex<Vec<Resolved>>,
4907    /// Every item that already existed and that this source has written in this command, as
4908    /// it wrote it — dropped by [`TaskSource::end_command`].
4909    ///
4910    /// The other half of [`Self::created`], held on the same terms and for the reason a
4911    /// narrowed read needs it: an answer from GitHub's search or from the board's own field
4912    /// filter is an index behind a write this process made moments ago, so a query matching
4913    /// what this process just wrote onto an existing item would otherwise miss it. Nothing
4914    /// is remembered that this process did not itself just write.
4915    updated: Mutex<Vec<Resolved>>,
4916    /// Every issue this source has added a comment to or edited a comment of in this command
4917    /// — dropped by [`TaskSource::end_command`].
4918    ///
4919    /// A comment-activity read is narrowed by GitHub's issue search, whose `updated:` index
4920    /// lags the write that moved an issue's `updatedAt`, and neither [`Self::created`] nor
4921    /// [`Self::updated`] is moved by a comment, so an issue this process had just commented
4922    /// on was missing from such a read — or ruled out by the `updatedAt` its own record held
4923    /// from before — until the index caught up. Each id here is a candidate of every such
4924    /// search-narrowed read, and wherever it is a candidate its comments are read rather than
4925    /// it being ruled out by a stale `updatedAt`; that read is of the issue's own node, so it
4926    /// is current. It holds ids alone: nothing of a comment is remembered. A comment another
4927    /// process wrote is still found only once the index has it.
4928    commented: Mutex<Vec<NativeId>>,
4929    /// How fast this source writes, and how long it waits out a refusal.
4930    pacing: Pacing,
4931    /// When the last content-creating mutation finished, or the moment the furthest-out
4932    /// reserved slot releases the next one, whichever is later — so the one after it can be
4933    /// spaced from that, when `pacing.min_mutation_interval_ms` asks for a spacing. See
4934    /// [`GitHubProjectsSource::paced`] for why completion rather than release is what it is
4935    /// measured from.
4936    last_mutation: Mutex<Option<Duration>>,
4937    /// The `Date` GitHub stated on the last answer this source read: its own time, which the
4938    /// watermark of a comment read is set back from. See [`TaskSource::served_at`].
4939    last_served: Mutex<Option<DateTime<Utc>>>,
4940    /// GitHub's secondary windows as this source has charged them; see the `pacing` module.
4941    windows: Mutex<pacing::Windows>,
4942    /// The tasks a project holds, as a copy's batched read of the project and every one of them
4943    /// found them — see [`TaskSource::read_ahead_for_copy`] — for the length of one command, so
4944    /// a listing of that project's tasks is answered without a read of its own.
4945    task_children: Mutex<BTreeMap<NativeId, Vec<Resolved>>>,
4946    /// The web address of each issue this source created in the current command, as its
4947    /// `createIssue` answered it — what [`TaskSource::written_location`] answers, without a
4948    /// request.
4949    written: Mutex<BTreeMap<NativeId, String>>,
4950    /// What a copy has held back of the items it created, between
4951    /// [`TaskSource::begin_deferred_writes`] and [`TaskSource::finish_writes`] — `None` while
4952    /// nothing is being held back, when every write lands whole as it is made.
4953    deferred: Mutex<Option<Deferred>>,
4954    /// Each existing issue's update held back while writes are, in the order it was made: sent
4955    /// together by [`Self::send_held_updates`] before any other request goes out, so nothing
4956    /// this source sends or reads ever sees the board without them.
4957    held_updates: Mutex<Vec<HeldUpdate>>,
4958    /// The first page of comments a comment-activity read read of each candidate it confirmed,
4959    /// held for the one comment listing of that task that follows in this command — see
4960    /// `batch::hold_comment_pages`.
4961    held_comments: Mutex<BTreeMap<NativeId, Page<Comment>>>,
4962    /// The board field writes and issue updates a batch of targeted updates is holding back,
4963    /// while one runs — see `batch::TaskWrites`.
4964    task_writes: Mutex<Option<batch::TaskWrites>>,
4965    /// The change token each task a targeted update wrote in the current command holds after
4966    /// that write, by the task's id with its board item's id — spelled from the write's own
4967    /// last response, or from the read made right after it where no response showed the whole
4968    /// issue: what [`TaskSource::written_task`] answers as its `version`. Any later mutation
4969    /// naming the task or its board item drops its entry before it is sent, so an entry is
4970    /// never one write behind.
4971    /// A response that showed the issue whole but not every part of its token — a draft, or a
4972    /// page of labels or field values that did not end — records `None`, which a read would
4973    /// not improve on.
4974    written_tokens: Mutex<BTreeMap<NativeId, (String, Option<String>)>>,
4975    clock: SharedClock,
4976    /// Whether the configuration declares this source private, as
4977    /// [`TaskSource::declare_visibility`] told it: what decides where a new issue whose one
4978    /// named repository reads public is created — see [`Self::creation_rule`].
4979    declared_private: std::sync::atomic::AtomicBool,
4980    numeric_repositories: tokio::sync::Mutex<BTreeMap<RepositoryTarget, std::num::NonZeroU64>>,
4981    /// The board as this process last read it, for the length of one command — dropped by
4982    /// [`TaskSource::end_command`].
4983    ///
4984    /// A copy of a project used to re-read the whole board, paged, before writing each of
4985    /// its items, which is by far the largest part of a copy's request count and none of
4986    /// its work. Nothing else changes this board while a command runs — this source's own
4987    /// writes are the only writer — so one read answers them all.
4988    ///
4989    /// It is not a store of a user's work and it is not the cache the no-persistence
4990    /// invariant forbids: it lives and dies with the process exactly as `created` does,
4991    /// nothing is written down, and [`Self::board`] still completes it from `created`, so
4992    /// an item this command created and then depends on resolves whether or not GitHub's
4993    /// own eventually-consistent read has caught up. A write to an item already on the
4994    /// board updates the entry here too, so what this holds is the last read plus this
4995    /// process's own writes rather than a snapshot taken before them.
4996    board_cache: Mutex<Option<Board>>,
4997    /// Every issue this board's own search reported, for the length of one command — dropped
4998    /// by [`TaskSource::end_command`].
4999    ///
5000    /// The second half of a board read, and cached for the same reason and on the same
5001    /// terms as the first: it lives and dies with the process, nothing is written down, and
5002    /// a write this process makes updates the entry here exactly as it updates the one in
5003    /// [`Self::board_cache`]. One read answers every question a command asks, so a command
5004    /// that lists this board's projects and its tasks pays for one search rather than two.
5005    search_cache: Mutex<Option<Vec<Resolved>>>,
5006    /// What each narrowed question GitHub was asked answered, keyed by that question, for
5007    /// the length of one command — dropped by [`TaskSource::end_command`].
5008    ///
5009    /// The narrowed counterpart of [`Self::search_cache`], held on the same terms: it lives
5010    /// and dies with the process, nothing is written down, a write this process makes
5011    /// updates the entry here as it updates the other two, and every answer is completed
5012    /// with this process's own writes each time it is given. A command that asks the same
5013    /// narrowed question twice — a wait polling for its own items, a listing repeated after a
5014    /// write — pays for it once, which is what the whole-board read it replaced gave it.
5015    narrowed_cache: Mutex<BTreeMap<String, Vec<Resolved>>>,
5016    /// Each page of a narrowed search's own read, row for row as GitHub answered it — `None`
5017    /// for a row that is no item of this board, or one this process deleted since — held on
5018    /// the terms [`Self::narrowed_cache`] is. Row for row because a cursor names a row of a
5019    /// page by its position (`SearchPosition::offset`), which an entry removed would move.
5020    search_rows: Mutex<SearchRows>,
5021    search_next: Mutex<BTreeMap<String, Option<String>>>,
5022    /// Records already resolved in this command, reused by writes and for comment identity.
5023    /// Explicit item reads still reach GitHub. Nothing is persisted, and
5024    /// [`TaskSource::end_command`] drops every record, so a write in the next command reads
5025    /// its item as a person has since left it.
5026    resolved_cache: Mutex<BTreeMap<NativeId, Resolved>>,
5027    /// What [`TaskSource::read_ahead_for_copy`] read, by id — `None` for an id that read
5028    /// answered as holding nothing — each taken by the next read of that item by id and by
5029    /// nothing else, dropped by any mutation naming it, and cleared by
5030    /// [`TaskSource::end_command`]. So a read answered from it is the copy's own
5031    /// read-before-write, made in the same request as the others' rather than on its own.
5032    read_ahead: Mutex<BTreeMap<NativeId, Option<Resolved>>>,
5033    /// The origins [`TaskSource::read_ahead_origins_for_copy`] was asked about and has not sent
5034    /// yet: held for the [`TaskSource::read_ahead_for_copy`] that follows it, which sends them —
5035    /// beside the members of the one project it names, when it names one — or for the next
5036    /// request this source makes, whichever comes first.
5037    pending_origins: Mutex<Vec<String>>,
5038    /// Each project's members as a lookup carrying them read them in this command, trimmed to
5039    /// their classification and repositories, taken by [`TaskSource::member_classifications`]
5040    /// of that project and by nothing else, and cleared by [`TaskSource::end_command`].
5041    member_classes: Mutex<BTreeMap<NativeId, Vec<MemberClass>>>,
5042    /// Every item a listing of one project's members carried whole in this command — the
5043    /// project issue and each of its sub-issues — kept for [`TaskSource::read_ahead_for_copy`]
5044    /// alone, which takes each one it is asked for into [`Self::read_ahead`] instead of reading
5045    /// it again. No other read is answered from it, so a read by id outside a copy's
5046    /// read-before-write reads GitHub as it always did. Dropped by any mutation naming an
5047    /// item, and cleared by [`TaskSource::end_command`].
5048    carried: Mutex<BTreeMap<NativeId, Resolved>>,
5049    /// Items an issue read by reference reached, held for the one status write each was read
5050    /// for and taken out by it alone — see [`Self::take_held`] — because that read selects only
5051    /// what such a write needs. Dropped by [`TaskSource::end_command`].
5052    held_cache: Mutex<BTreeMap<NativeId, Resolved>>,
5053    /// Each project's sub-issues as GitHub answered them, keyed by the selector they were
5054    /// asked for under, with the project that selector named — for the length of one command,
5055    /// dropped by [`TaskSource::end_command`].
5056    ///
5057    /// A caller pages through a project's tasks one engine page at a time, and every page
5058    /// is cut from the whole list of them, so without this each page walked every
5059    /// [`graphql::SUB_ISSUES`] page again and a project of `n` listing pages cost `n²`
5060    /// requests to read once. Held on the terms [`Self::narrowed_cache`] is: it lives and
5061    /// dies with the process, nothing is written down, a write this process makes updates or
5062    /// removes the entry here as it does there, and every answer is completed with this
5063    /// process's own writes each time it is given.
5064    children_cache: Mutex<ProjectChildren>,
5065    /// The board's own id and field definitions as this process last read them on their
5066    /// own, for the length of one command — dropped by [`TaskSource::end_command`].
5067    ///
5068    /// What a write needs of the board and its item does not say, read once per command
5069    /// rather than once per item written, on the terms [`Self::board_cache`] is held on: it
5070    /// lives and dies with the process and nothing is written down. It holds no item and so
5071    /// can answer no question about one — see [`Self::board_fields`].
5072    fields_cache: Mutex<Option<BoardFields>>,
5073    /// Each destination repository's node id, resolved once per repository
5074    /// rather than per issue created.
5075    ///
5076    /// A repository's node id does not change, and re-reading it for every issue of a copy
5077    /// spent one request per item on an answer this source already had. It is a map rather
5078    /// than one entry because a copy files each item in the repository its own
5079    /// `repositories` field names, so a plan across five repositories asks GitHub five
5080    /// times and not once per item.
5081    repository_cache: Mutex<BTreeMap<RepositoryTarget, String>>,
5082    /// What every request this source sends is recorded into.
5083    ///
5084    /// Ordinary code path, not a mode: [`Self::send_once`] records into it at the one place
5085    /// a request leaves this crate, so nothing has to be switched on for a session to be
5086    /// counted. It is shared rather than owned so a caller accounting for a whole session —
5087    /// its own schema verification, board lookups, residue sweep and cleanup beside this
5088    /// source's reads and writes — adds up one accounting instead of two. See
5089    /// [`accounting`] for what a record carries and what a session's spend is and is not.
5090    ledger: Arc<Accounting>,
5091    /// What [`expected`] holds for a write the store's cache expects: the journal while one is
5092    /// open, the issues primed from the cache, and the comments known on each.
5093    expected: expected::Held,
5094    /// What [`projection`] holds for a producer's projection: a kept placement awaiting its
5095    /// setup-context token, and where the last create was placed.
5096    projection: projection::Held,
5097}
5098
5099/// The board item a single field update's answer names, refused unless it is `item_id`.
5100fn field_update_item<'a>(data: &'a Value, item_id: &str) -> Result<&'a Value, SourceError> {
5101    let returned = data
5102        .pointer("/updateProjectV2ItemFieldValue/projectV2Item")
5103        .ok_or_else(|| SourceError::Malformed {
5104            message: "GitHub field update returned no project item".into(),
5105        })?;
5106    if required_str(returned, "id")? != item_id {
5107        return Err(SourceError::Malformed {
5108            message: "GitHub field update returned the wrong project item".into(),
5109        });
5110    }
5111    Ok(returned)
5112}
5113
5114/// GitHub's closed single-select color vocabulary.
5115#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
5116#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
5117pub enum StatusOptionColor {
5118    /// Gray.
5119    Gray,
5120    /// Blue.
5121    Blue,
5122    /// Green.
5123    Green,
5124    /// Yellow.
5125    Yellow,
5126    /// Purple.
5127    Purple,
5128    /// Red.
5129    Red,
5130    /// Orange.
5131    Orange,
5132    /// Pink.
5133    Pink,
5134}
5135
5136/// Whether a guarded board setup — of the fields, or of the Status options alone — plans or
5137/// applies its additions.
5138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5139pub enum SetupMode {
5140    /// Read without mutation.
5141    Plan,
5142    /// Apply and verify.
5143    Apply,
5144}
5145
5146/// The name [`SetupMode`] had when Status was the one field set up, kept so a caller written
5147/// against it goes on compiling.
5148pub type StatusOptionsMode = SetupMode;
5149
5150/// The explicit result of the requested operation.
5151#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5152#[serde(rename_all = "kebab-case")]
5153pub enum StatusOptionsOutcome {
5154    /// A read-only plan.
5155    Planned,
5156    /// Apply found nothing missing.
5157    Unchanged,
5158    /// Additions were applied and verified.
5159    Applied,
5160}
5161
5162/// A GitHub single-select option's opaque GraphQL node identifier.
5163#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5164#[serde(transparent)]
5165pub struct StatusOptionId(#[schemars(length(min = 1))] String);
5166
5167impl TryFrom<String> for StatusOptionId {
5168    type Error = String;
5169
5170    fn try_from(id: String) -> Result<Self, Self::Error> {
5171        if id.trim().is_empty() {
5172            return Err("a GitHub Status option id cannot be blank".to_owned());
5173        }
5174        Ok(Self(id))
5175    }
5176}
5177
5178/// One existing or proposed option in a guarded Status-field update.
5179#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5180pub struct StatusOption {
5181    /// GitHub's stable id.
5182    pub id: StatusOptionId,
5183    /// The visible option name.
5184    pub name: ColumnName,
5185    /// GitHub's single-select color token.
5186    pub color: StatusOptionColor,
5187    /// The option description, including an empty one.
5188    pub description: String,
5189}
5190
5191/// One board item's Status assignment, retained as recovery data.
5192#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5193pub struct StatusAssignment {
5194    /// The project item id whose assignment this is.
5195    // llmlint: ignore[invalid_states_unrepresentable] This opaque GraphQL node ID is
5196    // carried verbatim as operator recovery data; introducing a semantic type would claim
5197    // validation rules GitHub does not publish and no operation here interprets.
5198    pub item_id: String,
5199    /// The selected option, absent when the item has no status.
5200    #[serde(skip_serializing_if = "Option::is_none")]
5201    pub option: Option<AssignedStatusOption>,
5202}
5203
5204/// The inseparable id and name of an assigned option.
5205#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5206pub struct AssignedStatusOption {
5207    /// GitHub's stable id.
5208    pub id: StatusOptionId,
5209    /// The visible name.
5210    pub name: ColumnName,
5211}
5212
5213/// The plan and verified outcome of reconciling configured Status options.
5214#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5215pub struct StatusOptionsReport {
5216    /// The configured source name.
5217    pub source: SourceName,
5218    /// Configured option names absent before the operation.
5219    // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a
5220    // `ColumnName` and has therefore already passed its nonblank validation; retaining the
5221    // serialized string here preserves the report's intentionally simple public contract.
5222    pub missing: Vec<String>,
5223    /// What the requested operation did.
5224    pub outcome: StatusOptionsOutcome,
5225    /// The complete option list observed before any mutation.
5226    pub existing: Vec<StatusOption>,
5227}
5228
5229#[derive(Debug, Clone, PartialEq, Eq)]
5230struct StatusSnapshot {
5231    // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
5232    // passed back as the mutation's project identity; a newtype could enforce no stronger
5233    // invariant because GitHub publishes no grammar for it.
5234    board_id: String,
5235    // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
5236    // passed back as the mutation's field identity; a newtype could enforce no stronger
5237    // invariant because GitHub publishes no grammar for it.
5238    field_id: String,
5239    options: Vec<StatusOption>,
5240    assignments: Vec<StatusAssignment>,
5241}
5242
5243/// The name of the board field a status is held in.
5244const STATUS_FIELD: &str = "Status";
5245
5246/// Every item's value of each field `report` names, as it stood before the setup wrote
5247/// anything — what a person puts back when the setup is refused part way.
5248fn recovery(report: &FieldsReport, before: &BoardSnapshot) -> Result<String, SourceError> {
5249    let assignments: BTreeMap<&str, Vec<StatusAssignment>> = report
5250        .fields
5251        .iter()
5252        .map(|field| (field.field.name(), before.assignments(field.field)))
5253        .collect();
5254    serde_json::to_string_pretty(&assignments).map_err(|error| SourceError::Malformed {
5255        message: format!("cannot render the pre-write field recovery snapshot: {error}"),
5256    })
5257}
5258
5259/// One board field the guarded setup reads and writes — every one it reads, and the only
5260/// ones it writes.
5261#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, schemars::JsonSchema)]
5262pub enum BoardField {
5263    /// The single-select `Status` field every instance's `status_mapping` resolves into.
5264    Status,
5265    /// The single-select `Priority` field an instance's `priority_mapping` resolves into.
5266    Priority,
5267}
5268
5269impl BoardField {
5270    /// The field's name on the board.
5271    #[must_use]
5272    pub const fn name(self) -> &'static str {
5273        match self {
5274            Self::Status => STATUS_FIELD,
5275            Self::Priority => PRIORITY_FIELD,
5276        }
5277    }
5278
5279    /// The field a board calls `name`, or `None` for one this setup does not own.
5280    fn named(name: &str) -> Option<Self> {
5281        [Self::Status, Self::Priority]
5282            .into_iter()
5283            .find(|field| field.name() == name)
5284    }
5285}
5286
5287/// What the guarded setup did to one field.
5288#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5289#[serde(rename_all = "kebab-case")]
5290pub enum FieldOutcome {
5291    /// A read-only plan.
5292    Planned,
5293    /// Apply found the field there with every configured option.
5294    Unchanged,
5295    /// Missing options were added to the field that was there, and verified.
5296    Applied,
5297    /// The field was not there; it was created holding the configured options, and verified.
5298    Created,
5299}
5300
5301/// One field's plan, or its verified outcome.
5302#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5303pub struct FieldReport {
5304    /// Which field.
5305    pub field: BoardField,
5306    /// Whether the board had the field before the operation.
5307    // llmlint: ignore[invalid_states_unrepresentable] `exists` beside `outcome` is the report's
5308    // wire shape as its consumer's contract fixes it — `{"field", "exists", "missing",
5309    // "outcome", "existing"}` — so folding one into the other would change a published JSON
5310    // shape. The contradictory pairings cannot be built: `GitHubProjectsSource::fields` is the
5311    // one constructor, and it derives `outcome` from `exists` in one match.
5312    pub exists: bool,
5313    /// Configured option names the field lacked before the operation — every one of them,
5314    /// in the order a new field lists them, when the field was not there at all.
5315    // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a validated
5316    // mapping name and has therefore already passed its nonblank validation; the serialized
5317    // string is the report's intentionally simple public contract, as `StatusOptionsReport`'s is.
5318    pub missing: Vec<String>,
5319    /// For the `Status` field, which item kind each missing name is configured for: one
5320    /// entry per kind `status_mapping` names a missing option for, task before project, each
5321    /// listing that kind's missing names in category order. A name both kinds use is in
5322    /// both. Empty — and left out of the JSON — when nothing is missing, and always for
5323    /// `Priority`, which only a task holds.
5324    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5325    // Kept in the schema as `"default": []` although the JSON leaves an empty list out, so
5326    // both SDKs model an absent `kinds` as an empty list rather than as `null`.
5327    #[schemars(!skip_serializing_if)]
5328    pub kinds: Vec<KindMissing>,
5329    /// What the requested operation did.
5330    pub outcome: FieldOutcome,
5331    /// The field's complete option list observed before any mutation; empty when the field
5332    /// was not there.
5333    pub existing: Vec<StatusOption>,
5334}
5335
5336/// The `Status` option names one item kind's `status_mapping` names that the field lacked.
5337#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5338pub struct KindMissing {
5339    /// The kind these names are configured for.
5340    pub kind: ItemKind,
5341    /// The names that kind maps a category to and the field lacked, in category order.
5342    // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a validated
5343    // mapping name, as `FieldReport::missing`'s do, and the serialized string is the report's
5344    // intentionally simple public contract.
5345    pub missing: Vec<String>,
5346}
5347
5348/// The plan and verified outcome of setting up every field a source's configuration names.
5349#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5350pub struct FieldsReport {
5351    /// The configured source name.
5352    pub source: SourceName,
5353    /// `Status`, always, and `Priority` when the source sets `priority_mapping`.
5354    // llmlint: ignore[invalid_states_unrepresentable] A list is the report's wire shape as its
5355    // consumer's contract fixes it — `{"source", "fields": [...]}` — so a struct with one member
5356    // per field would change a published JSON shape. The states the list could hold and the
5357    // contract forbids cannot be built: `GitHubProjectsSource::fields` is the one constructor,
5358    // and it pushes `Status` first and exactly once, then `Priority` exactly when configured.
5359    pub fields: Vec<FieldReport>,
5360    /// Each board text field the source's `metadata_fields` projects a value onto, in
5361    /// configured order. Empty — and left out of the JSON — when it projects none.
5362    #[serde(default, skip_serializing_if = "Vec::is_empty")]
5363    // Kept in the schema as `"default": []` although the JSON leaves an empty list out, so
5364    // both SDKs model an absent list as an empty one rather than as `null`.
5365    #[schemars(!skip_serializing_if)]
5366    pub metadata_fields: Vec<MetadataFieldReport>,
5367}
5368
5369/// The type of a board field that is not a text field, as GitHub names it — its `dataType`, or
5370/// its GraphQL type when it has none — which is what a projected field's conflict reports.
5371///
5372/// Never empty, never beginning with whitespace, and never `TEXT`: a text field of that name is
5373/// no conflict.
5374// The schema states that rule as `NON_TEXT_FIELD_TYPE_PATTERN`, so a generated SDK model
5375// refuses exactly what `try_from` below does.
5376#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5377#[serde(transparent)]
5378pub struct NonTextFieldType(#[schemars(regex(pattern = NON_TEXT_FIELD_TYPE_PATTERN))] String);
5379
5380/// What a [`NonTextFieldType`] may be, as the emitted schema states it: a first character that
5381/// is not whitespace, and anything but exactly `TEXT` — spelled without a lookahead, which
5382/// neither SDK's validator can be relied on to support.
5383const NON_TEXT_FIELD_TYPE_PATTERN: &str =
5384    r"^(?:[^T\s]|T(?:[^E]|$)|TE(?:[^X]|$)|TEX(?:[^T]|$)|TEXT[\s\S])";
5385
5386impl TryFrom<String> for NonTextFieldType {
5387    type Error = String;
5388
5389    fn try_from(kind: String) -> Result<Self, Self::Error> {
5390        if kind.is_empty() || kind.starts_with(char::is_whitespace) {
5391            return Err("a board field's type cannot be blank or begin with whitespace".to_owned());
5392        }
5393        if kind == "TEXT" {
5394            return Err("a TEXT field is no conflict for a projected text field".to_owned());
5395        }
5396        Ok(Self(kind))
5397    }
5398}
5399
5400impl std::fmt::Display for NonTextFieldType {
5401    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5402        formatter.write_str(&self.0)
5403    }
5404}
5405
5406/// One projected metadata text field's plan, or its verified outcome.
5407///
5408/// The setup creates a missing one as a text field and never alters a field that is there:
5409/// a same-named field of another type is reported in `conflict` and left as it is.
5410#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5411pub struct MetadataFieldReport {
5412    /// The board field's name.
5413    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.
5414    /// The metadata key the value is read from.
5415    pub key: String, // llmlint: ignore[invalid_states_unrepresentable] As `field`: a validated configuration value reported back as written.
5416    /// The object keys walked inside that key's value; empty for the key's own value.
5417    pub path: Vec<String>,
5418    /// Whether the board had a text field of that name before the operation.
5419    // 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.
5420    pub exists: bool,
5421    /// The type of a field of that name that is not a text field, which the setup leaves as
5422    /// it is; absent — and left out of the JSON — when there is none.
5423    #[serde(default, skip_serializing_if = "Option::is_none")]
5424    pub conflict: Option<NonTextFieldType>,
5425    /// What the requested operation did: `planned`; `created` for a field that was not
5426    /// there; `unchanged` for one that was, and for a conflict, which is never changed.
5427    pub outcome: FieldOutcome,
5428}
5429
5430/// Which options one field is configured with, in the order a new field would list them.
5431struct FieldPlan {
5432    field: BoardField,
5433    wanted: Vec<String>,
5434}
5435
5436/// One single-select field as the guarded setup snapshots it.
5437#[derive(Debug, Clone, PartialEq, Eq)]
5438struct SnapshotField {
5439    // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
5440    // passed back as the mutation's field identity; a newtype could enforce no stronger
5441    // invariant because GitHub publishes no grammar for it.
5442    field_id: String,
5443    options: Vec<StatusOption>,
5444}
5445
5446/// Every single-select field of a board and every item's value of each.
5447#[derive(Debug, Clone, PartialEq, Eq)]
5448struct BoardSnapshot {
5449    // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
5450    // passed back as the mutation's project identity; a newtype could enforce no stronger
5451    // invariant because GitHub publishes no grammar for it.
5452    board_id: String,
5453    fields: BTreeMap<BoardField, SnapshotField>,
5454    /// Each board item's id, and its value of each field this setup owns that it holds one of.
5455    items: Vec<(String, BTreeMap<BoardField, AssignedStatusOption>)>,
5456}
5457
5458impl BoardSnapshot {
5459    /// Every item's value of `field`, in board order — the recovery data a drift refusal
5460    /// carries.
5461    fn assignments(&self, field: BoardField) -> Vec<StatusAssignment> {
5462        self.items
5463            .iter()
5464            .map(|(item_id, values)| StatusAssignment {
5465                item_id: item_id.clone(),
5466                option: values.get(&field).cloned(),
5467            })
5468            .collect()
5469    }
5470}
5471
5472impl GitHubProjectsSource {
5473    /// `content` as this source sends it, with the markup the engine handed it applied.
5474    fn marked(&self, content: &str) -> String {
5475        match self.body_markup.get() {
5476            Some(markup) if !content.is_empty() => markup.written(content),
5477            _ => content.to_owned(),
5478        }
5479    }
5480
5481    /// The visible body and the metadata slot of `body` as [`metadata_body`] splits them,
5482    /// the visible body without the markup [`Self::marked`] applies.
5483    fn visible(
5484        &self,
5485        body: Option<String>,
5486    ) -> Result<(Option<String>, BTreeMap<String, Value>), SourceError> {
5487        let (visible, slot) = metadata_body(body)?;
5488        Ok((
5489            match (visible, self.body_markup.get()) {
5490                (Some(visible), Some(markup)) => {
5491                    Some(markup.read(&visible)).filter(|read| !read.is_empty())
5492                }
5493                (visible, _) => visible,
5494            },
5495            slot,
5496        ))
5497    }
5498
5499    /// Report missing configured Status options and, when `apply` is true, add them with
5500    /// a whole-list mutation that preserves every existing id and verifies the result.
5501    ///
5502    /// # Errors
5503    ///
5504    /// Refuses a board without a single-select `Status` field. A post-write difference in
5505    /// any pre-existing option id or item assignment is refused with the complete pre-write
5506    /// assignment snapshot in the diagnostic for recovery.
5507    // llmlint: ignore[changed_behavior_has_e2e] The CLI journeys cover plan, no-op apply,
5508    // successful mutation, both drift refusals, source selection, missing Status, casing,
5509    // and paging. Transport errors remain the shared `graphql` boundary's behavior rather
5510    // than a new status-options behavior, and the pinned-schema test prevents valid GitHub
5511    // responses from entering the defensive malformed-response branches below.
5512    pub async fn status_options(
5513        &self,
5514        mode: StatusOptionsMode,
5515    ) -> Result<StatusOptionsReport, SourceError> {
5516        let before = self.status_snapshot().await?;
5517        // A terminal category's option is as configured as an open one's: a terminal
5518        // write validates it before closing and refuses when the board lacks it. Both
5519        // kinds' names are options of the one field, so both are asked for.
5520        let missing = self
5521            .statuses
5522            .wanted()
5523            .into_iter()
5524            .filter(|wanted| {
5525                !before
5526                    .options
5527                    .iter()
5528                    .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
5529            })
5530            .collect::<Vec<_>>();
5531        let report = StatusOptionsReport {
5532            source: self.name.clone(),
5533            missing: missing.clone(),
5534            outcome: match (mode, missing.is_empty()) {
5535                (StatusOptionsMode::Plan, _) => StatusOptionsOutcome::Planned,
5536                (StatusOptionsMode::Apply, true) => StatusOptionsOutcome::Unchanged,
5537                (StatusOptionsMode::Apply, false) => StatusOptionsOutcome::Applied,
5538            },
5539            existing: before.options.clone(),
5540        };
5541        if mode == StatusOptionsMode::Plan || missing.is_empty() {
5542            return Ok(report);
5543        }
5544        let mut options = before
5545            .options
5546            .iter()
5547            .map(|option| {
5548                json!({
5549                    "id": option.id, "name": option.name, "color": option.color,
5550                    "description": option.description,
5551                })
5552            })
5553            .collect::<Vec<_>>();
5554        options.extend(missing.iter().map(|name| {
5555            json!({
5556                "name": name, "color": "GRAY", "description": ""
5557            })
5558        }));
5559        self.graphql(
5560            graphql::STATUS_OPTIONS_UPDATE,
5561            json!({"input": {
5562                "fieldId": before.field_id,
5563                "singleSelectOptions": options,
5564            }}),
5565        )
5566        .await?;
5567        let after = self.status_snapshot().await?;
5568        let options_preserved = before
5569            .options
5570            .iter()
5571            .all(|old| after.options.iter().any(|new| new == old));
5572        let additions_present = missing.iter().all(|wanted| {
5573            after
5574                .options
5575                .iter()
5576                .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
5577        });
5578        if !options_preserved || !additions_present || after.assignments != before.assignments {
5579            let recovery = serde_json::to_string_pretty(&before.assignments).map_err(|error| {
5580                SourceError::Malformed {
5581                    message: format!("cannot render pre-write Status recovery snapshot: {error}"),
5582                }
5583            })?;
5584            return Err(SourceError::Refused {
5585                message: format!(
5586                    "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}"
5587                ),
5588            });
5589        }
5590        Ok(report)
5591    }
5592
5593    /// A fresh snapshot of the Status field and every board item's assignment of it.
5594    ///
5595    /// # Errors
5596    ///
5597    /// Refuses a board without a single-select `Status` field, and one the token cannot see.
5598    async fn status_snapshot(&self) -> Result<StatusSnapshot, SourceError> {
5599        // Status alone, as this operation has always read it: a `Priority` field is another
5600        // operation's, so nothing about it can refuse this one.
5601        let mut board = self.board_snapshot(&[BoardField::Status]).await?;
5602        let field = board
5603            .fields
5604            .remove(&BoardField::Status)
5605            .ok_or_else(|| self.no_status_field())?;
5606        Ok(StatusSnapshot {
5607            assignments: board.assignments(BoardField::Status),
5608            board_id: board.board_id,
5609            field_id: field.field_id,
5610            options: field.options,
5611        })
5612    }
5613
5614    /// The refusal a board with no `Status` field is answered with by the guarded setup.
5615    fn no_status_field(&self) -> SourceError {
5616        SourceError::Refused {
5617            message: format!("source {} board has no Status field", self.name),
5618        }
5619    }
5620
5621    // llmlint: ignore-block[changed_behavior_has_e2e] Valid snapshot shapes are exercised through
5622    // the real CLI loopback journey, including pagination. The individual malformed guards
5623    // are defensive validation of a schema-pinned third-party response, not separate user
5624    // journeys; drift and missing-field failures cover the operation's recovery behavior.
5625    /// A fresh snapshot of each of the `owned` fields on the board, with its options, and of
5626    /// every board item's value of each, walked to the end of the board's items. A field not
5627    /// in `owned` is read past whatever it holds.
5628    async fn board_snapshot(&self, owned: &[BoardField]) -> Result<BoardSnapshot, SourceError> {
5629        let mut after: Option<String> = None;
5630        let mut snapshot: Option<BoardSnapshot> = None;
5631        loop {
5632            let data = self
5633                .graphql(
5634                    graphql::STATUS_OPTIONS_SNAPSHOT,
5635                    json!({
5636                        "owner": self.owner, "number": self.project_number,
5637                        "first": MAX_PAGE_SIZE, "after": after, "nestedFirst": MAX_PAGE_SIZE,
5638                    }),
5639                )
5640                .await?;
5641            let board = data
5642                .pointer("/owner/projectV2")
5643                .filter(|board| board.is_object())
5644                .ok_or_else(|| SourceError::Refused {
5645                    message: format!(
5646                        "source {} has no accessible GitHub Projects board",
5647                        self.name
5648                    ),
5649                })?;
5650            if board
5651                .pointer("/fields/pageInfo/hasNextPage")
5652                .and_then(Value::as_bool)
5653                != Some(false)
5654            {
5655                return Err(SourceError::Malformed {
5656                    message:
5657                        "GitHub project fields is incomplete or has malformed pageInfo.hasNextPage"
5658                            .into(),
5659                });
5660            }
5661            let mut fields = BTreeMap::new();
5662            // Only the fields this setup owns, by name: a node the single-select fragment did not
5663            // match carries no name, and a person's own single-select field — a `Size`, a
5664            // `Team` — is none of this setup's business, so nothing about it can refuse one. A
5665            // `Status` or `Priority` field without its options is malformed, not absent.
5666            // 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.
5667            for (owned, field) in board
5668                .pointer("/fields/nodes")
5669                .and_then(Value::as_array)
5670                .ok_or_else(|| SourceError::Malformed {
5671                    message: "GitHub project fields.nodes is not an array".into(),
5672                })?
5673                .iter()
5674                .filter_map(|field| {
5675                    let named = BoardField::named(field.get("name")?.as_str()?)?;
5676                    owned.contains(&named).then_some((named, field))
5677                })
5678            {
5679                let options = field
5680                    .get("options")
5681                    .and_then(Value::as_array)
5682                    .ok_or_else(|| SourceError::Malformed {
5683                        message: "GitHub single-select field options is not an array".into(),
5684                    })?
5685                    .iter()
5686                    .map(|option| {
5687                        Ok(StatusOption {
5688                            id: StatusOptionId::try_from(required_str(option, "id")?.to_owned())
5689                                .map_err(|message| SourceError::Malformed { message })?,
5690                            name: ColumnName::try_from(required_str(option, "name")?.to_owned())
5691                                .map_err(|message| SourceError::Malformed {
5692                                    message: format!(
5693                                        "GitHub single-select option name is invalid: {message}"
5694                                    ),
5695                                })?,
5696                            color: serde_json::from_value(
5697                                option.get("color").cloned().unwrap_or(Value::Null),
5698                            )
5699                            .map_err(|error| {
5700                                SourceError::Malformed {
5701                                    message: format!(
5702                                        "GitHub single-select option color is invalid: {error}"
5703                                    ),
5704                                }
5705                            })?,
5706                            description: optional_str(option, "description")?
5707                                .unwrap_or_default()
5708                                .to_owned(),
5709                        })
5710                    })
5711                    .collect::<Result<Vec<_>, SourceError>>()?;
5712                let snapshot = SnapshotField {
5713                    field_id: required_nonblank_str(field, "id")?.to_owned(),
5714                    options,
5715                };
5716                // A board's field names are unique, so a second one is an answer that cannot
5717                // say which field the setup would act on — refused rather than one chosen.
5718                if fields.insert(owned, snapshot).is_some() {
5719                    return Err(SourceError::Malformed {
5720                        message: format!(
5721                            "GitHub answered two {} fields for this board",
5722                            owned.name()
5723                        ),
5724                    });
5725                }
5726            }
5727            let board_id = required_nonblank_str(board, "id")?.to_owned();
5728            let current = snapshot.get_or_insert_with(|| BoardSnapshot {
5729                board_id,
5730                fields,
5731                items: Vec::new(),
5732            });
5733            let items = board
5734                .pointer("/items/nodes")
5735                .and_then(Value::as_array)
5736                .ok_or_else(|| SourceError::Malformed {
5737                    message: "GitHub project items.nodes is not an array".into(),
5738                })?;
5739            for item in items {
5740                let field_values =
5741                    item.get("fieldValues")
5742                        .ok_or_else(|| SourceError::Malformed {
5743                            message: "GitHub project item is missing fieldValues".into(),
5744                        })?;
5745                if field_values
5746                    .pointer("/pageInfo/hasNextPage")
5747                    .and_then(Value::as_bool)
5748                    != Some(false)
5749                {
5750                    return Err(SourceError::Malformed {
5751                        message: "GitHub project item fieldValues is incomplete or has malformed pageInfo.hasNextPage".into(),
5752                    });
5753                }
5754                let values = item
5755                    .pointer("/fieldValues/nodes")
5756                    .and_then(Value::as_array)
5757                    .ok_or_else(|| SourceError::Malformed {
5758                        message: "GitHub project item fieldValues.nodes is not an array".into(),
5759                    })?;
5760                let item_id = required_nonblank_str(item, "id")?;
5761                let mut assigned = BTreeMap::new();
5762                for value in values {
5763                    let Some(field) = value
5764                        .pointer("/field/name")
5765                        .and_then(Value::as_str)
5766                        .and_then(BoardField::named)
5767                        .filter(|field| owned.contains(field))
5768                    else {
5769                        continue;
5770                    };
5771                    let held = assigned.insert(
5772                        field,
5773                        AssignedStatusOption {
5774                            id: StatusOptionId::try_from(
5775                                required_str(value, "optionId")?.to_owned(),
5776                            )
5777                            .map_err(|message| SourceError::Malformed { message })?,
5778                            name: ColumnName::try_from(required_str(value, "name")?.to_owned())
5779                                .map_err(|message| SourceError::Malformed {
5780                                    message: format!(
5781                                        "GitHub assigned {} name is invalid: {message}",
5782                                        field.name()
5783                                    ),
5784                                })?,
5785                        },
5786                    );
5787                    // An item holds one value of a field, so a second one leaves no way to
5788                    // tell which it holds — and a verification or recovery built on either
5789                    // could restore the wrong one.
5790                    if held.is_some() {
5791                        return Err(SourceError::Malformed {
5792                            message: format!(
5793                                "GitHub answered two {} values for board item {item_id}",
5794                                field.name()
5795                            ),
5796                        });
5797                    }
5798                }
5799                current.items.push((item_id.to_owned(), assigned));
5800            }
5801            let page = board.get("items").ok_or_else(|| SourceError::Malformed {
5802                message: "GitHub project is missing items".into(),
5803            })?;
5804            let has_next = page
5805                .pointer("/pageInfo/hasNextPage")
5806                .and_then(Value::as_bool)
5807                .ok_or_else(|| SourceError::Malformed {
5808                    message: "GitHub project items.pageInfo.hasNextPage is not a boolean".into(),
5809                })?;
5810            if !has_next {
5811                break;
5812            }
5813            let next =
5814                required_nonblank_str(page.get("pageInfo").unwrap_or(&Value::Null), "endCursor")?;
5815            validate_cursor_progress(after.as_deref(), next)?;
5816            after = Some(next.to_owned());
5817        }
5818        snapshot.ok_or_else(|| SourceError::Malformed {
5819            message: "GitHub returned no board field snapshot".into(),
5820        })
5821    }
5822    // llmlint: ignore-end[changed_behavior_has_e2e]
5823
5824    /// Report every board field this source's configuration names and, with
5825    /// [`SetupMode::Apply`], set each up: add the options a field lacks, and create
5826    /// the `Priority` field when the board has none.
5827    ///
5828    /// The fields are `Status`, always, with the options `status_mapping` resolves to; and
5829    /// `Priority`, when `priority_mapping` is set, with its four mapped options — created in
5830    /// the order urgent, high, medium, low. An option a field already has keeps its id, name,
5831    /// color and description: the whole option list goes back with every existing id, because
5832    /// a re-minted id clears every item's value.
5833    ///
5834    /// # Errors
5835    ///
5836    /// Refuses a board without a single-select `Status` field. After an apply the board is
5837    /// read again, and a pre-existing option or any item's value of either field that moved is
5838    /// refused with the complete pre-write assignments in the diagnostic, for recovery.
5839    // llmlint: ignore[changed_behavior_has_e2e] The `sources fields` journeys drive plan,
5840    // unchanged apply, a created field, an added option to each field, drift refusal, a board
5841    // with no Status field and a non-github-projects source through the compiled CLI against
5842    // the loopback board. Transport errors are the shared `graphql` boundary's behavior.
5843    pub async fn fields(&self, mode: SetupMode) -> Result<FieldsReport, SourceError> {
5844        let owned: Vec<BoardField> = if self.priorities.is_some() {
5845            vec![BoardField::Status, BoardField::Priority]
5846        } else {
5847            vec![BoardField::Status]
5848        };
5849        let before = self.board_snapshot(&owned).await?;
5850        let mut plans = vec![FieldPlan {
5851            field: BoardField::Status,
5852            wanted: self.statuses.wanted(),
5853        }];
5854        if !before.fields.contains_key(&BoardField::Status) {
5855            return Err(self.no_status_field());
5856        }
5857        if let Some(mapping) = &self.priorities {
5858            plans.push(FieldPlan {
5859                field: BoardField::Priority,
5860                wanted: mapping.names().map(str::to_owned).collect(),
5861            });
5862        }
5863        // The snapshot reads single-select fields alone, so a field it did not find may still
5864        // be on the board under the name, of another type: creating one beside it would fail
5865        // part way, or leave two fields of one name. Asked of the board's own field list, and
5866        // only when a field is missing.
5867        if plans
5868            .iter()
5869            .any(|plan| !before.fields.contains_key(&plan.field))
5870        {
5871            let board = self.board_fields().await?;
5872            for plan in plans
5873                .iter()
5874                .filter(|plan| !before.fields.contains_key(&plan.field))
5875            {
5876                if let Some(field) = Board::field(&board.fields, plan.field.name())? {
5877                    return Err(SourceError::Refused {
5878                        message: format!(
5879                            "source {}'s board has a {} field that is not a single-select field \
5880                             (it is a {}), so it cannot hold this source's options; next: rename \
5881                             or remove that field, then run this again",
5882                            self.name,
5883                            plan.field.name(),
5884                            optional_str(field, "__typename")?.unwrap_or("field of another type")
5885                        ),
5886                    });
5887                }
5888            }
5889        }
5890        let mut reports = Vec::new();
5891        for plan in &plans {
5892            let held = before.fields.get(&plan.field);
5893            let existing = held.map(|field| field.options.clone()).unwrap_or_default();
5894            let mut missing: Vec<String> = Vec::new();
5895            for wanted in &plan.wanted {
5896                let present = existing
5897                    .iter()
5898                    .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
5899                    || missing
5900                        .iter()
5901                        .any(|named| named.eq_ignore_ascii_case(wanted));
5902                if !present {
5903                    missing.push(wanted.clone());
5904                }
5905            }
5906            let kinds = match plan.field {
5907                BoardField::Status => self.statuses.missing_by_kind(&existing),
5908                BoardField::Priority => Vec::new(),
5909            };
5910            reports.push(FieldReport {
5911                field: plan.field,
5912                exists: held.is_some(),
5913                kinds,
5914                outcome: match (mode, held.is_some(), missing.is_empty()) {
5915                    (SetupMode::Plan, _, _) => FieldOutcome::Planned,
5916                    (SetupMode::Apply, true, true) => FieldOutcome::Unchanged,
5917                    (SetupMode::Apply, true, false) => FieldOutcome::Applied,
5918                    (SetupMode::Apply, false, _) => FieldOutcome::Created,
5919                },
5920                missing,
5921                existing,
5922            });
5923        }
5924        // A projected field is a text field, which the single-select snapshot cannot see, so
5925        // it is asked of the board's own field list — and only when one is configured.
5926        let mut metadata_fields = Vec::new();
5927        if !self.metadata_fields.is_empty() {
5928            let board = self.board_fields().await?;
5929            for projection in &self.metadata_fields {
5930                let conflict = match Board::field(&board.fields, &projection.field)? {
5931                    None => None,
5932                    Some(field) => {
5933                        let typename = optional_str(field, "__typename")?;
5934                        let data_type = optional_str(field, "dataType")?;
5935                        if typename == Some("ProjectV2Field") && data_type == Some("TEXT") {
5936                            None
5937                        } else {
5938                            let named = data_type
5939                                .filter(|kind| *kind != "TEXT")
5940                                .or(typename)
5941                                .unwrap_or("field of another type");
5942                            Some(NonTextFieldType::try_from(named.to_owned()).map_err(
5943                                |message| SourceError::Malformed {
5944                                    message: format!(
5945                                        "GitHub answered the board's {} field with a type this \
5946                                         setup cannot read: {message}",
5947                                        &*projection.field
5948                                    ),
5949                                },
5950                            )?)
5951                        }
5952                    }
5953                };
5954                let exists =
5955                    conflict.is_none() && Board::field(&board.fields, &projection.field)?.is_some();
5956                metadata_fields.push(MetadataFieldReport {
5957                    field: projection.field.to_string(),
5958                    key: projection.key.to_string(),
5959                    path: projection.path.clone(),
5960                    exists,
5961                    outcome: match (mode, exists || conflict.is_some()) {
5962                        (SetupMode::Plan, _) => FieldOutcome::Planned,
5963                        (SetupMode::Apply, true) => FieldOutcome::Unchanged,
5964                        (SetupMode::Apply, false) => FieldOutcome::Created,
5965                    },
5966                    conflict,
5967                });
5968            }
5969        }
5970        let report = FieldsReport {
5971            source: self.name.clone(),
5972            fields: reports,
5973            metadata_fields,
5974        };
5975        let writes: Vec<&FieldReport> = report
5976            .fields
5977            .iter()
5978            .filter(|field| !field.missing.is_empty() || !field.exists)
5979            .collect();
5980        let creates: Vec<&MetadataFieldReport> = report
5981            .metadata_fields
5982            .iter()
5983            .filter(|field| field.outcome == FieldOutcome::Created)
5984            .collect();
5985        if mode == SetupMode::Plan || (writes.is_empty() && creates.is_empty()) {
5986            return Ok(report);
5987        }
5988        let mut landed: Vec<&str> = Vec::new();
5989        for field in &writes {
5990            let added = field
5991                .missing
5992                .iter()
5993                .map(|name| json!({"name": name, "color": "GRAY", "description": ""}));
5994            let sent = match before.fields.get(&field.field) {
5995                Some(held) => {
5996                    let mut options = held
5997                        .options
5998                        .iter()
5999                        .map(|option| {
6000                            json!({
6001                                "id": option.id, "name": option.name, "color": option.color,
6002                                "description": option.description,
6003                            })
6004                        })
6005                        .collect::<Vec<_>>();
6006                    options.extend(added);
6007                    self.graphql(
6008                        graphql::STATUS_OPTIONS_UPDATE,
6009                        json!({"input": {
6010                            "fieldId": held.field_id,
6011                            "singleSelectOptions": options,
6012                        }}),
6013                    )
6014                    .await
6015                }
6016                None => {
6017                    self.graphql(
6018                        graphql::CREATE_FIELD,
6019                        json!({"input": {
6020                            "projectId": before.board_id, "dataType": "SINGLE_SELECT",
6021                            "name": field.field.name(),
6022                            "singleSelectOptions": added.collect::<Vec<_>>(),
6023                        }}),
6024                    )
6025                    .await
6026                }
6027            };
6028            // A mutation that failed does not establish that GitHub left its field as it was,
6029            // so every failure from here on carries the recovery data a drift refusal does.
6030            match sent {
6031                Ok(_) => landed.push(field.field.name()),
6032                Err(error) => {
6033                    let changed = if landed.is_empty() {
6034                        String::new()
6035                    } else {
6036                        format!("changed the {} field and then ", landed.join(" and "))
6037                    };
6038                    return Err(SourceError::Refused {
6039                        message: format!(
6040                            "the guarded field setup {changed}failed on the {} field, which it may \
6041                             have changed part way: {error}; the pre-write item assignments \
6042                             are:\n{}",
6043                            field.field.name(),
6044                            recovery(&report, &before)?
6045                        ),
6046                    });
6047                }
6048            }
6049        }
6050        for field in &creates {
6051            let sent = self
6052                .graphql(
6053                    graphql::CREATE_FIELD,
6054                    json!({"input": {
6055                        "projectId": before.board_id, "dataType": "TEXT", "name": field.field,
6056                    }}),
6057                )
6058                .await;
6059            if let Err(error) = sent {
6060                let changed = if landed.is_empty() {
6061                    String::new()
6062                } else {
6063                    format!("changed the {} field and then ", landed.join(" and "))
6064                };
6065                return Err(SourceError::Refused {
6066                    message: format!(
6067                        "the guarded field setup {changed}failed creating the {} text field: \
6068                         {error}; run it again to create what is still missing",
6069                        field.field
6070                    ),
6071                });
6072            }
6073            landed.push(&field.field);
6074        }
6075        // The board has been written, so a verification read that fails leaves it unverified
6076        // rather than unchanged, and says what to put back.
6077        let after = match self.board_snapshot(&owned).await {
6078            Ok(after) => after,
6079            Err(error) => {
6080                return Err(SourceError::Refused {
6081                    message: format!(
6082                        "the guarded field setup changed the {} field and then could not read the \
6083                         board back to verify it: {error}; the pre-write item assignments are:\n{}",
6084                        landed.join(" and "),
6085                        recovery(&report, &before)?
6086                    ),
6087                });
6088            }
6089        };
6090        let mut moved = Vec::new();
6091        for field in &report.fields {
6092            let name = field.field.name();
6093            let now = after
6094                .fields
6095                .get(&field.field)
6096                .map(|held| held.options.as_slice())
6097                .unwrap_or_default();
6098            if !field.existing.iter().all(|old| now.contains(old)) {
6099                moved.push(format!(
6100                    "a pre-existing {name} option id, name, color or description"
6101                ));
6102            }
6103            if !field.missing.iter().all(|wanted| {
6104                now.iter()
6105                    .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
6106            }) {
6107                moved.push(format!("an added {name} option"));
6108            }
6109            if after.assignments(field.field) != before.assignments(field.field) {
6110                moved.push(format!("an item's {name} value"));
6111            }
6112        }
6113        if !creates.is_empty() {
6114            // Read afresh: the view held for this command is the one from before the creates.
6115            *self.fields_cache()? = None;
6116            let board = match self.board_fields().await {
6117                Ok(board) => board,
6118                Err(error) => {
6119                    return Err(SourceError::Refused {
6120                        message: format!(
6121                            "the guarded field setup changed the {} field and then could not \
6122                             read the board back to verify it: {error}; run it again to verify \
6123                             it, which creates nothing a second time",
6124                            landed.join(" and ")
6125                        ),
6126                    });
6127                }
6128            };
6129            for field in &creates {
6130                let text = Board::field(&board.fields, &field.field)?.is_some_and(|held| {
6131                    held.get("__typename").and_then(Value::as_str) == Some("ProjectV2Field")
6132                        && held.get("dataType").and_then(Value::as_str) == Some("TEXT")
6133                });
6134                if !text {
6135                    moved.push(format!("the created {} text field", field.field));
6136                }
6137            }
6138        }
6139        if !moved.is_empty() {
6140            return Err(SourceError::Refused {
6141                message: format!(
6142                    "GitHub changed {} after the guarded field setup; the pre-write item \
6143                     assignments are:\n{}",
6144                    moved.join(", "),
6145                    recovery(&report, &before)?
6146                ),
6147            });
6148        }
6149        Ok(report)
6150    }
6151
6152    /// Validate configuration and capture the named credential without exposing it.
6153    ///
6154    /// # Errors
6155    ///
6156    /// Returns [`SourceError::Config`] for a configuration this instance cannot use and
6157    /// [`SourceError::Auth`] when the named credential is missing or empty.
6158    pub fn new(
6159        name: &SourceName,
6160        config: GitHubProjectsConfig,
6161        secrets: &dyn SecretResolver,
6162    ) -> Result<Self, SourceError> {
6163        Self::recording_into(name, config, secrets, Arc::new(Accounting::new()))
6164    }
6165
6166    /// The same, recording every request it sends into an accounting the caller holds too.
6167    ///
6168    /// [`Self::new`] is this with an accounting of its own. A caller that is also making
6169    /// its own calls to GitHub — a lane verifying a schema, sweeping residue or cleaning
6170    /// up — passes the one it records those into, so the session total accounts for the
6171    /// whole session rather than for this source's share of it.
6172    ///
6173    /// # Errors
6174    ///
6175    /// Exactly [`Self::new`]'s: [`SourceError::Config`] for a configuration this instance
6176    /// cannot use and [`SourceError::Auth`] when the named credential is missing or empty.
6177    pub fn recording_into(
6178        name: &SourceName,
6179        config: GitHubProjectsConfig,
6180        secrets: &dyn SecretResolver,
6181        ledger: Arc<Accounting>,
6182    ) -> Result<Self, SourceError> {
6183        if !valid_github_owner(&config.owner) {
6184            return Err(SourceError::Config {
6185                message: "owner must be 1-39 ASCII letters, digits, or single hyphens, and cannot start or end with a hyphen".into(),
6186            });
6187        }
6188        if config.project_number == 0 || config.project_number > i32::MAX as u32 {
6189            return Err(SourceError::Config {
6190                message: format!("project_number must be between 1 and {}", i32::MAX),
6191            });
6192        }
6193        if !valid_environment_name(&config.token_env) {
6194            return Err(SourceError::Config {
6195                message: "token_env must be a valid environment-variable name".into(),
6196            });
6197        }
6198        let repository = config
6199            .repository
6200            .as_deref()
6201            .map(RepositoryTarget::parse)
6202            .transpose()?;
6203        if let Some(entry) = config
6204            .creation_owners
6205            .iter()
6206            .find(|entry| !valid_github_owner(entry))
6207        {
6208            return Err(SourceError::Config {
6209                message: format!(
6210                    "creation_owners entry {entry:?} is not a GitHub login: a login is 1-39 ASCII \
6211                     letters, digits, or single hyphens, and cannot start or end with a hyphen"
6212                ),
6213            });
6214        }
6215        let endpoint = Url::parse(&config.endpoint).map_err(|e| SourceError::Config {
6216            message: format!("endpoint is not a valid URL: {e}"),
6217        })?;
6218        if endpoint.scheme() != "https"
6219            && !(endpoint.scheme() == "http"
6220                && endpoint
6221                    .host_str()
6222                    .is_some_and(|h| h == "127.0.0.1" || h == "localhost" || h == "::1"))
6223        {
6224            return Err(SourceError::Config {
6225                message:
6226                    "endpoint must use HTTPS (HTTP is accepted only for a loopback test server)"
6227                        .into(),
6228            });
6229        }
6230        let token = secrets.get(&config.token_env).filter(|token| !token.expose_secret().trim().is_empty()).ok_or_else(|| SourceError::Auth {
6231            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),
6232        })?;
6233        Ok(Self {
6234            name: name.clone(),
6235            owner: config.owner,
6236            project_number: config.project_number,
6237            repository,
6238            creation_owners: config.creation_owners,
6239            asset_client: std::sync::OnceLock::new(),
6240            body_markup: std::sync::OnceLock::new(),
6241            endpoint,
6242            token,
6243            credential_name: config.token_env,
6244            statuses: BoardStatuses::resolve(&config.status_mapping, name)?,
6245            priorities: config
6246                .priority_mapping
6247                .map(|mapping| PriorityMapping::resolve(mapping, name))
6248                .transpose()?,
6249            metadata_fields: MetadataField::resolve(config.metadata_fields, name)?,
6250            sub_issues: config.sub_issues,
6251            assignees: config.assignees,
6252            people: Mutex::new(BTreeMap::new()),
6253            forgotten: Mutex::new(Vec::new()),
6254            spellings: Mutex::new(BTreeMap::new()),
6255            link_types: onetaskgraph_plugin_api::LinkTypes::checked(
6256                KIND,
6257                &config.link_types,
6258                &[relations::RELATES_TO],
6259                relations::REFUSED_WORDS,
6260            )
6261            .map_err(|error| match error {
6262                SourceError::Config { message } => SourceError::Config {
6263                    message: format!("source {name}: {message}"),
6264                },
6265                other => other,
6266            })?,
6267            client: std::sync::OnceLock::new(),
6268            created: Mutex::new(Vec::new()),
6269            updated: Mutex::new(Vec::new()),
6270            commented: Mutex::new(Vec::new()),
6271            pacing: Pacing::resolve(config.pacing, name)?,
6272            last_mutation: Mutex::new(None),
6273            last_served: Mutex::new(None),
6274            windows: Mutex::new(pacing::Windows::default()),
6275            task_children: Mutex::new(BTreeMap::new()),
6276            written: Mutex::new(BTreeMap::new()),
6277            deferred: Mutex::new(None),
6278            held_updates: Mutex::new(Vec::new()),
6279            held_comments: Mutex::new(BTreeMap::new()),
6280            task_writes: Mutex::new(None),
6281            written_tokens: Mutex::new(BTreeMap::new()),
6282            clock: system_clock(),
6283            declared_private: std::sync::atomic::AtomicBool::new(false),
6284            numeric_repositories: tokio::sync::Mutex::new(BTreeMap::new()),
6285            board_cache: Mutex::new(None),
6286            search_cache: Mutex::new(None),
6287            narrowed_cache: Mutex::new(BTreeMap::new()),
6288            resolved_cache: Mutex::new(BTreeMap::new()),
6289            read_ahead: Mutex::new(BTreeMap::new()),
6290            pending_origins: Mutex::new(Vec::new()),
6291            member_classes: Mutex::new(BTreeMap::new()),
6292            carried: Mutex::new(BTreeMap::new()),
6293            held_cache: Mutex::new(BTreeMap::new()),
6294            children_cache: Mutex::new(BTreeMap::new()),
6295            search_rows: Mutex::new(BTreeMap::new()),
6296            search_next: Mutex::new(BTreeMap::new()),
6297            fields_cache: Mutex::new(None),
6298            repository_cache: Mutex::new(BTreeMap::new()),
6299            ledger,
6300            expected: expected::Held::default(),
6301            projection: projection::Held::default(),
6302        })
6303    }
6304
6305    /// The client every API request goes through, built on the first one.
6306    ///
6307    /// Not with the source: building a client loads the system's certificate store, which
6308    /// costs tens of milliseconds, and a command that configures this board but never sends to
6309    /// it — a read of another source — should not pay that in its process.
6310    fn client(&self) -> Result<&Client, SourceError> {
6311        built(&self.client, || {
6312            Client::builder()
6313                .user_agent("onetaskgraph")
6314                .build()
6315                .map_err(|e| SourceError::Config {
6316                    message: format!("cannot build HTTP client: {e}"),
6317                })
6318        })
6319    }
6320
6321    /// The client attachment requests go through, with its own redirect policy, built on the
6322    /// first one for the reason [`Self::client`] gives.
6323    fn asset_client(&self) -> Result<&Client, SourceError> {
6324        built(&self.asset_client, || assets::client(&self.endpoint))
6325    }
6326
6327    /// A snapshot of every request this source has sent, and what each cost.
6328    ///
6329    /// A value to hold and compare rather than a borrow of the accounting itself, so two
6330    /// of them can sit side by side. When this source was built with
6331    /// [`Self::recording_into`] the snapshot is the whole shared session, which is the
6332    /// point of building it that way.
6333    #[must_use]
6334    pub fn accounting(&self) -> accounting::Session {
6335        self.ledger.snapshot()
6336    }
6337
6338    /// Send one GraphQL document, pacing this source's own mutations and waiting out a
6339    /// rate limit rather than handing it straight back as an error.
6340    ///
6341    /// Retrying is safe for every document here, including the mutations, and the reason
6342    /// is that only a *refusal* is retried: [`Limiter::classify`] rules on a response
6343    /// GitHub sent, and a request GitHub refused for a rate limit did not run, so nothing
6344    /// this replays has already taken effect. An outcome this source cannot know — the
6345    /// send failed, or the body could not be read, so the mutation may well have landed —
6346    /// is [`Attempt::Failed`] in [`send_once`] and leaves this loop without a second
6347    /// attempt. A duplicate write would come from replaying one of those, and none is
6348    /// replayed.
6349    async fn graphql(&self, query: &str, variables: Value) -> Result<Value, SourceError> {
6350        // Updates held back go out before any other request, so whatever it reads or writes
6351        // sees the board as though each had been sent when it was made.
6352        Box::pin(self.send_held_updates()).await?;
6353        // Origins held back for a read ahead that never came are sent before anything else.
6354        if query != graphql::ORIGIN_LOOKUPS && query != graphql::ORIGIN_LOOKUPS_WITH_MEMBERS {
6355            Box::pin(self.send_pending_origins(None)).await?;
6356        }
6357        let journaling = self.expected.journaling();
6358        let spelling = self.spelling();
6359        if !journaling && !spelling {
6360            return self.graphql_sent(query, variables).await;
6361        }
6362        // While a write the store's cache expects runs, its mutations select the whole issue
6363        // they leave behind, so the response vouches for what the cache keeps — and every
6364        // request is recorded, so the write's parts are reported from their own responses.
6365        // A targeted update sends a twin of each selecting the issue's token parts inline, at
6366        // the same price, so the version it answers is the one its own last response spells.
6367        let (query, variables) = match (journaling, graphql::whole_twin(query)) {
6368            (true, Some(twin)) => (twin, expected::whole_variables(variables)),
6369            _ => match graphql::token_twin(query).filter(|_| spelling) {
6370                Some(twin) => (twin, token_variables(variables)),
6371                None => (query, variables),
6372            },
6373        };
6374        let sent = self.graphql_sent(query, variables.clone()).await;
6375        if spelling && let Ok(data) = &sent {
6376            self.record_written_token(query, &variables, data);
6377        }
6378        if journaling {
6379            self.journal(query, &variables, &sent).await;
6380        }
6381        sent
6382    }
6383
6384    /// Whether a targeted update of this source is running, whose mutations are each sent as
6385    /// the twin selecting the whole issue (see [`Self::written_tokens`]).
6386    fn spelling(&self) -> bool {
6387        SPELLING
6388            .try_with(|source| *source == std::ptr::from_ref(self) as usize)
6389            .unwrap_or(false)
6390    }
6391
6392    /// Record the change token the issue a mutation's response shows whole holds now, as
6393    /// [`TaskSource::written_task`] answers it; a response showing no whole issue records
6394    /// nothing.
6395    fn record_written_token(&self, document: &str, variables: &Value, data: &Value) {
6396        let (issue, _) = expected::read_back(document, variables, data);
6397        if let Some(issue) = issue {
6398            self.record_written_issue(issue);
6399        }
6400    }
6401
6402    /// Record the change token `issue`, as a write's own answer shows it whole, holds now — or,
6403    /// where that answer lacks a part of one, that it was shown and spells none.
6404    fn record_written_issue(&self, issue: &Value) {
6405        // An answer naming the issue by its id alone did not show it, so it says nothing.
6406        if issue.get("updatedAt").is_none() {
6407            return;
6408        }
6409        let Some(id) = issue.get("id").and_then(Value::as_str) else {
6410            return;
6411        };
6412        let (item, token) = match self.written_token_of(issue) {
6413            Some((item, token)) => (item, Some(token)),
6414            None => {
6415                // Answered whole, but without every part of a token: its board item's id, where
6416                // it says one, so a later write naming that item still drops the entry.
6417                let item = issue
6418                    .pointer("/projectItems/nodes")
6419                    .and_then(Value::as_array)
6420                    .and_then(|nodes| self.board_entry(nodes))
6421                    .and_then(|entry| entry.get("id"))
6422                    .and_then(Value::as_str)
6423                    .unwrap_or_default()
6424                    .to_owned();
6425                (item, None)
6426            }
6427        };
6428        if let Ok(mut tokens) = self.written_tokens.lock() {
6429            tokens.insert(NativeId(id.to_owned()), (item, token));
6430        }
6431    }
6432
6433    /// Record `token` as the change token the task `item` holds after this command's write.
6434    fn remember_written_token(&self, item: &Resolved, token: String) {
6435        if let Ok(mut tokens) = self.written_tokens.lock() {
6436            tokens.insert(item.id.clone(), (item.item_id.clone(), Some(token)));
6437        }
6438    }
6439
6440    /// The change token the task `id` holds after this command's latest write of it, when that
6441    /// write's own response — or the read made right after it — showed one.
6442    fn written_token(&self, id: &NativeId) -> Option<String> {
6443        self.written_answer(id).flatten()
6444    }
6445
6446    /// What this command's latest write of the task `id` showed of it: `Some` once a response
6447    /// showed the issue whole — its token, or `None` where that response could not spell one —
6448    /// and `None` where no response did.
6449    fn written_answer(&self, id: &NativeId) -> Option<Option<String>> {
6450        self.written_tokens
6451            .lock()
6452            .ok()?
6453            .get(id)
6454            .map(|(_, token)| token.clone())
6455    }
6456
6457    /// Drop the written token of every task `variables` names, by its id or its board item's,
6458    /// before a mutation that may move it is sent.
6459    fn forget_written_tokens(&self, variables: &Value) {
6460        let Ok(mut tokens) = self.written_tokens.lock() else {
6461            return;
6462        };
6463        if tokens.is_empty() {
6464            return;
6465        }
6466        let named: Vec<&str> = variables
6467            .as_object()
6468            .into_iter()
6469            .flat_map(|arguments| arguments.values())
6470            .flat_map(|input| {
6471                WRITTEN_NAMES
6472                    .iter()
6473                    .filter_map(|key| input.get(key).and_then(Value::as_str))
6474            })
6475            .collect();
6476        tokens.retain(|id, (item, _)| {
6477            !named
6478                .iter()
6479                .any(|name| *name == id.0 || *name == item.as_str())
6480        });
6481    }
6482
6483    /// One document sent, retried while GitHub asks for a wait, exactly as asked.
6484    async fn graphql_sent(&self, query: &str, variables: Value) -> Result<Value, SourceError> {
6485        if is_mutation(query) {
6486            self.forget_written_tokens(&variables);
6487        }
6488        if is_mutation(query)
6489            && ![
6490                graphql::ADD_COMMENT,
6491                graphql::UPDATE_COMMENT,
6492                graphql::DELETE_COMMENT,
6493                graphql::ADD_COMMENT_WHOLE,
6494                graphql::UPDATE_COMMENT_WHOLE,
6495            ]
6496            .contains(&query)
6497        {
6498            let mut cache = self.resolved_cache()?;
6499            let mut ahead = self.read_ahead()?;
6500            let mut carried = self.carried()?;
6501            for argument in ["input", "second", "third", "clear"] {
6502                if let Some(input) = variables.get(argument) {
6503                    let names = |id: &NativeId, item_id: Option<&str>| {
6504                        ["id", "issueId", "subjectId", "itemId"].iter().any(|key| {
6505                            input
6506                                .get(key)
6507                                .and_then(Value::as_str)
6508                                .is_some_and(|value| value == id.0 || Some(value) == item_id)
6509                        })
6510                    };
6511                    cache.retain(|id, item| !names(id, Some(&item.item_id)));
6512                    ahead.retain(|id, item| {
6513                        !names(id, item.as_ref().map(|item| item.item_id.as_str()))
6514                    });
6515                    carried.retain(|id, item| !names(id, Some(&item.item_id)));
6516                }
6517            }
6518        }
6519        let doing = operation_description(query);
6520        let mutation = is_mutation(query);
6521        let charge = pacing::Charge::graphql(query, &variables);
6522        let mut waited = Duration::ZERO;
6523        let mut waits = 0_u32;
6524        let mut backoff = self.pacing.retry_backoff;
6525        loop {
6526            let ticket = self.pace(charge, mutation).await;
6527            // Every write but a create is asked for immediately before it is sent — a create's
6528            // fields, its relationships, its content and the delete that takes it back included
6529            // — so a copy that owns the create renews its hold first, and one that has lost it
6530            // sends nothing more. Asked again before a retry, which is sent later.
6531            if mutation
6532                && !query.contains("createIssue(")
6533                && let Err(refused) = <dyn onetaskgraph_plugin_api::WriteGuard>::check().await
6534            {
6535                self.paced(ticket, mutation);
6536                return Err(refused);
6537            }
6538            // And of a caller's request gate, before every request this source sends — a retry
6539            // as its own — so a caller pacing its own floor inside one call waits or stops here.
6540            let admitted = match <dyn onetaskgraph_plugin_api::RequestGate>::before(&gated_graphql(
6541                query, &variables,
6542            ))
6543            .await
6544            {
6545                Ok(admitted) => admitted,
6546                Err(refused) => {
6547                    self.paced(ticket, mutation);
6548                    return Err(refused);
6549                }
6550            };
6551            let (attempt, cost) = self.send_once(query, &variables, waits + 1).await;
6552            // Over however it ended — answered, refused or failed before any header — and
6553            // ended before any wait for a retry, which is asked for as a request of its own;
6554            // an answered read is first told to the gate with what GitHub said it cost, after
6555            // the readings its response carried.
6556            match cost {
6557                Some(cost) => admitted.end_reporting(&onetaskgraph_plugin_api::ReportedCost {
6558                    resource: accounting::Budget::Graphql.name().to_owned(),
6559                    cost,
6560                }),
6561                None => admitted.end(),
6562            }
6563            self.paced(ticket, mutation);
6564            let remaining = self.pacing.retry_budget.saturating_sub(waited);
6565            let (wait, cause) = match attempt {
6566                Ok(data) => return Ok(data),
6567                Err(Attempt::Failed(error)) => return Err(error),
6568                Err(Attempt::Conflicted(said)) => {
6569                    // A create is never replayed: see `CONFLICT_WORDINGS`.
6570                    if query.contains("createIssue(") || backoff.is_zero() || backoff > remaining {
6571                        return Err(SourceError::Unavailable {
6572                            message: format!(
6573                                "GitHub refused this source while {doing} as a temporary \
6574                                 conflict ({said}); it retried {} over {} and the conflict \
6575                                 did not clear within the {} one call may spend waiting. \
6576                                 next: run the command again once nothing else is writing to \
6577                                 the same items",
6578                                plural(waits, "time"),
6579                                seconds(waited),
6580                                seconds(self.pacing.retry_budget),
6581                            ),
6582                        });
6583                    }
6584                    (backoff, pacing::cause::BACKOFF)
6585                }
6586                Err(Attempt::Limited(limited)) => {
6587                    let (wait, cause) = limited.wait(backoff);
6588                    // A wait of nothing spends none of the budget, so it is exhaustion rather
6589                    // than a retry. `Pacing::resolve` rules out every way of configuring one
6590                    // except a budget of zero, where reporting the first refusal is the ask.
6591                    if wait.is_zero() || wait > remaining {
6592                        return Err(limited.exhausted(
6593                            doing,
6594                            waits,
6595                            waited,
6596                            wait,
6597                            self.pacing.retry_budget,
6598                        ));
6599                    }
6600                    (wait, cause)
6601                }
6602            };
6603            self.clock.sleep_because(wait, cause).await;
6604            waited += wait;
6605            waits += 1;
6606            backoff = backoff.saturating_mul(2);
6607        }
6608    }
6609
6610    /// Hold one request charging `charge` until every secondary window it charges has room for
6611    /// the whole of it — and, for a mutation of an instance configured with
6612    /// `pacing.min_mutation_interval_ms`, until that interval has passed since the last one
6613    /// finished — then count it, answering the ticket [`Self::paced`] finishes it with.
6614    ///
6615    /// The moment is decided and counted under the lock and waited out outside it, so two
6616    /// callers take two places rather than the same one, and no lock is held across an await.
6617    /// A request with room goes out at once: nothing here waits that a window does not ask for.
6618    async fn pace(&self, charge: pacing::Charge, mutation: bool) -> pacing::Ticket {
6619        let (wait, cause, ticket) = {
6620            // A poisoned lock here costs pacing, not correctness, and refusing the write over
6621            // it would turn an earlier failure into a second one for no gain.
6622            let mut windows = self
6623                .windows
6624                .lock()
6625                .unwrap_or_else(std::sync::PoisonError::into_inner);
6626            let now = self.clock.now();
6627            let (mut at, mut cause) = if self.pacing.windows {
6628                windows.room(now, charge)
6629            } else {
6630                (now, None)
6631            };
6632            if mutation && !self.pacing.min_mutation_interval.is_zero() {
6633                let mut last = self
6634                    .last_mutation
6635                    .lock()
6636                    .unwrap_or_else(std::sync::PoisonError::into_inner);
6637                // `checked_add` rather than `+`: adding durations can panic on overflow, and
6638                // pacing is not worth a panic even at a bound `MAX_PACING_MS` already rules out.
6639                if let Some(earliest) = last
6640                    .and_then(|previous| previous.checked_add(self.pacing.min_mutation_interval))
6641                    && earliest > at
6642                {
6643                    at = earliest;
6644                    cause = Some(pacing::cause::MIN_INTERVAL);
6645                }
6646                *last = Some(at);
6647            }
6648            let ticket = windows.charge(at, charge);
6649            (at.saturating_sub(now), cause, ticket)
6650        };
6651        if let (false, Some(cause)) = (wait.is_zero(), cause) {
6652            self.clock.sleep_because(wait, cause).await;
6653        }
6654        ticket
6655    }
6656
6657    /// Record that the request `ticket` was charged for has finished, so each window — and
6658    /// the configured spacing — counts it from here rather than from the moment it left.
6659    ///
6660    /// This source can only choose when a request *departs*; GitHub's limiter counts when it
6661    /// *arrives*, and the two differ by whatever the request spent in transit. Counting from
6662    /// departure would hand the limiter a window that looked roomier than it is, so a source
6663    /// pacing exactly at a limit could still be seen arriving over it — which is how a copy
6664    /// paced well inside a board's threshold was once refused by it on a slower machine while
6665    /// passing on a quick one. The previous request had arrived before its response came back,
6666    /// so counting from here is never earlier than the limiter does, whatever transit costs
6667    /// and on whatever platform: the safe side of a limit that punishes being wrong by refusing
6668    /// reads for the next fifty minutes.
6669    ///
6670    /// A failed attempt is finished too: a request refused by the limiter still arrived, and
6671    /// one that never left costs only room nobody needed.
6672    fn paced(&self, ticket: pacing::Ticket, mutation: bool) {
6673        let now = self.clock.now();
6674        self.windows
6675            .lock()
6676            .unwrap_or_else(std::sync::PoisonError::into_inner)
6677            .finish(ticket, now);
6678        if mutation && !self.pacing.min_mutation_interval.is_zero() {
6679            let mut last = self
6680                .last_mutation
6681                .lock()
6682                .unwrap_or_else(std::sync::PoisonError::into_inner);
6683            // `max` rather than an assignment: a concurrent caller may already have reserved a
6684            // slot further out, and completing this request must never pull that slot back in.
6685            *last = Some(last.map_or(now, |reserved| reserved.max(now)));
6686        }
6687    }
6688
6689    /// One HTTP attempt, classified into an answer, a rate limit to wait out, or a
6690    /// failure that waiting cannot help — and recorded, whichever of the three it was.
6691    ///
6692    /// This is the one place a request leaves this crate, which is why the accounting is
6693    /// here rather than at each of the callers: a read path added later is counted without
6694    /// anybody remembering to count it, and
6695    /// `the_session_report_counts_every_request_the_board_served_and_what_each_cost` fails
6696    /// when one is not.
6697    async fn send_once(
6698        &self,
6699        query: &str,
6700        variables: &Value,
6701        number: u32,
6702    ) -> (Result<Value, Attempt>, Option<u64>) {
6703        // A lookup goes out sized to the people it names, and the record names and counts it as
6704        // what it is; everything that decides how it is retried or read compares `query`, the
6705        // constant it was written as.
6706        let sized = graphql::sized(query, variables);
6707        // Every read asks GitHub what it cost, so the gate and the ledger are told the
6708        // request's own charge rather than a model of it.
6709        let executed: std::borrow::Cow<'_, str> = match graphql::with_reported_cost(&sized) {
6710            Some(priced) => std::borrow::Cow::Owned(priced),
6711            None => std::borrow::Cow::Borrowed(sized.as_ref()),
6712        };
6713        let Attempted {
6714            result,
6715            limits,
6716            reported_cost,
6717            response_outcome,
6718        } = self
6719            .attempt(sized.as_ref(), executed.as_ref(), variables)
6720            .await;
6721        // No `otherwise` name: every document this source sends is one of its own, and the
6722        // inventory gate on `graphql::DOCUMENTS` is what keeps that true.
6723        let sending = accounting::Request::graphql(sized.as_ref(), variables, None, reported_cost);
6724        let outcome = match &result {
6725            Ok(_) => accounting::Outcome::Answered,
6726            Err(Attempt::Limited(_)) => accounting::Outcome::RateLimited,
6727            Err(Attempt::Failed(_) | Attempt::Conflicted(_)) => accounting::Outcome::Refused,
6728        };
6729        self.ledger
6730            .record(sending.finished(outcome, limits).with_execution(
6731                Some(executed.into_owned()),
6732                response_outcome,
6733                number,
6734            ));
6735        // Only an answered request's cost is the gate's to be told: a refused or failed one
6736        // delivers none, whatever its body said.
6737        let answered_cost = reported_cost.filter(|_| result.is_ok());
6738        (result, answered_cost)
6739    }
6740
6741    /// The attempt itself, with what its response said about the rate limit alongside.
6742    ///
6743    /// The two are returned together rather than recorded here because every one of the
6744    /// early exits below is a different outcome, and a record written at each of them is a
6745    /// record one of them can be added without.
6746    async fn attempt(&self, query: &str, executed: &str, variables: &Value) -> Attempted {
6747        let mut limits = accounting::RateLimit::default();
6748        let mut reported_cost = None;
6749        let mut response_outcome = accounting::ResponseOutcome::TransportError;
6750        // Spelled here, at the one place a document leaves for GitHub, and nowhere earlier:
6751        // everything that decides how a document is retried or how its answer is read compares
6752        // it with the constant it was written as.
6753        // `query` is the document as written, which decides how the answer is read; `executed`
6754        // is that document selecting its own cost, which is what is sent.
6755        let spelled = self
6756            .assignees
6757            .then(|| graphql::with_assignees(executed))
6758            .flatten();
6759        let result = self
6760            .attempted(
6761                query,
6762                spelled.as_deref().unwrap_or(executed),
6763                variables,
6764                &mut limits,
6765                &mut reported_cost,
6766                &mut response_outcome,
6767            )
6768            .await;
6769        Attempted {
6770            result,
6771            limits,
6772            reported_cost,
6773            response_outcome,
6774        }
6775    }
6776
6777    /// One HTTP attempt, filling in what its response said about the rate limit as it goes.
6778    async fn attempted(
6779        &self,
6780        query: &str,
6781        sent: &str,
6782        variables: &Value,
6783        limits: &mut accounting::RateLimit,
6784        reported_cost: &mut Option<u64>,
6785        response_outcome: &mut accounting::ResponseOutcome,
6786    ) -> Result<Value, Attempt> {
6787        let response = self
6788            .client()
6789            .map_err(Attempt::Failed)?
6790            .post(self.endpoint.clone())
6791            .bearer_auth(self.token.expose_secret())
6792            .json(&json!({"query": sent, "variables": variables}))
6793            .send()
6794            .await
6795            .map_err(|e| {
6796                Attempt::Failed(SourceError::Unavailable {
6797                    message: format!("GitHub GraphQL request failed: {}", transport_error(&e)),
6798                })
6799            })?;
6800        let status = response.status();
6801        if !status.is_success() {
6802            *response_outcome = accounting::ResponseOutcome::HttpError;
6803        }
6804        let header = |name: &str| whole_seconds(response.headers().get(name));
6805        let served = response
6806            .headers()
6807            .get(reqwest::header::DATE)
6808            .and_then(|value| value.to_str().ok())
6809            .and_then(|value| DateTime::parse_from_rfc2822(value).ok())
6810            .map(|at| at.with_timezone(&Utc));
6811        *limits = accounting::RateLimit::read(|name| {
6812            response
6813                .headers()
6814                .get(name)
6815                .and_then(|value| value.to_str().ok())
6816                .map(str::to_owned)
6817        });
6818        // Each response's own reading, as it gave it: never merged with another window's.
6819        <dyn onetaskgraph_plugin_api::RequestGate>::after(&quota::header_readings(limits));
6820        // Exactly `0` is exhaustion and everything else — a count, an empty value, bytes
6821        // that are not text at all — is "not known to be exhausted". This never makes a
6822        // response a refusal on its own: it says which limiter a refusal is attributed to
6823        // and where its hint comes from, so a value this cannot read costs a hint rather
6824        // than an answer.
6825        let exhausted = response
6826            .headers()
6827            .get("x-ratelimit-remaining")
6828            .and_then(|value| value.to_str().ok())
6829            == Some("0");
6830        // `retry-after` is what GitHub asks for when it asks; when it does not and the
6831        // primary budget is spent, `x-ratelimit-reset` says when that budget comes back,
6832        // which is the same question answered as an absolute time. Nothing else here is a
6833        // hint, and a schedule is what answers a refusal that carries none.
6834        let retry_after = header("retry-after");
6835        let hinted_by = if retry_after.is_some() || !exhausted {
6836            Hint::RetryAfter
6837        } else {
6838            Hint::PrimaryReset
6839        };
6840        let hint = retry_after.or_else(|| {
6841            exhausted
6842                .then(|| header("x-ratelimit-reset"))
6843                .flatten()
6844                .map(|reset| reset.saturating_sub(Utc::now().timestamp().max(0).unsigned_abs()))
6845        });
6846        // Read before it is parsed, because the evidence which tells a secondary rate
6847        // limit from a rejected credential is in the body of a response whose status says
6848        // only "forbidden" — and a non-success response was never parsed at all.
6849        let body = response.text().await.map_err(|e| {
6850            Attempt::Failed(SourceError::Unavailable {
6851                message: format!(
6852                    "GitHub GraphQL response could not be read: {}",
6853                    transport_error(&e)
6854                ),
6855            })
6856        })?;
6857        let parsed = serde_json::from_str::<Value>(&body).ok();
6858        *reported_cost = parsed.as_ref().and_then(|body| {
6859            let data = body.get("data")?;
6860            graphql::reported_cost(data).or_else(|| {
6861                data.get("rateLimit")
6862                    .and_then(|limit| limit.get("cost"))
6863                    .and_then(Value::as_u64)
6864            })
6865        });
6866        *response_outcome = accounting::ResponseOutcome::of_graphql_reply(status, parsed.as_ref());
6867        if let Some(limiter) = Limiter::classify(status, exhausted, &body) {
6868            return Err(Attempt::Limited(Limited {
6869                limiter,
6870                hint,
6871                hinted_by,
6872            }));
6873        }
6874        if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
6875            return Err(Attempt::Failed(SourceError::Auth {
6876                message: format!(
6877                    "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"
6878                ),
6879            }));
6880        }
6881        if !status.is_success() {
6882            return Err(Attempt::Failed(SourceError::Unavailable {
6883                message: format!("GitHub GraphQL returned HTTP {status}"),
6884            }));
6885        }
6886        let said = refusal_wording(status, &body);
6887        let normalized = said.to_ascii_lowercase();
6888        if CONFLICT_WORDINGS
6889            .iter()
6890            .any(|wording| normalized.contains(wording))
6891        {
6892            return Err(Attempt::Conflicted(said));
6893        }
6894        // A lookup is read as the inventoried document it was sized from.
6895        let query = graphql::inventoried(query);
6896        let answered = if query == graphql::ISSUES_BY_REFERENCE {
6897            self.answer_unresolved(&body)
6898        } else if [
6899            graphql::CREATE_ISSUES,
6900            graphql::SEARCH_BATCH,
6901            graphql::USER_IDS,
6902            graphql::ADD_COMMENTS,
6903            graphql::WRITE_TASKS,
6904            graphql::SET_PARENTS,
6905            graphql::ADD_RELATES_TO,
6906            graphql::REMOVE_RELATES_TO,
6907        ]
6908        .contains(&query)
6909        {
6910            answer_with_errors(&body).map_or_else(|| self.answer(&body), Ok)
6911        } else {
6912            self.answer(&body)
6913        };
6914        let mut data = answered.map_err(Attempt::Failed)?;
6915        // What GitHub said the request cost is the request's, never part of what it answered.
6916        graphql::forget_reported_cost(&mut data);
6917        if let Some(served) = served {
6918            *self
6919                .last_served
6920                .lock()
6921                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(served);
6922            stamp_served(&mut data, &served.to_rfc3339());
6923        }
6924        Ok(data)
6925    }
6926
6927    /// What one successful HTTP response says, once its GraphQL errors are read.
6928    /// [`Self::answer`], for a read of issues by reference: a reference GitHub cannot resolve
6929    /// for this credential — a repository it cannot see, an issue number it does not hold —
6930    /// is answered `null` beside a `NOT_FOUND` error naming it, and that is an answer about
6931    /// that reference rather than a failure of the others. Any other error refuses the read,
6932    /// as there.
6933    fn answer_unresolved(&self, body: &str) -> Result<Value, SourceError> {
6934        let parsed: Option<Value> = serde_json::from_str(body).ok();
6935        // Each error is a `NOT_FOUND` whose path names one slot of the batch, `r<n>` or its
6936        // `issue`, and the answer holds `null` at exactly that path: anything else — another
6937        // kind of error, one naming no slot, or one beside a value it says is not there — is a
6938        // refusal of the whole read.
6939        let unresolved = |data: &Value, error: &Value| {
6940            error.get("type").and_then(Value::as_str) == Some("NOT_FOUND")
6941                && error
6942                    .get("path")
6943                    .and_then(Value::as_array)
6944                    .is_some_and(|path| {
6945                        let alias = path.first().and_then(Value::as_str).and_then(|alias| {
6946                            alias
6947                                .strip_prefix('r')
6948                                .and_then(|slot| slot.parse::<usize>().ok())
6949                                .filter(|slot| *slot < REFERENCE_BATCH)
6950                                .map(|_| alias)
6951                        });
6952                        match (alias, path.get(1).and_then(Value::as_str), path.len()) {
6953                            (Some(alias), None, 1) => data.get(alias).is_some_and(Value::is_null),
6954                            (Some(alias), Some("issue"), 2) => data
6955                                .get(alias)
6956                                .and_then(|repository| repository.get("issue"))
6957                                .is_some_and(Value::is_null),
6958                            _ => false,
6959                        }
6960                    })
6961        };
6962        let unresolved_only = parsed.as_ref().is_some_and(|parsed| {
6963            parsed.get("data").is_some_and(|data| {
6964                data.is_object()
6965                    && parsed
6966                        .get("errors")
6967                        .and_then(Value::as_array)
6968                        .is_some_and(|errors| errors.iter().all(|error| unresolved(data, error)))
6969            })
6970        });
6971        match parsed {
6972            Some(parsed) if unresolved_only => Ok(parsed["data"].clone()),
6973            _ => self.answer(body),
6974        }
6975    }
6976
6977    fn answer(&self, body: &str) -> Result<Value, SourceError> {
6978        let body: Value = serde_json::from_str(body).map_err(|e| SourceError::Malformed {
6979            message: format!("GitHub returned invalid JSON: {e}"),
6980        })?;
6981        let errors = body
6982            .get("errors")
6983            .map(|value| {
6984                value.as_array().ok_or_else(|| SourceError::Malformed {
6985                    message: "GitHub response errors is not an array".into(),
6986                })
6987            })
6988            .transpose()?;
6989        if let Some(errors) = errors.filter(|errors| !errors.is_empty()) {
6990            let messages = errors
6991                .iter()
6992                .filter_map(|e| e.get("message").and_then(Value::as_str))
6993                .collect::<Vec<_>>()
6994                .join("; ");
6995            let message = if messages.is_empty() {
6996                "GitHub returned GraphQL errors".into()
6997            } else {
6998                messages
6999            };
7000            let normalized = message.to_ascii_lowercase();
7001            if normalized.contains("resource not accessible") || normalized.contains("scope") {
7002                return Err(SourceError::Auth {
7003                    message: format!(
7004                        "{message}; grant {} Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board",
7005                        self.credential_name
7006                    ),
7007                });
7008            }
7009            return Err(SourceError::Refused { message });
7010        }
7011        body.get("data")
7012            .filter(|data| data.is_object())
7013            .cloned()
7014            .ok_or_else(|| SourceError::Malformed {
7015                message: "GitHub response has no data object".into(),
7016            })
7017    }
7018
7019    // llmlint: ignore[boundary_inputs_validated] GitHub caps nested connections at 100 and
7020    // GraphQL cannot independently page them inside the outer item page. This source page is
7021    // deliberately bounded at that published maximum; the live drift journey exercises it.
7022    async fn board_page(
7023        &self,
7024        items_after: Option<&str>,
7025        items_first: u32,
7026    ) -> Result<Value, SourceError> {
7027        let data = self
7028            .graphql(
7029                graphql::BOARD,
7030                json!({"owner":self.owner,"number":self.project_number,
7031                       "first":items_first.min(MAX_PAGE_SIZE),"after":items_after,
7032                       "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
7033            )
7034            .await?;
7035        data.pointer("/owner/projectV2")
7036            .filter(|v| !v.is_null())
7037            .cloned()
7038            .ok_or_else(|| SourceError::Refused {
7039                message: format!(
7040                    "GitHub project {}/{} was not found or is not visible to the token",
7041                    self.owner, self.project_number
7042                ),
7043            })
7044    }
7045
7046    /// The search that finds the issues of this board, narrowed by `also` when it is
7047    /// given.
7048    ///
7049    /// `project:owner/number` is what scopes a search to one board, and `is:issue` is what
7050    /// keeps pull requests out of it: GitHub's `ISSUE` search type covers both, and a pull
7051    /// request is somebody's change rather than a unit of plan. `-has:parent` is *not*
7052    /// here on purpose — GitHub accepts it and silently ignores it, so a project is told
7053    /// from a task by the `parent` field each issue carries rather than by the search.
7054    fn board_search(&self, also: Option<&str>) -> String {
7055        let scope = format!("project:{}/{} is:issue", self.owner, self.project_number);
7056        match also {
7057            Some(also) => format!("{scope} {also}"),
7058            None => scope,
7059        }
7060    }
7061
7062    /// One issue this source reached directly, as the board item a read of the board would
7063    /// have produced — or `None` when this board does not hold it.
7064    ///
7065    /// The board half of an issue rides along on `Issue.projectItems`, so the value handed
7066    /// to [`Self::resolve`] is the very shape a `ProjectV2.items` read gives it: the board
7067    /// item's own id, that item's field values, and the issue as its content. One resolver
7068    /// for both routes is what makes an issue read through a search, through its own node
7069    /// id, or through its project's sub-issues report the same title, the same status, the
7070    /// same labels and the same qualified id.
7071    ///
7072    /// An issue with no entry for *this* board is not this source's to report, which is
7073    /// what keeps an id naming some other repository's issue from being answered as an item
7074    /// of this board. That answer is given about an **exhausted** connection and never
7075    /// about an unread page: the entry is looked for on the page in hand, and only if that
7076    /// page reports more of the connection, in [`Self::board_membership`]'s walk of the
7077    /// rest of it.
7078    async fn resolve_issue(&self, issue: &Value) -> Result<Option<Resolved>, SourceError> {
7079        self.resolve_issue_as(issue, true).await
7080    }
7081
7082    /// [`Self::resolve_issue`], remembering what it resolves for this command's later reads
7083    /// and writes only when `remember` says to.
7084    async fn resolve_issue_as(
7085        &self,
7086        issue: &Value,
7087        remember: bool,
7088    ) -> Result<Option<Resolved>, SourceError> {
7089        if optional_str(issue, "__typename")? != Some("Issue") {
7090            return Ok(None);
7091        }
7092        let memberships = issue
7093            .get("projectItems")
7094            .ok_or_else(|| SourceError::Malformed {
7095                message: "GitHub issue is missing projectItems".into(),
7096            })?;
7097        let nodes = memberships
7098            .get("nodes")
7099            .and_then(Value::as_array)
7100            .ok_or_else(|| SourceError::Malformed {
7101                message: "GitHub issue projectItems.nodes is not an array".into(),
7102            })?;
7103        let held = match self.board_entry(nodes) {
7104            Some(held) => held.clone(),
7105            None => {
7106                let info = memberships
7107                    .get("pageInfo")
7108                    .ok_or_else(|| SourceError::Malformed {
7109                        message: "GitHub issue projectItems has no pageInfo".into(),
7110                    })?;
7111                // The page held no entry for this board. Whether that means the issue is
7112                // not on it is a question about the rest of the connection, and only a
7113                // connection with no rest answers it here.
7114                if !required_bool(info, "hasNextPage")? {
7115                    return Ok(None);
7116                }
7117                let cursor = required_str(info, "endCursor")?;
7118                validate_cursor_progress(None, cursor)?;
7119                let issue_id = required_str(issue, "id")?;
7120                match self.board_membership(issue_id, cursor).await? {
7121                    Some(held) => held,
7122                    None => return Ok(None),
7123                }
7124            }
7125        };
7126        // The membership's own `updatedAt` rides along: it is the board half of the item's change
7127        // token, which a field change moves where the issue's own time does not.
7128        let item = json!({
7129            "id": required_str(&held, "id")?,
7130            "updatedAt": held.get("updatedAt"),
7131            "project": held.get("project"),
7132            "fieldValues": held.get("fieldValues"),
7133            "content": issue,
7134        });
7135        if remember {
7136            self.resolve(&item)
7137        } else {
7138            self.resolve_unremembered(&item)
7139        }
7140    }
7141
7142    /// This board's own entry among one page of an issue's `Issue.projectItems`.
7143    ///
7144    /// One spelling of *which membership is this board's*, so the page a read carries and
7145    /// the pages [`Self::board_membership`] walks are searched by the same rule.
7146    fn board_entry<'a>(&self, nodes: &'a [Value]) -> Option<&'a Value> {
7147        nodes.iter().find(|node| {
7148            node.pointer("/project/number").and_then(Value::as_u64)
7149                == Some(u64::from(self.project_number))
7150        })
7151    }
7152
7153    /// The rest of one issue's board memberships, from `after`, for this board's entry.
7154    ///
7155    /// The recovery read: a page of memberships that holds no entry for this board says
7156    /// nothing about the memberships past it, so the connection is walked to exhaustion
7157    /// before an issue is reported as one this board does not hold. `Ok(None)` is that
7158    /// positive answer — the whole connection was read and no entry named this board —
7159    /// rather than a failure, and the walk is held to
7160    /// [`validate_cursor_progress`] like every other page walk here, so a source answering
7161    /// with a cursor that does not advance is refused instead of spun on.
7162    async fn board_membership(
7163        &self,
7164        issue: &str,
7165        after: &str,
7166    ) -> Result<Option<Value>, SourceError> {
7167        let mut after = after.to_owned();
7168        loop {
7169            let data = self
7170                .graphql(
7171                    graphql::ISSUE_BOARD_ITEMS,
7172                    json!({"id":issue,"first":MAX_PAGE_SIZE,"after":after,
7173                           "nestedFirst":NESTED_PAGE_SIZE}),
7174                )
7175                .await?;
7176            let Some(connection) = data
7177                .pointer("/node/projectItems")
7178                .filter(|value| !value.is_null())
7179            else {
7180                // The id resolved to nothing, or to something with no memberships to walk —
7181                // which is the same answer as a connection holding no entry for this board.
7182                return Ok(None);
7183            };
7184            let nodes = connection
7185                .get("nodes")
7186                .and_then(Value::as_array)
7187                .ok_or_else(|| SourceError::Malformed {
7188                    message: "GitHub issue projectItems.nodes is not an array".into(),
7189                })?;
7190            if let Some(held) = self.board_entry(nodes) {
7191                return Ok(Some(held.clone()));
7192            }
7193            let info = connection
7194                .get("pageInfo")
7195                .ok_or_else(|| SourceError::Malformed {
7196                    message: "GitHub issue projectItems has no pageInfo".into(),
7197                })?;
7198            let next = required_bool(info, "hasNextPage")?
7199                .then(|| required_str(info, "endCursor"))
7200                .transpose()?;
7201            match next {
7202                Some(next) => {
7203                    validate_cursor_progress(Some(&after), next)?;
7204                    after = next.to_owned();
7205                }
7206                None => return Ok(None),
7207            }
7208        }
7209    }
7210
7211    /// One page of a board-scoped issue search, and where the next page resumes.
7212    async fn search_page(
7213        &self,
7214        search: &str,
7215        first: u32,
7216        after: Option<&str>,
7217    ) -> Result<(Vec<Resolved>, Option<String>), SourceError> {
7218        let (rows, next) = self.search_rows_page(search, first, after).await?;
7219        Ok((rows.into_iter().flatten().collect(), next))
7220    }
7221
7222    /// [`Self::search_page`], row for row: `None` for a row that is no item of this board, so a
7223    /// row's position in the answer is its position in GitHub's — what a cursor's offset counts.
7224    async fn search_rows_page(
7225        &self,
7226        search: &str,
7227        first: u32,
7228        after: Option<&str>,
7229    ) -> Result<(Vec<Option<Resolved>>, Option<String>), SourceError> {
7230        let data = self
7231            .graphql(
7232                graphql::SEARCH_ISSUES,
7233                json!({"search":search,"type":"ISSUE","first":first.min(MAX_PAGE_SIZE),
7234                       "after":after,"nestedFirst":NESTED_PAGE_SIZE,
7235                       "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
7236            )
7237            .await?;
7238        let connection = data.get("search").ok_or_else(|| SourceError::Malformed {
7239            message: "GitHub search response has no search connection".into(),
7240        })?;
7241        let mut found = Vec::new();
7242        for node in connection
7243            .get("nodes")
7244            .and_then(Value::as_array)
7245            .ok_or_else(|| SourceError::Malformed {
7246                message: "GitHub search nodes is not an array".into(),
7247            })?
7248        {
7249            found.push(self.resolve_issue(node).await?);
7250        }
7251        let info = connection
7252            .get("pageInfo")
7253            .ok_or_else(|| SourceError::Malformed {
7254                message: "GitHub search connection has no pageInfo".into(),
7255            })?;
7256        let next = required_bool(info, "hasNextPage")?
7257            .then(|| required_str(info, "endCursor"))
7258            .transpose()?
7259            .map(str::to_owned);
7260        if let Some(next) = &next {
7261            validate_cursor_progress(after, next)?;
7262        }
7263        Ok((found, next))
7264    }
7265
7266    /// Every issue this board holds, completed with what this run wrote.
7267    ///
7268    /// The completion is not an optimisation and it is not a cache: GitHub's issue search
7269    /// is an index and is eventually consistent, so an issue this run created seconds ago
7270    /// can be absent from it, and a project listed straight after being written would
7271    /// otherwise be missing from its own board. What is added back is only what this
7272    /// process itself wrote, out of [`Self::created`], which lives and dies with the
7273    /// process.
7274    async fn board_issues(&self) -> Result<Vec<Resolved>, SourceError> {
7275        let found = self.searched_issues().await?;
7276        self.completed_with_written(found, |_| true)
7277    }
7278
7279    /// Every issue this board's own search reports, walked to exhaustion, read once per
7280    /// source.
7281    ///
7282    /// The uncompleted half of [`Self::board_issues`], separated because [`Self::board`]
7283    /// needs it too and the two would otherwise walk the same search twice in one command.
7284    /// See [`Self::search_cache`] for why holding it is the same bargain holding the board
7285    /// is.
7286    async fn searched_issues(&self) -> Result<Vec<Resolved>, SourceError> {
7287        let cached = self.search_cache()?.clone();
7288        if let Some(held) = cached {
7289            return Ok(held);
7290        }
7291        let mut after: Option<String> = None;
7292        let mut found = Vec::new();
7293        let search = self.board_search(None);
7294        loop {
7295            let (page, next) = self
7296                .search_page(&search, MAX_PAGE_SIZE, after.as_deref())
7297                .await?;
7298            found.extend(page);
7299            match next {
7300                Some(next) => after = Some(next),
7301                None => break,
7302            }
7303        }
7304        *self.search_cache()? = Some(found.clone());
7305        Ok(found)
7306    }
7307
7308    /// Every issue this board's own search reports with `also` beside its scope, walked to
7309    /// exhaustion — held for no later read, which may not be narrowed alike.
7310    async fn searched_narrowly(&self, also: &str) -> Result<Vec<Resolved>, SourceError> {
7311        let mut after: Option<String> = None;
7312        let mut found = Vec::new();
7313        let search = self.board_search(Some(also));
7314        loop {
7315            let (page, next) = self
7316                .search_page(&search, MAX_PAGE_SIZE, after.as_deref())
7317                .await?;
7318            found.extend(page);
7319            match next {
7320                Some(next) => after = Some(next),
7321                None => return Ok(found),
7322            }
7323        }
7324    }
7325
7326    /// This process's own view of the board's issues, or the refusal a poisoned lock is.
7327    fn search_cache(
7328        &self,
7329    ) -> Result<std::sync::MutexGuard<'_, Option<Vec<Resolved>>>, SourceError> {
7330        self.search_cache
7331            .lock()
7332            .map_err(|_| SourceError::Unavailable {
7333                message: "this source's view of the board's issues was left inconsistent by an \
7334                      earlier failure; next: run the command again"
7335                    .into(),
7336            })
7337    }
7338
7339    /// `found`, with everything this run wrote that `keep` accepts and the read did not
7340    /// report.
7341    ///
7342    /// See [`Self::created`] and [`Self::board_issues`] for why a read has to be completed
7343    /// at all: the search index is behind, and a node read of an item filed moments ago can
7344    /// be too.
7345    fn completed_with_written(
7346        &self,
7347        mut found: Vec<Resolved>,
7348        keep: impl Fn(&Resolved) -> bool,
7349    ) -> Result<Vec<Resolved>, SourceError> {
7350        for own in self.created()?.iter().filter(|own| keep(own)) {
7351            if !found.iter().any(|item| item.id == own.id) {
7352                found.push(own.clone());
7353            }
7354        }
7355        Ok(found)
7356    }
7357
7358    /// What resolving one node id reached.
7359    ///
7360    /// Three answers rather than an `Option`, because a board *draft* is none of the other
7361    /// two: it is not an issue, so the issue fragment reads nothing of it, and a read of one
7362    /// is completed by a read of the draft itself rather than reported as nothing.
7363    async fn reach(&self, id: &NativeId) -> Result<Reached, SourceError> {
7364        let asked = self
7365            .graphql(
7366                graphql::ISSUE,
7367                json!({"id":id.0,"first":MAX_PAGE_SIZE,"nestedFirst":NESTED_PAGE_SIZE,
7368                       "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
7369            )
7370            .await;
7371        let data = match asked {
7372            Ok(data) => data,
7373            // A string that is not a node id at all is not a failure to report: it is an id
7374            // this board does not hold, which is what every read of one already answers.
7375            Err(error) if unresolvable_node(&error) => return Ok(Reached::Nothing),
7376            Err(error) => return Err(error),
7377        };
7378        let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
7379            return Ok(Reached::Nothing);
7380        };
7381        if optional_str(node, "__typename")? == Some("DraftIssue") {
7382            return Ok(Reached::Draft);
7383        }
7384        Ok(match self.resolve_issue(node).await? {
7385            Some(item) => Reached::Held(Box::new(item)),
7386            None => Reached::Nothing,
7387        })
7388    }
7389
7390    /// One item of this board by its own id, whatever kind it is.
7391    ///
7392    /// Resolved from the identifier alone: no search, board-wide or otherwise. What this
7393    /// run wrote is read first, because a node read of an item created moments ago can
7394    /// still be behind the board field values written onto it — see [`Self::created`].
7395    async fn item_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7396        if let Some(own) = self.created()?.iter().find(|own| own.id == *id) {
7397            return Ok(Some(own.clone()));
7398        }
7399        if let Some(held) = self.read_ahead()?.remove(id) {
7400            return Ok(held);
7401        }
7402        match self.reach(id).await? {
7403            Reached::Held(item) => Ok(Some(*item)),
7404            Reached::Nothing => Ok(None),
7405            Reached::Draft => self.draft_by_id(id).await,
7406        }
7407    }
7408
7409    /// [`Self::item_by_id`] for a document: one [`graphql::DOCUMENT_IN_PROJECT`] read, which
7410    /// answers the project it is filed under and that project's members beside it.
7411    ///
7412    /// Each is held for this command as a read of it would have been: the project for the
7413    /// next read of it by its id, and — when its page of members is the whole of them — the
7414    /// members for the next listing of that project. So a write held to who may read the
7415    /// document, which reads all three, is answered by this one request.
7416    async fn document_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7417        if self.created()?.iter().any(|own| own.id == *id) || self.read_ahead()?.contains_key(id) {
7418            return self.item_by_id(id).await;
7419        }
7420        let asked = self
7421            .graphql(
7422                graphql::DOCUMENT_IN_PROJECT,
7423                json!({"id":id.0,"first":MAX_PAGE_SIZE,"memberFirst":MEMBER_PAGE_SIZE,
7424                       "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
7425                       "duplicates":true}),
7426            )
7427            .await;
7428        let data = match asked {
7429            Ok(data) => data,
7430            Err(error) if unresolvable_node(&error) => return Ok(None),
7431            Err(error) => return Err(error),
7432        };
7433        let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
7434            return Ok(None);
7435        };
7436        if optional_str(node, "__typename")? == Some("DraftIssue") {
7437            return self.draft_by_id(id).await;
7438        }
7439        let Some(item) = self.resolve_issue(node).await? else {
7440            return Ok(None);
7441        };
7442        // An answer for another issue than the one asked about says nothing of that one.
7443        if item.id != *id {
7444            return Err(SourceError::Malformed {
7445                message: format!(
7446                    "GitHub answered issue {} when asked for document {}",
7447                    item.id.0, id.0
7448                ),
7449            });
7450        }
7451        if let Some(project) = node.get("project").filter(|value| !value.is_null())
7452            && let Some(parent) = self
7453                .resolve_issue(project)
7454                .await?
7455                .filter(|parent| Some(&parent.id) == item.parent.as_ref())
7456        {
7457            let members = project.get("subIssues").filter(|value| !value.is_null());
7458            let whole = members
7459                .and_then(|members| members.pointer("/pageInfo/hasNextPage"))
7460                .and_then(Value::as_bool)
7461                == Some(false);
7462            if whole {
7463                let nodes = members
7464                    .and_then(|members| members.get("nodes"))
7465                    .and_then(Value::as_array)
7466                    .ok_or_else(|| SourceError::Malformed {
7467                        message: "GitHub subIssues.nodes is not an array".into(),
7468                    })?;
7469                let mut children = Vec::new();
7470                for member in nodes {
7471                    if let Some(resolved) = self.resolve_issue(member).await? {
7472                        children.push(resolved);
7473                    }
7474                }
7475                // Held as the project's members only when every one resolved and says it is
7476                // filed under it: a page with any other answers nothing of all the members.
7477                if children.len() == nodes.len()
7478                    && children
7479                        .iter()
7480                        .all(|child| child.parent.as_ref() == Some(&parent.id))
7481                {
7482                    self.children_cache()?
7483                        .insert(parent.id.clone(), (parent.id.clone(), children));
7484                }
7485            }
7486            self.read_ahead()?.insert(parent.id.clone(), Some(parent));
7487        }
7488        Ok(Some(item))
7489    }
7490
7491    /// Several items of this board, each by its own id, in order — what [`Self::item_by_id`]
7492    /// answers for each, read [`DETAIL_BATCH`] at a time with [`graphql::ISSUE_DETAILS`] rather
7493    /// than one request per id.
7494    ///
7495    /// What this run wrote answers first, as it does there, and only the rest is read. One id
7496    /// left to read is read by [`Self::item_by_id`] itself, which costs what a batch does. A
7497    /// batch GitHub refuses because one of its ids resolves to no node at all is read again one
7498    /// id at a time, so that id is answered as not held and the others as themselves; a draft
7499    /// is completed by a read of the draft, exactly as there.
7500    async fn items_by_ids(&self, ids: &[NativeId]) -> Result<Vec<Option<Resolved>>, SourceError> {
7501        let mut found: Vec<Option<Option<Resolved>>> = {
7502            let created = self.created()?;
7503            ids.iter()
7504                .map(|id| {
7505                    created
7506                        .iter()
7507                        .find(|own| own.id == *id)
7508                        .map(|own| Some(own.clone()))
7509                })
7510                .collect()
7511        };
7512        let unread: Vec<NativeId> = ids
7513            .iter()
7514            .zip(&found)
7515            .filter(|(_, found)| found.is_none())
7516            .map(|(id, _)| id.clone())
7517            .collect();
7518        let mut read = Vec::with_capacity(unread.len());
7519        if let [one] = unread.as_slice() {
7520            read.push(self.item_by_id(one).await?);
7521        } else {
7522            for batch in unread.chunks(DETAIL_BATCH) {
7523                let data = match self
7524                    .graphql(graphql::ISSUE_DETAILS, detail_batch(batch, None))
7525                    .await
7526                {
7527                    Ok(data) => data,
7528                    Err(error) if unresolvable_node(&error) => {
7529                        for id in batch {
7530                            read.push(self.item_by_id(id).await?);
7531                        }
7532                        continue;
7533                    }
7534                    Err(error) => return Err(error),
7535                };
7536                for (slot, id) in batch.iter().enumerate() {
7537                    let node =
7538                        data.get(format!("i{slot}"))
7539                            .ok_or_else(|| SourceError::Malformed {
7540                                message: format!(
7541                                    "GitHub answered a batch read with no item for {}",
7542                                    id.0
7543                                ),
7544                            })?;
7545                    read.push(if node.is_null() {
7546                        None
7547                    } else if optional_str(node, "__typename")? == Some("DraftIssue") {
7548                        self.draft_by_id(id).await?
7549                    } else {
7550                        if optional_str(node, "__typename")? == Some("Issue")
7551                            && required_str(node, "id")? != id.0
7552                        {
7553                            return Err(SourceError::Malformed {
7554                                message: format!(
7555                                    "GitHub answered the read of {} with issue {}",
7556                                    id.0,
7557                                    required_str(node, "id")?
7558                                ),
7559                            });
7560                        }
7561                        self.resolve_issue(node).await?
7562                    });
7563                }
7564            }
7565        }
7566        let mut read = read.into_iter();
7567        Ok(found
7568            .iter_mut()
7569            .map(|slot| slot.take().unwrap_or_else(|| read.next().flatten()))
7570            .collect())
7571    }
7572
7573    fn read_ahead(
7574        &self,
7575    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Option<Resolved>>>, SourceError> {
7576        self.read_ahead
7577            .lock()
7578            .map_err(|_| SourceError::Unavailable {
7579                message:
7580                    "items read ahead for a copy were left inconsistent; run the command again"
7581                        .into(),
7582            })
7583    }
7584
7585    fn resolved_cache(
7586        &self,
7587    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Resolved>>, SourceError> {
7588        self.resolved_cache
7589            .lock()
7590            .map_err(|_| SourceError::Unavailable {
7591                message: "resolved item records were left inconsistent; run the command again"
7592                    .into(),
7593            })
7594    }
7595
7596    /// Reuse a record this invocation already resolved. The mutation sender invalidates
7597    /// it before writing, so a partial failure cannot leave a pre-write binding behind.
7598    async fn bound_item(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7599        let cached = self.resolved_cache()?.get(id).cloned();
7600        if let Some(item) = cached {
7601            return Ok(Some(item));
7602        }
7603        self.item_by_id(id).await
7604    }
7605
7606    /// Take out the item an issue read by reference reached for `id`, when one is held: the
7607    /// status write it was read for is the one caller, so no other read or write is ever
7608    /// answered from a read that selected only what that write needs.
7609    fn take_held(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7610        Ok(self
7611            .held_cache
7612            .lock()
7613            .map_err(|_| SourceError::Unavailable {
7614                message: "items read by issue reference were left inconsistent; run the \
7615                          command again"
7616                    .into(),
7617            })?
7618            .remove(id))
7619    }
7620
7621    /// One board draft by its own id, with the board item it sits in — or `None` when no
7622    /// item of this board is that draft's.
7623    ///
7624    /// The same decision [`Self::resolve_issue`] makes for an issue, over the draft's own
7625    /// `projectV2Items`: an entry naming this board is what makes it this board's. GitHub
7626    /// links a draft to one board item, so the page this read carries is the whole of that
7627    /// connection, and a page that reports more than it holds is refused rather than read
7628    /// as an answer about memberships nobody read.
7629    async fn draft_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7630        let data = self
7631            .graphql(
7632                graphql::DRAFT,
7633                json!({"id":id.0,"nestedFirst":NESTED_PAGE_SIZE,
7634                       "boardItems":BOARD_ITEMS_PAGE_SIZE}),
7635            )
7636            .await?;
7637        // Gone between the two reads is an answer — the draft is no longer there. Anything
7638        // else than the draft [`Self::reach`] was just told this id is, is not one.
7639        let Some(draft) = data.get("node").filter(|node| !node.is_null()) else {
7640            return Ok(None);
7641        };
7642        if optional_str(draft, "__typename")? != Some("DraftIssue") {
7643            return Err(SourceError::Malformed {
7644                message: format!(
7645                    "GitHub answered {} as a draft and then as something else",
7646                    id.0
7647                ),
7648            });
7649        }
7650        if required_str(draft, "id")? != id.0 {
7651            return Err(SourceError::Malformed {
7652                message: format!("GitHub answered a different draft for {}", id.0),
7653            });
7654        }
7655        let memberships = draft
7656            .get("projectV2Items")
7657            .ok_or_else(|| SourceError::Malformed {
7658                message: format!("GitHub draft {} is missing projectV2Items", id.0),
7659            })?;
7660        let nodes = memberships
7661            .get("nodes")
7662            .and_then(Value::as_array)
7663            .ok_or_else(|| SourceError::Malformed {
7664                message: format!("GitHub draft {} projectV2Items.nodes is not an array", id.0),
7665            })?;
7666        let info = memberships
7667            .get("pageInfo")
7668            .ok_or_else(|| SourceError::Malformed {
7669                message: format!("GitHub draft {} projectV2Items has no pageInfo", id.0),
7670            })?;
7671        // Read whether or not this board's entry is on the page: a page claiming more than
7672        // the one item GitHub links a draft to is a malformed answer either way.
7673        if required_bool(info, "hasNextPage")? || nodes.len() > 1 {
7674            return Err(SourceError::Malformed {
7675                message: format!(
7676                    "GitHub draft {} reports more board items than the one GitHub links a draft \
7677                     to",
7678                    id.0
7679                ),
7680            });
7681        }
7682        if let Some(node) = nodes.first()
7683            && node
7684                .pointer("/project/number")
7685                .and_then(Value::as_u64)
7686                .is_none()
7687        {
7688            return Err(SourceError::Malformed {
7689                message: format!(
7690                    "GitHub draft {} board item has no numeric project number",
7691                    id.0
7692                ),
7693            });
7694        }
7695        let Some(held) = self.board_entry(nodes) else {
7696            return Ok(None);
7697        };
7698        if required_str(
7699            held.get("project").ok_or_else(|| SourceError::Malformed {
7700                message: format!("GitHub draft {} board item has no project", id.0),
7701            })?,
7702            "id",
7703        )? != self.board_fields().await?.id.as_str()
7704        {
7705            return Ok(None);
7706        }
7707        let item = json!({
7708            "id": required_str(held, "id")?,
7709            "project": held.get("project"),
7710            "fieldValues": held.get("fieldValues"),
7711            "content": draft,
7712        });
7713        self.resolve(&item)
7714    }
7715
7716    /// The board's own id and field definitions, for a write whose item does not carry
7717    /// them — never its items.
7718    ///
7719    /// A board this command has already listed supplies them, since it read them beside its
7720    /// items; otherwise they come from [`graphql::BOARD_FIELDS`], once per command. Neither
7721    /// is consulted about which items the board holds: see the module documentation for
7722    /// why a question about one known item is answered by reading that item.
7723    async fn board_fields(&self) -> Result<BoardFields, SourceError> {
7724        if let Some(board) = self.board_cache()?.as_ref() {
7725            return Ok(BoardFields {
7726                id: BoardId::parse(&board.id)?,
7727                fields: board.fields.clone(),
7728            });
7729        }
7730        if let Some(held) = self.fields_cache()?.clone() {
7731            return Ok(held);
7732        }
7733        let data = self
7734            .graphql(
7735                graphql::BOARD_FIELDS,
7736                json!({"owner":self.owner,"number":self.project_number,
7737                       "nestedFirst":NESTED_PAGE_SIZE}),
7738            )
7739            .await?;
7740        self.fields_read(&data)
7741    }
7742
7743    /// The board's id and fields out of an answer carrying the `boardFields` root, held for
7744    /// the rest of this command.
7745    fn fields_read(&self, data: &Value) -> Result<BoardFields, SourceError> {
7746        let board = data
7747            .pointer("/boardFields/projectV2")
7748            .filter(|value| !value.is_null())
7749            .ok_or_else(|| SourceError::Refused {
7750                message: format!(
7751                    "GitHub project {}/{} was not found or is not visible to the token",
7752                    self.owner, self.project_number
7753                ),
7754            })?;
7755        let read = BoardFields {
7756            id: BoardId::parse(required_str(board, "id")?)?,
7757            fields: board.get("fields").cloned().unwrap_or(Value::Null),
7758        };
7759        *self.fields_cache()? = Some(read.clone());
7760        Ok(read)
7761    }
7762
7763    /// Read what creating an issue in `repository` needs and this command has not read yet —
7764    /// the board's fields and the repository's node id — in one request when it needs both.
7765    ///
7766    /// When either is already known this sends nothing, and the other is read by its own
7767    /// document where it is asked for, so no create reads anything twice.
7768    async fn creation_context(
7769        &self,
7770        repository: &RepositoryTarget,
7771        incoming: &Incoming<'_>,
7772    ) -> Result<(), SourceError> {
7773        let fields_known = self.board_cache()?.is_some() || self.fields_cache()?.is_some();
7774        if fields_known || self.repository_cache()?.contains_key(repository) {
7775            return Ok(());
7776        }
7777        // A placement an earlier process kept is taken only while the project issue this create
7778        // has just read shows its setup-context token unchanged; see `projection`.
7779        if self.placed_by_kept(repository, incoming.parent) {
7780            return Ok(());
7781        }
7782        let data = self
7783            .graphql(
7784                graphql::CREATION_CONTEXT,
7785                json!({"owner":self.owner,"number":self.project_number,
7786                       "nestedFirst":NESTED_PAGE_SIZE,"repositoryOwner":repository.owner,
7787                       "repositoryName":repository.name}),
7788            )
7789            .await?;
7790        self.fields_read(&data)?;
7791        self.repository_read(&data, repository, incoming)?;
7792        Ok(())
7793    }
7794
7795    /// This process's own view of the board's fields, or the refusal a poisoned lock is.
7796    fn fields_cache(&self) -> Result<std::sync::MutexGuard<'_, Option<BoardFields>>, SourceError> {
7797        self.fields_cache
7798            .lock()
7799            .map_err(|_| SourceError::Unavailable {
7800                message: "this source's view of the board's fields was left inconsistent by an \
7801                      earlier failure; next: run the command again"
7802                    .into(),
7803            })
7804    }
7805
7806    /// What a write to `item` needs of the board, read off that item when it says enough and
7807    /// off [`Self::board_fields`] when it does not.
7808    ///
7809    /// A node read of an item names its board and carries the definition of every field it
7810    /// holds a value of — so an item naming its board, holding a value of the origin field
7811    /// when the write carries an origin, and, when the write carries a status, holding a
7812    /// `Status` value, needs no read of the board at all. **Nothing the item does not say is
7813    /// guessed:** a field it holds no value of may still be on the board, and a view reading it
7814    /// as absent would refuse a write the board can take or skip a field write the board
7815    /// needs, so such an item — and a create, which has no item yet — takes the board's fields
7816    /// from their own read instead. A write carrying no origin to an item holding none — every
7817    /// write out of a source declared private — writes no origin whatever the board defines,
7818    /// so it needs no definition of that field.
7819    async fn fields_for(
7820        &self,
7821        item: Option<&Resolved>,
7822        writes_origin: bool,
7823        writes_status: bool,
7824        selects_priority: bool,
7825    ) -> Result<BoardFields, SourceError> {
7826        if let Some(board) = item.and_then(Resolved::carried_board) {
7827            return Ok(board);
7828        }
7829        if let Some(item) = item
7830            && let Some(board_id) = item.named_board()
7831            && (!writes_origin || item.defines(ORIGIN_FIELD))
7832            && (!writes_status || item.defines("Status"))
7833            && (!selects_priority || item.defines(PRIORITY_FIELD))
7834            && self
7835                .metadata_fields
7836                .iter()
7837                .all(|projection| item.defines(&projection.field))
7838        {
7839            return Ok(BoardFields {
7840                id: board_id,
7841                fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
7842            });
7843        }
7844        self.board_fields().await
7845    }
7846
7847    /// Everything filed under one issue of this board, walked to exhaustion — or `None`
7848    /// when that id names nothing here with a sub-issue relationship to walk.
7849    ///
7850    /// `None` and an empty answer are different: `None` is *this is not an issue of this
7851    /// GitHub*, which is what sends a project selector on to be read as a name, and an
7852    /// empty vector is a project that holds nothing.
7853    async fn sub_issues(&self, id: &NativeId) -> Result<Option<Vec<Resolved>>, SourceError> {
7854        let mut after: Option<String> = None;
7855        let mut children = Vec::new();
7856        // The project issue as the first page carried it, held once the walk has ended.
7857        let mut parent: Option<Resolved> = None;
7858        loop {
7859            let asked = self
7860                .graphql(
7861                    graphql::SUB_ISSUES,
7862                    json!({"id":id.0,"memberFirst":MEMBER_PAGE_SIZE,"after":after,
7863                           "nestedFirst":NESTED_PAGE_SIZE,
7864                           "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
7865                )
7866                .await;
7867            let data = match asked {
7868                Ok(data) => data,
7869                // A string that is not a node id at all is not a failure to report: it is
7870                // the ordinary answer to a selector naming a project by its name.
7871                Err(error) if unresolvable_node(&error) => return Ok(None),
7872                Err(error) => return Err(error),
7873            };
7874            let Some(connection) = data
7875                .pointer("/node/subIssues")
7876                .filter(|value| !value.is_null())
7877            else {
7878                // No such node, or one with no sub-issue relationship — a board draft is
7879                // the one this board can really hold.
7880                return Ok(None);
7881            };
7882            if after.is_none()
7883                && let Some(node) = data.get("node").filter(|node| node.get("id").is_some())
7884            {
7885                parent = self
7886                    .resolve_issue(node)
7887                    .await?
7888                    .filter(|resolved| resolved.id == *id);
7889            }
7890            for node in connection
7891                .get("nodes")
7892                .and_then(Value::as_array)
7893                .ok_or_else(|| SourceError::Malformed {
7894                    message: "GitHub subIssues.nodes is not an array".into(),
7895                })?
7896            {
7897                if let Some(resolved) = self.resolve_issue(node).await? {
7898                    children.push(resolved);
7899                }
7900            }
7901            let info = connection
7902                .get("pageInfo")
7903                .ok_or_else(|| SourceError::Malformed {
7904                    message: "GitHub subIssues connection has no pageInfo".into(),
7905                })?;
7906            let next = required_bool(info, "hasNextPage")?
7907                .then(|| required_str(info, "endCursor"))
7908                .transpose()?;
7909            match next {
7910                Some(next) => {
7911                    validate_cursor_progress(after.as_deref(), next)?;
7912                    after = Some(next.to_owned());
7913                }
7914                None => {
7915                    // Held only once the walk has ended, so one failing part way holds
7916                    // nothing and every read it would have answered is made.
7917                    // The project issue the first page carried answers the next read of the
7918                    // project by its id in this command, as a read of it made now would: what
7919                    // classifying a project for a write reads straight after its members.
7920                    if let Some(parent) = &parent {
7921                        self.read_ahead()?
7922                            .entry(parent.id.clone())
7923                            .or_insert_with(|| Some(parent.clone()));
7924                    }
7925                    let mut carried = self.carried()?;
7926                    for item in parent.into_iter().chain(children.iter().cloned()) {
7927                        carried.insert(item.id.clone(), item);
7928                    }
7929                    return Ok(Some(children));
7930                }
7931            }
7932        }
7933    }
7934
7935    fn carried(
7936        &self,
7937    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Resolved>>, SourceError> {
7938        self.carried.lock().map_err(|_| SourceError::Unavailable {
7939            message: "items a project's listing carried were left inconsistent; run the \
7940                      command again"
7941                .into(),
7942        })
7943    }
7944
7945    /// Which issue of this board a project *name* is, or `None` when none is.
7946    ///
7947    /// One bounded query which filters on that name at the server, rather than a walk of
7948    /// every issue the board holds. The name is compared again here: the qualifier narrows
7949    /// what GitHub sends, and this source decides what it names.
7950    async fn project_by_name(&self, name: &str) -> Result<Option<NativeId>, SourceError> {
7951        let search = self.board_search(Some(&title_qualifier(name)));
7952        let mut after = None;
7953        loop {
7954            let (candidates, next) = self
7955                .search_page(&search, SEARCH_PAGE_SIZE, after.as_deref())
7956                .await?;
7957            if let Some(item) = candidates.into_iter().find(|item| {
7958                item.kind == BoardKind::Work(ItemKind::Project)
7959                    && item.title.eq_ignore_ascii_case(name)
7960            }) {
7961                return Ok(Some(item.id));
7962            }
7963            match next {
7964                Some(next) => after = Some(next),
7965                None => return Ok(None),
7966            }
7967        }
7968    }
7969
7970    /// Everything filed under one project of this board: the sub-issues of the issue that
7971    /// project is.
7972    ///
7973    /// Tasks *and* documents, because a document filed under a project is a sub-issue of it
7974    /// too — the caller keeps the kind it asked for. Nothing about this grows as the board
7975    /// gains projects, or as another project gains tasks.
7976    ///
7977    /// A qualified id names the issue and is asked for its sub-issues directly: one
7978    /// request, no search of any kind. Only a selector GitHub cannot resolve that way is
7979    /// read as a project *name*, which costs the one bounded search
7980    /// [`Self::project_by_name`] makes.
7981    ///
7982    /// What GitHub answered is held for the rest of the command — see [`Self::children_cache`]
7983    /// — and each answer is still cut to the items whose parent is this project, so one this
7984    /// process has since filed elsewhere is not reported here, and completed with what this
7985    /// process filed under it.
7986    async fn project_children(&self, selector: &NativeId) -> Result<Vec<Resolved>, SourceError> {
7987        let held = self.children_cache()?.get(selector).cloned();
7988        let (project, children) = match held {
7989            Some(held) => held,
7990            None => {
7991                let answered = match self.sub_issues(selector).await? {
7992                    Some(children) => (selector.clone(), children),
7993                    None => match self.project_by_name(&selector.0).await? {
7994                        Some(project) => {
7995                            let children = self.sub_issues(&project).await?.unwrap_or_default();
7996                            (project, children)
7997                        }
7998                        None => return Ok(Vec::new()),
7999                    },
8000                };
8001                self.children_cache()?
8002                    .insert(selector.clone(), answered.clone());
8003                answered
8004            }
8005        };
8006        let mut children: Vec<Resolved> = children
8007            .into_iter()
8008            .filter(|child| child.parent.as_ref() == Some(&project))
8009            .collect();
8010        for own in self.updated()?.iter() {
8011            if own.parent.as_ref() == Some(&project) && !children.iter().any(|c| c.id == own.id) {
8012                children.push(own.clone());
8013            }
8014        }
8015        self.completed_with_written(children, |own| own.parent.as_ref() == Some(&project))
8016    }
8017
8018    /// Every issue of this board GitHub's issue search reports updated at or after `since`,
8019    /// completed with what this run wrote — the candidates a comment-activity read confirms.
8020    ///
8021    /// Scoped by the board and by nothing else: `project:<owner>/<number>` reaches every issue
8022    /// on the board whatever repository, and whatever owner, it lives in, so no repository or
8023    /// owner qualifier is added and none is needed. What makes the `updated:` qualifier
8024    /// sufficient is a fact about GitHub rather than about this source: a comment written on an
8025    /// issue **and a comment edited on it** both move that issue's `updatedAt`. The credentialed
8026    /// journey `an_edited_comment_moves_its_issue_and_is_selected_since` in `tests/journey`
8027    /// re-takes that fact on every run of the lane, so a change on GitHub's side fails there
8028    /// rather than silently narrowing a caller's answer.
8029    ///
8030    /// The instant is written to the second, rounded down, which can only widen what the
8031    /// search returns; confirmation against each candidate's own comments is what makes the
8032    /// answer exact. The search is an index that lags a write by a second or two — the module
8033    /// documentation records it — so a caller that asks again from its last instant should
8034    /// overlap the two by more than that.
8035    async fn updated_since(&self, since: DateTime<Utc>) -> Result<Vec<Resolved>, SourceError> {
8036        let found = self.searched(&updated_qualifier(since)).await?;
8037        self.completed_with_written(found, |_| true)
8038    }
8039
8040    /// Every issue of this board GitHub's issue search reports for the board-scoped search
8041    /// narrowed by `also`, in pages of [`SEARCH_PAGE_SIZE`].
8042    ///
8043    /// Uncompleted: what this process wrote is added by the caller, which knows whether its
8044    /// own record is the fresher of the two.
8045    async fn searched(&self, also: &str) -> Result<Vec<Resolved>, SourceError> {
8046        let search = self.board_search(Some(also));
8047        let mut after: Option<String> = None;
8048        let mut found = Vec::new();
8049        loop {
8050            let (page, next) = self
8051                .search_page(&search, SEARCH_PAGE_SIZE, after.as_deref())
8052                .await?;
8053            found.extend(page);
8054            match next {
8055                Some(next) => after = Some(next),
8056                None => return Ok(found),
8057            }
8058        }
8059    }
8060
8061    /// A bounded task answer; the versioned cursor carries the connection position, how
8062    /// many rows of the page starting there were already handed out, and the own-write ids
8063    /// already observed, including across a new source instance.
8064    ///
8065    /// Every page is sent at [`SEARCH_PAGE_SIZE`] whatever the caller's limit, and a limit is
8066    /// sliced from the pages it needs; why is the module documentation's paging contract.
8067    async fn search_tasks(
8068        &self,
8069        query: &TaskQuery,
8070        page: &PageRequest,
8071        also: &str,
8072    ) -> Result<Page<Task>, SourceError> {
8073        let mut position = match &page.cursor {
8074            None => SearchPosition::default(),
8075            Some(cursor) => serde_json::from_str::<SearchPosition>(&cursor.0)
8076                .ok()
8077                .filter(|position| {
8078                    position.version == SEARCH_CURSOR_VERSION
8079                        && position.connection.valid_resume(position.offset)
8080                })
8081                .ok_or_else(|| SourceError::Config {
8082                    message: "page cursor is invalid".into(),
8083                })?,
8084        };
8085        let search = self.board_search(Some(also));
8086        let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
8087        let own = self.with_own_writes(Vec::new())?;
8088        // An issue this process commented on is a candidate of a comment-activity read
8089        // whether or not the search has caught up with the comment; see `Self::commented`.
8090        let commented = match query.commented_since {
8091            Some(_) => self.commented()?.clone(),
8092            None => Vec::new(),
8093        };
8094        for id in own.iter().map(|item| &item.id).chain(&commented) {
8095            if !position.own.contains(id) {
8096                position.own.push(id.clone());
8097            }
8098        }
8099        let mut tasks = Vec::new();
8100        while !position.connection.exhausted() && tasks.len() < limit {
8101            // A page this read resumes 20 rows or more into — a cursor a batched page shared with
8102            // a larger search handed out — is asked far enough to hold a page of rows past them.
8103            let first = if position.offset < SEARCH_PAGE_SIZE as usize {
8104                SEARCH_PAGE_SIZE
8105            } else {
8106                u32::try_from(position.offset)
8107                    .unwrap_or(MAX_PAGE_SIZE)
8108                    .saturating_add(SEARCH_PAGE_SIZE)
8109                    .min(MAX_PAGE_SIZE)
8110            };
8111            // Page size is part of the key: a short cached answer cannot answer a wider ask.
8112            let key =
8113                serde_json::to_string(&("page", &search, &position.connection.after(), first))
8114                    .expect("search page key is serializable");
8115            let cached = if query.commented_since.is_none() {
8116                self.search_rows()?.get(&key).cloned()
8117            } else {
8118                None
8119            };
8120            let (found, next) = match cached {
8121                Some(found) => {
8122                    let next = self
8123                        .search_next
8124                        .lock()
8125                        .map_err(|_| SourceError::Unavailable {
8126                            message:
8127                                "search pagination was left inconsistent; run the command again"
8128                                    .into(),
8129                        })?
8130                        .get(&key)
8131                        .cloned()
8132                        .flatten();
8133                    (found, next)
8134                }
8135                None => {
8136                    let (found, next) = self
8137                        .search_rows_page(&search, first, position.connection.after())
8138                        .await?;
8139                    if query.commented_since.is_none() {
8140                        self.search_next
8141                            .lock()
8142                            .map_err(|_| SourceError::Unavailable {
8143                                message:
8144                                    "search pagination was left inconsistent; run the command again"
8145                                        .into(),
8146                            })?
8147                            .insert(key.clone(), next.clone());
8148                        self.search_rows()?.insert(key, found.clone());
8149                    }
8150                    (found, next)
8151                }
8152            };
8153            let rows = found.len();
8154            // Every candidate of the page this read confirms by its comments is read together.
8155            let candidates = self.comment_candidates(
8156                found.iter().skip(position.offset).flatten(),
8157                query,
8158                &query.project,
8159            )?;
8160            self.hold_comment_pages(&candidates).await?;
8161            for row in found.into_iter().skip(position.offset) {
8162                if tasks.len() == limit {
8163                    break;
8164                }
8165                position.offset += 1;
8166                let Some(mut item) = row else {
8167                    continue;
8168                };
8169                if position.own.contains(&item.id) {
8170                    if position.seen.contains(&item.id) {
8171                        continue;
8172                    }
8173                    position.seen.push(item.id.clone());
8174                    // The search's own copy of an issue this process only commented on is as
8175                    // good as a node read of it, since its comments are read either way.
8176                    let only_commented = commented.contains(&item.id)
8177                        && !own.iter().any(|written| written.id == item.id);
8178                    if !only_commented {
8179                        let updated_at = item.updated_at;
8180                        let Some(written) = self.search_written(&own, &item.id).await? else {
8181                            continue;
8182                        };
8183                        item = written;
8184                        item.updated_at = item.updated_at.max(updated_at);
8185                        self.resolved_cache()?.insert(item.id.clone(), item.clone());
8186                    }
8187                }
8188                if item.kind == BoardKind::Work(ItemKind::Task) {
8189                    let task = item.task()?;
8190                    if task_matches(&task, query, &query.project)
8191                        && self.commented_since(&item, query.commented_since).await?
8192                    {
8193                        tasks.push(task);
8194                    }
8195                }
8196            }
8197            if position.offset < rows {
8198                continue;
8199            }
8200            position.offset = 0;
8201            position.connection = match next {
8202                Some(after) => SearchConnection::Continuing {
8203                    after: Cursor(after),
8204                },
8205                None => SearchConnection::Exhausted {},
8206            };
8207        }
8208        if position.connection.exhausted() {
8209            for id in position.own.clone() {
8210                if position.seen.contains(&id) {
8211                    continue;
8212                }
8213                if tasks.len() == limit {
8214                    break;
8215                }
8216                position.seen.push(id.clone());
8217                let Some(item) = self.search_written(&own, &id).await? else {
8218                    continue;
8219                };
8220                if item.kind == BoardKind::Work(ItemKind::Task) {
8221                    let task = item.task()?;
8222                    if task_matches(&task, query, &query.project)
8223                        && self.commented_since(&item, query.commented_since).await?
8224                    {
8225                        tasks.push(task);
8226                    }
8227                }
8228            }
8229        }
8230        let more = !position.connection.exhausted()
8231            || position.own.iter().any(|id| !position.seen.contains(id));
8232        Ok(Page {
8233            items: tasks,
8234            next: more.then(|| {
8235                Cursor(serde_json::to_string(&position).expect("search position is serializable"))
8236            }),
8237        })
8238    }
8239
8240    /// A resumed process has the ids but no write records; resolve only a record the
8241    /// current page needs, by its uncached node read rather than the lagging search index.
8242    async fn search_written(
8243        &self,
8244        own: &[Resolved],
8245        id: &NativeId,
8246    ) -> Result<Option<Resolved>, SourceError> {
8247        match own.iter().find(|item| item.id == *id) {
8248            Some(item) => Ok(Some(item.clone())),
8249            None => self.item_by_id(id).await,
8250        }
8251    }
8252
8253    /// The candidates for a task query carrying a text, metadata or origin predicate, read
8254    /// without enumerating the board — or `None` for a query carrying none of the three, which
8255    /// keeps the reads it always had.
8256    ///
8257    /// An origin is answered by [`Self::origin_candidates`], whatever else the query carries,
8258    /// because it names at most a handful of items. Text and metadata are answered by one
8259    /// board-scoped issue search carrying every term — see [`narrowing_qualifiers`] — narrowed
8260    /// further by `updated:>=` when the query also asks for comment activity, since both
8261    /// qualifiers must hold of an issue the answer keeps. Every candidate is confirmed in
8262    /// process afterwards by the same predicates [`task_matches`] applies to every read.
8263    ///
8264    /// Completed with what this process wrote, its own record winning over the index's copy
8265    /// of the same item: see [`Self::with_own_writes`].
8266    async fn narrowed(&self, query: &TaskQuery) -> Result<Option<Vec<Resolved>>, SourceError> {
8267        self.send_pending_origins(None).await?;
8268        let asked = match (&query.origin, narrowing_qualifiers(query)) {
8269            (Some(origin), _) => Narrowing::Origin(origin.clone()),
8270            (None, Some(qualifiers)) => Narrowing::Search(match query.commented_since {
8271                Some(since) => format!("{} {qualifiers}", updated_qualifier(since)),
8272                None => qualifiers,
8273            }),
8274            (None, None) => return Ok(None),
8275        };
8276        // A question about comment activity is asked afresh every time, as it always was: it
8277        // is the one a caller polls from one source while waiting for the index, and an
8278        // answer held from the first poll would be the answer to every later one.
8279        let key = query.commented_since.is_none().then(|| asked.key());
8280        let cached = match &key {
8281            Some(key) => self.narrowed_cache()?.get(key).cloned(),
8282            None => None,
8283        };
8284        let found = match cached {
8285            Some(found) => found,
8286            None => {
8287                let found = match &asked {
8288                    Narrowing::Origin(origin) => self.origin_candidates(origin).await?,
8289                    Narrowing::Search(also) => self.searched(also).await?,
8290                };
8291                if let Some(key) = key {
8292                    self.narrowed_cache()?.insert(key, found.clone());
8293                }
8294                found
8295            }
8296        };
8297        self.with_own_writes(found).map(Some)
8298    }
8299
8300    /// The candidates for a project or unscoped document query carrying a searchable text,
8301    /// read without enumerating the board — or `None` for a query with no text or a blank one,
8302    /// which keeps the read it always had.
8303    ///
8304    /// The text is sent as the very phrase a task query's text is — see [`text_qualifiers`] —
8305    /// in one board-scoped issue search walked to its end at [`SEARCH_PAGE_SIZE`], so what it
8306    /// costs is the issues that match and never the board. Its answer is held for the command
8307    /// under the same key [`Self::narrowed`] holds that search under, so a walk of the caller's
8308    /// pages asks GitHub once. Every candidate is confirmed afterwards by its kind and by the
8309    /// substring rule, exactly as an item of the wider read was, and is completed with what this
8310    /// process wrote: see [`Self::with_own_writes`].
8311    async fn text_searched(
8312        &self,
8313        text: Option<&TextQuery>,
8314    ) -> Result<Option<Vec<Resolved>>, SourceError> {
8315        let Some(also) = text_qualifiers(text) else {
8316            return Ok(None);
8317        };
8318        let key = Narrowing::Search(also.clone()).key();
8319        let cached = self.narrowed_cache()?.get(&key).cloned();
8320        let found = match cached {
8321            Some(found) => found,
8322            None => {
8323                let found = self.searched(&also).await?;
8324                self.narrowed_cache()?.insert(key, found.clone());
8325                found
8326            }
8327        };
8328        self.with_own_writes(found).map(Some)
8329    }
8330
8331    /// Every `kind` item of this board whose own origin is exactly `origin`: the candidates
8332    /// [`Self::narrowed`] reads for a task query carrying that origin — one
8333    /// [`graphql::ORIGIN_LOOKUP`] walk, held for the command under the same key, completed with
8334    /// what this process wrote — each confirmed against its own origin entry.
8335    ///
8336    /// What answers a project or document listing by origin, so finding every copy of one plan
8337    /// costs the items that carry its origin and never a page of the board.
8338    async fn copied_from(
8339        &self,
8340        origin: &str,
8341        kind: BoardKind,
8342    ) -> Result<Vec<Resolved>, SourceError> {
8343        let wanted = TaskQuery {
8344            origin: Some(origin.to_owned()),
8345            ..TaskQuery::default()
8346        };
8347        Ok(self
8348            .narrowed(&wanted)
8349            .await?
8350            .unwrap_or_default()
8351            .into_iter()
8352            .filter(|item| item.kind == kind && wanted.origin_matches(&item.metadata()))
8353            .collect())
8354    }
8355
8356    /// Every item of this board that may carry `origin` — a superset of those that do — found
8357    /// by [`graphql::ORIGIN_LOOKUP`] and never by enumerating the board.
8358    ///
8359    /// The union of the board's own field filter over the `onetaskgraph.origin` text field —
8360    /// which reads the field every carrier holds, whichever release wrote it — and the
8361    /// board-scoped issue search for the same id as a phrase in the body, where this source
8362    /// mirrors it. The caller adds the third read, this process's own writes. Candidates are
8363    /// returned unconfirmed; [`task_matches`] compares each one's own origin field with the
8364    /// query's, exactly.
8365    ///
8366    /// Both connections are walked to exhaustion, each from its own cursor. One that has
8367    /// already ended is sent its last cursor again, which answers an empty page, so the one
8368    /// document serves every page of either. What the two leave is stated in the module
8369    /// documentation: a carrier another process added within the last second or two, before
8370    /// either index has it.
8371    async fn origin_candidates(&self, origin: &str) -> Result<Vec<Resolved>, SourceError> {
8372        let filter = format!("{ORIGIN_FIELD}:{}", quoted(origin));
8373        let search = self.board_search(Some(&format!("in:body {}", quoted(&as_stored(origin)))));
8374        let mut items_after: Option<String> = None;
8375        let mut search_after: Option<String> = None;
8376        let mut found: Vec<Resolved> = Vec::new();
8377        let keep = |resolved: Resolved, found: &mut Vec<Resolved>| {
8378            if !found.iter().any(|held| held.id == resolved.id) {
8379                found.push(resolved);
8380            }
8381        };
8382        loop {
8383            let data = self
8384                .graphql(
8385                    graphql::ORIGIN_LOOKUP,
8386                    json!({"owner":self.owner,"number":self.project_number,"filter":filter,
8387                           "search":search,"type":"ISSUE","originFirst":ORIGIN_PAGE_SIZE,
8388                           "itemsAfter":items_after,"searchAfter":search_after,
8389                           "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
8390                           "duplicates":true}),
8391                )
8392                .await?;
8393            let items = data
8394                .pointer("/originItems/projectV2/items")
8395                .filter(|value| !value.is_null())
8396                .ok_or_else(|| SourceError::Refused {
8397                    message: format!(
8398                        "GitHub project {}/{} was not found or is not visible to the token",
8399                        self.owner, self.project_number
8400                    ),
8401                })?;
8402            for item in optional_nodes(Some(items), "project items")?
8403                .into_iter()
8404                .flatten()
8405            {
8406                // The board's own items list its drafts too, and a draft is not an issue: no
8407                // narrowed read answers with one, whatever its origin field holds.
8408                if let Some(resolved) = self.resolve(item)?
8409                    && resolved.content_kind == ContentKind::Issue
8410                {
8411                    keep(resolved, &mut found);
8412                }
8413            }
8414            let searched = data.get("search").ok_or_else(|| SourceError::Malformed {
8415                message: "GitHub search response has no search connection".into(),
8416            })?;
8417            for node in optional_nodes(Some(searched), "search")?
8418                .into_iter()
8419                .flatten()
8420            {
8421                if let Some(resolved) = self.resolve_issue(node).await? {
8422                    keep(resolved, &mut found);
8423                }
8424            }
8425            let items_next = resumed(items, items_after.as_deref())?;
8426            let search_next = resumed(searched, search_after.as_deref())?;
8427            if !items_next.has_more() && !search_next.has_more() {
8428                return Ok(found);
8429            }
8430            items_after = items_next.cursor();
8431            search_after = search_next.cursor();
8432        }
8433    }
8434
8435    /// `found`, with every item this process created or wrote in its place, and every one of
8436    /// them the read did not report added.
8437    ///
8438    /// This process's own record wins over the read's copy of the same item, because a read
8439    /// of an item written moments ago can still be behind what was written onto it — the
8440    /// origin field included, which is the one a narrowed read is confirmed against — and a
8441    /// read that still names an item under a predicate this process's write moved it out of
8442    /// must not return it. The one thing the read knows that the record cannot is when GitHub
8443    /// last saw the item change, which is what a comment-activity read rules a candidate out
8444    /// by, so the read's `updatedAt` is kept when the record has none of its own. See
8445    /// [`Self::created`] and [`Self::updated`](GitHubProjectsSource::updated).
8446    fn with_own_writes(&self, mut found: Vec<Resolved>) -> Result<Vec<Resolved>, SourceError> {
8447        // A board draft is not an issue, so no narrowed read returns one, and this process
8448        // having written one does not make it an answer either.
8449        let own: Vec<Resolved> = self
8450            .created()?
8451            .iter()
8452            .chain(self.updated()?.iter())
8453            .filter(|own| own.content_kind == ContentKind::Issue)
8454            .cloned()
8455            .collect();
8456        for mut own in own {
8457            self.resolved_cache()?.insert(own.id.clone(), own.clone());
8458            match found.iter_mut().find(|read| read.id == own.id) {
8459                Some(read) => {
8460                    own.updated_at = own.updated_at.max(read.updated_at);
8461                    *read = own;
8462                }
8463                None => found.push(own),
8464            }
8465        }
8466        Ok(found)
8467    }
8468
8469    /// Whether `item` has a comment created or last edited at or after `since` — always, when
8470    /// there is no instant to hold it to.
8471    ///
8472    /// The candidate's own `updatedAt` is read first, because a comment written or edited at
8473    /// or after the instant moved it there: an issue not updated since holds no such comment,
8474    /// and its comments are never asked for — unless this process commented on it in this
8475    /// command, when the `updatedAt` held may predate that comment; see [`Self::commented`]. Otherwise its comments are walked, oldest first,
8476    /// only as far as the first that matches. A board draft is not an issue and has no
8477    /// comments, so it never matches.
8478    async fn commented_since(
8479        &self,
8480        item: &Resolved,
8481        since: Option<DateTime<Utc>>,
8482    ) -> Result<bool, SourceError> {
8483        let Some(since) = since else {
8484            return Ok(true);
8485        };
8486        if item.content_kind == ContentKind::DraftIssue {
8487            return Ok(false);
8488        }
8489        // An `updatedAt` this process's own record or a lagging index holds can predate a
8490        // comment this process wrote since, so only an issue it did not comment on is ruled
8491        // out by one.
8492        if item.updated_at.is_some_and(|updated| updated < since)
8493            && !self.commented()?.contains(&item.id)
8494        {
8495            return Ok(false);
8496        }
8497        let query = TaskQuery {
8498            commented_since: Some(since),
8499            ..TaskQuery::default()
8500        };
8501        let mut after: Option<String> = None;
8502        // A first page read beside its fellow candidates answers as this read's own would.
8503        let held = self.held_comments()?.get(&item.id).cloned();
8504        if let Some(first) = held {
8505            if query.comments_match(&first.items) {
8506                return Ok(true);
8507            }
8508            match first.next {
8509                Some(next) => after = Some(next.0),
8510                None => return Ok(false),
8511            }
8512        }
8513        loop {
8514            let data = self
8515                .graphql(
8516                    graphql::ISSUE_COMMENTS,
8517                    json!({"id":item.id.0,"first":MAX_PAGE_SIZE,"after":after}),
8518                )
8519                .await?;
8520            let Some(connection) = data
8521                .get("node")
8522                .filter(|value| !value.is_null())
8523                .and_then(|node| node.get("comments"))
8524                .filter(|value| !value.is_null())
8525            else {
8526                // Removed since the search reported it: no longer an issue with comments.
8527                return Ok(false);
8528            };
8529            let comments = optional_nodes(Some(connection), "issue comments")?
8530                .into_iter()
8531                .flatten()
8532                .map(comment_from)
8533                .collect::<Result<Vec<_>, _>>()?;
8534            if query.comments_match(&comments) {
8535                return Ok(true);
8536            }
8537            match next_cursor(connection)? {
8538                Some(next) => {
8539                    validate_cursor_progress(after.as_deref(), &next.0)?;
8540                    after = Some(next.0);
8541                }
8542                None => return Ok(false),
8543            }
8544        }
8545    }
8546
8547    /// Every item on the board: the union of both enumerations GitHub offers of one.
8548    ///
8549    /// Neither contains the other, so neither is dropped — only `ProjectV2.items` lists a
8550    /// board **draft** and reads the board's own fields beside its items, and only the search
8551    /// reports an item that connection is behind on. The module documentation is where the lag and the
8552    /// measurements behind it are written down.
8553    ///
8554    /// A search result is admitted on the same terms as any other issue this source reaches
8555    /// directly — [`Self::resolve_issue`] keeps it only if that issue's own `projectItems`
8556    /// names *this* board — so an issue the index still believes is here after it was taken
8557    /// off is refused rather than reported.
8558    ///
8559    /// See [`Self::board_cache`]. Both completions happen on every call rather than once,
8560    /// which is what the cache could otherwise have broken.
8561    async fn board(&self) -> Result<Board, SourceError> {
8562        self.board_completed_by(None).await
8563    }
8564
8565    /// [`Self::board`], its search half narrowed by `also` when it is given — which an issue
8566    /// that half could add is then answered only if it holds.
8567    async fn board_completed_by(&self, also: Option<&str>) -> Result<Board, SourceError> {
8568        let cached = self.board_cache()?.clone();
8569        let mut board = match cached {
8570            Some(board) => board,
8571            None => {
8572                let read = self.read_board().await?;
8573                *self.board_cache()? = Some(read.clone());
8574                read
8575            }
8576        };
8577        let searched = match also {
8578            None => self.searched_issues().await?,
8579            Some(also) => self.searched_narrowly(also).await?,
8580        };
8581        // A complete sweep asks for every page of this view. Reconcile ids once per
8582        // view, rather than scanning the board for every search result on every page.
8583        let mut ids: std::collections::HashSet<_> =
8584            board.items.iter().map(|item| item.id.clone()).collect();
8585        for held in searched {
8586            if ids.insert(held.id.clone()) {
8587                board.items.push(held);
8588            }
8589        }
8590        for own in self.created()?.iter() {
8591            if ids.insert(own.id.clone()) {
8592                board.items.push(own.clone());
8593            }
8594        }
8595        Ok(board)
8596    }
8597
8598    /// Every open item of this board, drafts included, read through the board's own `is:open`
8599    /// filter page by page — never its unfiltered `items`, and with no issue search beside it —
8600    /// held for the command under [`OPEN_ITEMS_KEY`] on the terms every narrowed answer is
8601    /// held on, and completed with this process's own writes each time it is given.
8602    ///
8603    /// What a task listing whose every status category is open reads: an item is open exactly
8604    /// when GitHub's filter answers it, so the categories are still confirmed in process from
8605    /// each item's own node, and the answer is the whole board's filtered to the same
8606    /// categories — an open issue under a terminal card read as its card, a draft and an item
8607    /// under an option no mapping names included.
8608    async fn open_items(&self) -> Result<Vec<Resolved>, SourceError> {
8609        let key = OPEN_ITEMS_KEY.to_owned();
8610        let cached = self.narrowed_cache()?.get(&key).cloned();
8611        let mut found = match cached {
8612            Some(found) => found,
8613            None => {
8614                let found = self.read_open_items().await?;
8615                self.narrowed_cache()?.insert(key, found.clone());
8616                found
8617            }
8618        };
8619        // Every item this process wrote, drafts included: the filter answers drafts, so an
8620        // own draft is as much an answer as an own issue. Its category is confirmed below like
8621        // any other's, so one this process closed is left out there.
8622        let own: Vec<Resolved> = self
8623            .created()?
8624            .iter()
8625            .chain(self.updated()?.iter())
8626            .cloned()
8627            .collect();
8628        for own in own {
8629            match found.iter_mut().find(|read| read.id == own.id) {
8630                Some(read) => *read = own,
8631                None => found.push(own),
8632            }
8633        }
8634        Ok(found)
8635    }
8636
8637    /// Every page of [`graphql::OPEN_ITEMS`], resolved; the board's own fields are held for
8638    /// the writes that follow, as a reconcile holds them.
8639    async fn read_open_items(&self) -> Result<Vec<Resolved>, SourceError> {
8640        let mut after: Option<String> = None;
8641        let mut found = Vec::new();
8642        loop {
8643            let data = self
8644                .graphql(
8645                    graphql::OPEN_ITEMS,
8646                    json!({"owner":self.owner,"number":self.project_number,
8647                           "first":MAX_PAGE_SIZE,"after":after,"filter":OPEN_QUALIFIER,
8648                           "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
8649                )
8650                .await?;
8651            let board = data
8652                .pointer("/openItems/projectV2")
8653                .filter(|value| !value.is_null())
8654                .ok_or_else(|| SourceError::Refused {
8655                    message: format!(
8656                        "GitHub project {}/{} was not found or is not visible to the token",
8657                        self.owner, self.project_number
8658                    ),
8659                })?;
8660            *self.fields_cache()? = Some(BoardFields {
8661                id: BoardId::parse(required_str(board, "id")?)?,
8662                fields: board.get("fields").cloned().unwrap_or(Value::Null),
8663            });
8664            let items = board.get("items").ok_or_else(|| SourceError::Malformed {
8665                message: "GitHub project open items are missing".into(),
8666            })?;
8667            for item in items
8668                .get("nodes")
8669                .and_then(Value::as_array)
8670                .ok_or_else(|| SourceError::Malformed {
8671                    message: "GitHub project items.nodes is not an array".into(),
8672                })?
8673            {
8674                if let Some(resolved) = self.resolve(item)? {
8675                    found.push(resolved);
8676                }
8677            }
8678            let info = items
8679                .get("pageInfo")
8680                .ok_or_else(|| SourceError::Malformed {
8681                    message: "GitHub project items have no pageInfo".into(),
8682                })?;
8683            if !required_bool(info, "hasNextPage")? {
8684                return Ok(found);
8685            }
8686            let next = required_str(info, "endCursor")?;
8687            validate_cursor_progress(after.as_deref(), next)?;
8688            after = Some(next.to_owned());
8689        }
8690    }
8691
8692    /// This process's own view of the board, or the refusal a poisoned lock is.
8693    fn board_cache(&self) -> Result<std::sync::MutexGuard<'_, Option<Board>>, SourceError> {
8694        self.board_cache
8695            .lock()
8696            .map_err(|_| SourceError::Unavailable {
8697                message: "this source's view of the board was left inconsistent by an earlier \
8698                      failure; next: run the command again"
8699                    .into(),
8700            })
8701    }
8702
8703    /// Bring this process's own view of the board up to an item it has just written.
8704    ///
8705    /// A created item goes to `created`, which is what completes a board read GitHub's own
8706    /// eventual consistency has left behind. An item that was already there is replaced
8707    /// where it sits, so a second write of it in the same command reads its real parent
8708    /// rather than the one it had before the first write.
8709    ///
8710    /// "Where it sits" is three places, and missing an earlier one leaves a stale record
8711    /// that wins: an item this same run created is held in `created` and not in the cached
8712    /// board, and `board` completes the cached board *from* `created`, so replacing only
8713    /// the cached copy of such an item replaces nothing and the read still reports the
8714    /// title it was created with. The search is the third, and it is the one an item the
8715    /// board's own projection is behind on sits in *alone* — which is exactly the item this
8716    /// source is least able to re-read, so leaving it out would put the stale title back on
8717    /// the only items the completion in [`Self::board`] exists for.
8718    fn remember_written(&self, item: Resolved, created: bool) -> Result<(), SourceError> {
8719        self.resolved_cache()?.insert(item.id.clone(), item.clone());
8720        if created {
8721            self.created()?.push(item);
8722            return Ok(());
8723        }
8724        {
8725            let mut own = self.created()?;
8726            if let Some(held) = own.iter_mut().find(|held| held.id == item.id) {
8727                *held = item;
8728                return Ok(());
8729            }
8730        }
8731        {
8732            let mut own = self.updated()?;
8733            match own.iter_mut().find(|held| held.id == item.id) {
8734                Some(held) => *held = item.clone(),
8735                None => own.push(item.clone()),
8736            }
8737        }
8738        if let Some(board) = self.board_cache()?.as_mut()
8739            && let Some(held) = board.items.iter_mut().find(|held| held.id == item.id)
8740        {
8741            *held = item.clone();
8742        }
8743        if let Some(found) = self.search_cache()?.as_mut()
8744            && let Some(held) = found.iter_mut().find(|held| held.id == item.id)
8745        {
8746            *held = item.clone();
8747        }
8748        for found in self.narrowed_cache()?.values_mut() {
8749            if let Some(held) = found.iter_mut().find(|held| held.id == item.id) {
8750                *held = item.clone();
8751            }
8752        }
8753        for rows in self.search_rows()?.values_mut() {
8754            if let Some(held) = rows.iter_mut().flatten().find(|held| held.id == item.id) {
8755                *held = item.clone();
8756            }
8757        }
8758        for (_, found) in self.children_cache()?.values_mut() {
8759            if let Some(held) = found.iter_mut().find(|held| held.id == item.id) {
8760                *held = item.clone();
8761            }
8762        }
8763        Ok(())
8764    }
8765
8766    /// Forget one item this process has just deleted, from every half of its own view.
8767    fn forget(&self, id: &NativeId) -> Result<(), SourceError> {
8768        if let Some(Deferred::Held { created, .. }) = self.deferred()?.as_mut() {
8769            created.retain(|held| held.content != *id);
8770        }
8771        self.resolved_cache()?.remove(id);
8772        self.read_ahead()?.remove(id);
8773        self.carried()?.remove(id);
8774        self.created()?.retain(|own| own.id != *id);
8775        self.updated()?.retain(|own| own.id != *id);
8776        self.commented()?.retain(|own| own != id);
8777        if let Some(board) = self.board_cache()?.as_mut() {
8778            board.items.retain(|item| item.id != *id);
8779        }
8780        if let Some(found) = self.search_cache()?.as_mut() {
8781            found.retain(|item| item.id != *id);
8782        }
8783        for found in self.narrowed_cache()?.values_mut() {
8784            found.retain(|item| item.id != *id);
8785        }
8786        // Emptied rather than removed, so every later row of its page keeps its position.
8787        for rows in self.search_rows()?.values_mut() {
8788            for row in rows.iter_mut() {
8789                if row.as_ref().is_some_and(|item| item.id == *id) {
8790                    *row = None;
8791                }
8792            }
8793        }
8794        for (_, found) in self.children_cache()?.values_mut() {
8795            found.retain(|item| item.id != *id);
8796        }
8797        Ok(())
8798    }
8799
8800    /// This process's own record of each page of a narrowed search's own read, row for row, or
8801    /// the refusal a poisoned lock is.
8802    fn search_rows(&self) -> Result<std::sync::MutexGuard<'_, SearchRows>, SourceError> {
8803        self.search_rows
8804            .lock()
8805            .map_err(|_| SourceError::Unavailable {
8806                message: "this source's view of a narrowed search was left inconsistent by an \
8807                      earlier failure; next: run the command again"
8808                    .into(),
8809            })
8810    }
8811
8812    /// This process's own record of each narrowed answer, or the refusal a poisoned lock is.
8813    fn narrowed_cache(
8814        &self,
8815    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<String, Vec<Resolved>>>, SourceError> {
8816        self.narrowed_cache
8817            .lock()
8818            .map_err(|_| SourceError::Unavailable {
8819                message: "this source's view of a narrowed read was left inconsistent by an \
8820                      earlier failure; next: run the command again"
8821                    .into(),
8822            })
8823    }
8824
8825    /// This process's own record of each project's sub-issues, or the refusal a poisoned lock
8826    /// is.
8827    /// The tasks `project` holds, as a copy's batched read found them this command, when it did.
8828    fn held_task_children(&self, project: &NativeId) -> Result<Option<Vec<Resolved>>, SourceError> {
8829        Ok(self.task_children()?.get(project).cloned())
8830    }
8831
8832    fn task_children(
8833        &self,
8834    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Vec<Resolved>>>, SourceError> {
8835        self.task_children
8836            .lock()
8837            .map_err(|_| SourceError::Unavailable {
8838                message: "this source's record of a project's tasks was left inconsistent by an \
8839                          earlier failure; next: run the command again"
8840                    .into(),
8841            })
8842    }
8843
8844    fn children_cache(&self) -> Result<std::sync::MutexGuard<'_, ProjectChildren>, SourceError> {
8845        self.children_cache
8846            .lock()
8847            .map_err(|_| SourceError::Unavailable {
8848                message: "this source's view of a project's tasks was left inconsistent by an \
8849                      earlier failure; next: run the command again"
8850                    .into(),
8851            })
8852    }
8853
8854    /// Every page of the board, read from GitHub.
8855    async fn read_board(&self) -> Result<Board, SourceError> {
8856        let mut after: Option<String> = None;
8857        let mut items = Vec::new();
8858        let mut board;
8859        loop {
8860            let page = self.board_page(after.as_deref(), MAX_PAGE_SIZE).await?;
8861            for item in page
8862                .pointer("/items/nodes")
8863                .and_then(Value::as_array)
8864                .ok_or_else(|| SourceError::Malformed {
8865                    message: "GitHub project items.nodes is not an array".into(),
8866                })?
8867            {
8868                if let Some(resolved) = self.resolve(item)? {
8869                    items.push(resolved);
8870                }
8871            }
8872            let info = page
8873                .pointer("/items/pageInfo")
8874                .ok_or_else(|| SourceError::Malformed {
8875                    message: "GitHub project items have no pageInfo".into(),
8876                })?;
8877            let has_next = required_bool(info, "hasNextPage")?;
8878            let next = has_next
8879                .then(|| required_str(info, "endCursor"))
8880                .transpose()?;
8881            board = page.clone();
8882            match next {
8883                Some(next) => {
8884                    validate_cursor_progress(after.as_deref(), next)?;
8885                    after = Some(next.to_owned());
8886                }
8887                None => break,
8888            }
8889        }
8890        Ok(Board {
8891            id: required_str(&board, "id")?.to_owned(),
8892            fields: board.get("fields").cloned().unwrap_or(Value::Null),
8893            items,
8894        })
8895    }
8896
8897    /// The existing items this source has written, for completing a narrowed read that is
8898    /// behind; see [`Self::updated`](GitHubProjectsSource::updated).
8899    fn updated(&self) -> Result<std::sync::MutexGuard<'_, Vec<Resolved>>, SourceError> {
8900        self.updated.lock().map_err(|_| SourceError::Unavailable {
8901            message: "this source's record of what it wrote in this run was left inconsistent \
8902                      by an earlier failure; next: run the command again"
8903                .into(),
8904        })
8905    }
8906
8907    /// The issues this source has commented on in this command; see
8908    /// [`Self::commented`](GitHubProjectsSource::commented).
8909    fn commented(&self) -> Result<std::sync::MutexGuard<'_, Vec<NativeId>>, SourceError> {
8910        self.commented.lock().map_err(|_| SourceError::Unavailable {
8911            message: "this source's record of what it commented on in this run was left \
8912                      inconsistent by an earlier failure; next: run the command again"
8913                .into(),
8914        })
8915    }
8916
8917    /// Called only once GitHub has answered the comment write, so an issue whose comment
8918    /// failed is never made a candidate a later read would pay a node read for.
8919    fn remember_commented(&self, issue: &NativeId) -> Result<(), SourceError> {
8920        // A comment page held for this command is no longer what the issue holds.
8921        self.held_comments()?.remove(issue);
8922        let mut commented = self.commented()?;
8923        if !commented.contains(issue) {
8924            commented.push(issue.clone());
8925        }
8926        Ok(())
8927    }
8928
8929    /// The items this source has created, for completing a board read that is behind.
8930    fn created(&self) -> Result<std::sync::MutexGuard<'_, Vec<Resolved>>, SourceError> {
8931        self.created.lock().map_err(|_| SourceError::Unavailable {
8932            message: "this source's record of what it created in this run was left \
8933                      inconsistent by an earlier failure; next: run the command again"
8934                .into(),
8935        })
8936    }
8937
8938    /// One board item as this source reports it, or `None` for content it ignores.
8939    ///
8940    /// A pull request is neither a project nor a task — it is somebody's change, not a
8941    /// unit of plan — and an item whose content the token cannot see has nothing to
8942    /// report at all.
8943    fn resolve(&self, item: &Value) -> Result<Option<Resolved>, SourceError> {
8944        let resolved = self.resolve_unremembered(item)?;
8945        if let Some(resolved) = &resolved {
8946            self.resolved_cache()?
8947                .insert(resolved.id.clone(), resolved.clone());
8948        }
8949        Ok(resolved)
8950    }
8951
8952    /// [`Self::resolve`], without remembering the item it resolves: what reading a token off a
8953    /// write's own response needs, which says nothing this process should answer a later read
8954    /// with.
8955    fn resolve_unremembered(&self, item: &Value) -> Result<Option<Resolved>, SourceError> {
8956        let content = item.get("content").ok_or_else(|| SourceError::Malformed {
8957            message: "GitHub project item is missing content".into(),
8958        })?;
8959        if content.is_null() {
8960            return Ok(None);
8961        }
8962        let content_kind = match required_str(content, "__typename")? {
8963            "Issue" => ContentKind::Issue,
8964            "DraftIssue" => ContentKind::DraftIssue,
8965            _ => return Ok(None),
8966        };
8967        let field_values = item
8968            .get("fieldValues")
8969            .ok_or_else(|| SourceError::Malformed {
8970                message: "GitHub project item is missing fieldValues".into(),
8971            })?;
8972        complete_connection(field_values, "project item field values", NESTED_PAGE_SIZE)?;
8973        let nodes = field_values
8974            .get("nodes")
8975            .and_then(Value::as_array)
8976            .ok_or_else(|| SourceError::Malformed {
8977                message: "GitHub project item fieldValues.nodes is not an array".into(),
8978            })?;
8979        if let Some(labels) = content.get("labels") {
8980            complete_connection(labels, "content labels", NESTED_PAGE_SIZE)?;
8981        }
8982        let raw_body = optional_str(content, "body")?.map(str::to_owned);
8983        let (body, slot) = self.visible(raw_body.clone())?;
8984        let parent = optional_str(content.get("parent").unwrap_or(&Value::Null), "id")?
8985            .map(|id| NativeId(id.to_owned()));
8986        // A draft has no sub-issues to summarise, and GitHub's schema gives it no field
8987        // to read one from; it is a task, and never a project.
8988        let sub_issues = match content_kind {
8989            ContentKind::Issue => sub_issue_total(content)?,
8990            ContentKind::DraftIssue => 0,
8991        };
8992        let content_id = required_str(content, "id")?;
8993        let marked = ItemKind::from_metadata(&slot).map_err(|message| SourceError::Malformed {
8994            message: format!("GitHub issue {content_id}: {message}"),
8995        })?;
8996        let raw_title = required_str(content, "title")?;
8997        // Read as children, a sub-issue is filed under no project and nothing is a project: the
8998        // GitHub parent is the parent relation instead.
8999        let (kind, parent, issue_parent) = match self.sub_issues {
9000            SubIssues::Project => (
9001                BoardKind::of(raw_title, parent.is_some(), sub_issues, marked),
9002                parent,
9003                None,
9004            ),
9005            SubIssues::Parent => (
9006                if raw_title.starts_with(DESIGN_TITLE_PREFIX) {
9007                    BoardKind::Document
9008                } else {
9009                    BoardKind::Work(ItemKind::Task)
9010                },
9011                None,
9012                parent,
9013            ),
9014        };
9015        // The title a person wrote, which for a document is the one without the prefix —
9016        // the same way `content` above is the body without this source's metadata slot.
9017        let title = match kind {
9018            BoardKind::Document => raw_title[DESIGN_TITLE_PREFIX.len()..].to_owned(),
9019            BoardKind::Work(_) => raw_title.to_owned(),
9020        };
9021        let own_repository = content
9022            .pointer("/repository/nameWithOwner")
9023            .and_then(Value::as_str)
9024            .map(|origin| Repository::try_from(format!("{}/{origin}", RepositoryTarget::HOST)))
9025            .transpose()
9026            .map_err(|message| SourceError::Malformed { message })?;
9027        let repositories = if slot.contains_key(Repository::METADATA_KEY) {
9028            Repository::from_metadata(&slot)
9029                .map_err(|message| SourceError::Malformed { message })?
9030        } else {
9031            own_repository.clone().into_iter().collect()
9032        };
9033        let classification = Classification::from_metadata(&slot)
9034            .map_err(|message| SourceError::Malformed { message })?;
9035        let id = NativeId(content_id.to_owned());
9036        // Read only for a task, because only a task has either list: a project or a
9037        // document holding one of these keys holds nothing this source reports, and the
9038        // keys are left out of its caller-visible metadata all the same.
9039        let (delivers, delivered_by) = if kind == BoardKind::Work(ItemKind::Task) {
9040            let listed = |key: &str| {
9041                TaskRef::from_value(key, &id, Some(&self.name), slot.get(key))
9042                    .map_err(|message| SourceError::Malformed { message })
9043            };
9044            (
9045                listed(TaskRef::DELIVERS_KEY)?,
9046                listed(TaskRef::DELIVERED_BY_KEY)?,
9047            )
9048        } else {
9049            (Vec::new(), Vec::new())
9050        };
9051        let (option, closed, reason) = Self::status_parts(nodes, content)?;
9052        let priority = self.held_priority(nodes)?;
9053        let item_labels = labels(content)?;
9054        // Present when the item was reached through its own issue, whose board entry
9055        // names the board; a read of the board's own items has the board already. An
9056        // empty id names nothing a field write could address, so it is read as absent and
9057        // the write goes back to reading the board.
9058        let board_id = item
9059            .pointer("/project/id")
9060            .and_then(Value::as_str)
9061            .filter(|id| !id.is_empty());
9062        let resolved = Resolved {
9063            item_id: required_str(item, "id")?.to_owned(),
9064            id,
9065            content_kind,
9066            kind,
9067            title,
9068            body: body.filter(|value| !value.is_empty()),
9069            raw_body,
9070            status: self
9071                .statuses
9072                .status(kind.status_kind(), option, closed, reason),
9073            option: option.map(str::to_owned),
9074            priority,
9075            closed,
9076            reason: closed.then(|| reason.map(str::to_owned)).flatten(),
9077            delivers,
9078            delivered_by,
9079            labels: item_labels.clone(),
9080            parent,
9081            issue_parent,
9082            origin: text_field(nodes, ORIGIN_FIELD)?.filter(|value| !value.is_empty()),
9083            projected: self.held_projections(nodes)?,
9084            number: match content_kind {
9085                ContentKind::Issue => Some(issue_number(content)?),
9086                // A draft is filed in no repository, so nothing ever numbered it:
9087                // `DraftIssue` declares no `number` at all, exactly as it declares no
9088                // `subIssuesSummary` the branch above reads.
9089                ContentKind::DraftIssue => None,
9090            },
9091            url: optional_str(content, "url")?.map(str::to_owned),
9092            created_at: optional_time(content, "createdAt")?,
9093            updated_at: optional_time(content, "updatedAt")?,
9094            item_updated_at: optional_time(item, "updatedAt")?,
9095            comment_count: content
9096                .pointer("/commentCount/totalCount")
9097                .and_then(Value::as_u64),
9098            relationship_events: content
9099                .pointer("/relationshipEvents/totalCount")
9100                .and_then(Value::as_u64),
9101            // The issue node is stamped wherever it was read; a board item a read of the issue
9102            // put together from its memberships is not.
9103            served_at: match optional_time(content, SERVED_AT)? {
9104                Some(served) => Some(served),
9105                None => optional_time(item, SERVED_AT)?,
9106            },
9107            // Both connections were read to their end above — one reporting a further page is
9108            // refused — so these are every field value and every label the item holds. A
9109            // response that did not select the labels at all says nothing of them, and gives
9110            // no facets.
9111            facets: content.get("labels").is_some().then(|| {
9112                change_token::Facets::new(kind.facet(), facet_fields(nodes), &item_labels).digest()
9113            }),
9114            own_repository,
9115            repositories,
9116            classification,
9117            slot,
9118            board_id: board_id.map(str::to_owned),
9119            fields: field_definitions(nodes),
9120            board_fields: Self::carried_board_fields(content, board_id)?,
9121            blocked_by: carried_blocked_by(content)?,
9122            assignees: if self.assignees {
9123                Some(assignees::assignee_logins(content)?)
9124            } else {
9125                None
9126            },
9127        };
9128        Ok(Some(resolved))
9129    }
9130
9131    /// The field definitions of the board `board_id` names — the project this issue's own
9132    /// board item is on — off the `boards` page a read of an issue by its own id carries, or
9133    /// `None` when the read carried none, carried no entry for that board, or the board item
9134    /// named no board, which a write then answers by reading the board's fields itself.
9135    ///
9136    /// Matched by the board's node id and never by its number alone: a project number is
9137    /// unique only within its owner, so another owner's board numbered alike can sit on the
9138    /// same page, and its field and option ids address nothing on this one.
9139    fn carried_board_fields(
9140        content: &Value,
9141        board_id: Option<&str>,
9142    ) -> Result<Option<Value>, SourceError> {
9143        let (Some(nodes), Some(board_id)) = (
9144            content.pointer("/boards/nodes").and_then(Value::as_array),
9145            board_id,
9146        ) else {
9147            return Ok(None);
9148        };
9149        let Some(board) = nodes.iter().find_map(|node| {
9150            let project = node.get("project")?;
9151            (project.get("id").and_then(Value::as_str) == Some(board_id)).then_some(project)
9152        }) else {
9153            return Ok(None);
9154        };
9155        let Some(fields) = board.get("fields").filter(|fields| !fields.is_null()) else {
9156            return Ok(None);
9157        };
9158        complete_connection(fields, "board fields", NESTED_PAGE_SIZE)?;
9159        Ok(Some(fields.clone()))
9160    }
9161
9162    /// What one board item's `Priority` field says, through this instance's mapping.
9163    ///
9164    /// An instance with no mapping holds no priority, so every item reads as `none` whatever
9165    /// its board holds. With one, no value is `none`, a mapped option is its level, and an
9166    /// option the mapping does not name is kept as itself — never read as a level or as
9167    /// `none` — for a read of the task to report by name.
9168    fn held_priority(&self, field_values: &[Value]) -> Result<HeldPriority, SourceError> {
9169        let Some(mapping) = &self.priorities else {
9170            return Ok(HeldPriority::Read(Priority::None));
9171        };
9172        // A value of the field that names no option — a text field someone called `Priority` —
9173        // is malformed rather than `none`: reading it as no priority would let the next copy
9174        // clear one a person set.
9175        let Some(option) = field_values
9176            .iter()
9177            .find(|value| {
9178                value.pointer("/field/name").and_then(Value::as_str) == Some(PRIORITY_FIELD)
9179            })
9180            .map(|value| required_str(value, "name"))
9181            .transpose()?
9182        else {
9183            return Ok(HeldPriority::Read(Priority::None));
9184        };
9185        Ok(mapping.priority_of(option).map_or_else(
9186            || HeldPriority::Unmapped(option.to_owned()),
9187            HeldPriority::Read,
9188        ))
9189    }
9190
9191    /// What each projected metadata field holds for one board item, by field name — every text
9192    /// value GitHub answers, an empty one included.
9193    fn held_projections(
9194        &self,
9195        field_values: &[Value],
9196    ) -> Result<BTreeMap<String, String>, SourceError> {
9197        let mut held = BTreeMap::new();
9198        for projection in &self.metadata_fields {
9199            if let Some(text) = text_field(field_values, &projection.field)? {
9200                held.insert(projection.field.to_string(), text);
9201            }
9202        }
9203        Ok(held)
9204    }
9205
9206    /// What one board item's status is read from: its `Status` option, whether its issue
9207    /// is closed, and the reason it was closed with. [`BoardStatuses::status`] turns the
9208    /// three into the status it reports.
9209    fn status_parts<'a>(
9210        field_values: &'a [Value],
9211        content: &'a Value,
9212    ) -> Result<(Option<&'a str>, bool, Option<&'a str>), SourceError> {
9213        let option = field_values
9214            .iter()
9215            .find(|value| value.pointer("/field/name").and_then(Value::as_str) == Some("Status"))
9216            .map(|value| required_str(value, "name"))
9217            .transpose()?;
9218        let closed = optional_str(content, "state")? == Some("CLOSED");
9219        Ok((option, closed, optional_str(content, "stateReason")?))
9220    }
9221
9222    /// The board Status option this write selects, or the refusal that says why not.
9223    ///
9224    /// The mapped option is required for both open and terminal targets. A terminal write
9225    /// validates it before changing either representation, so it can never fall back to
9226    /// closing an issue whose board cannot display the matching status.
9227    ///
9228    /// Answers the field's id, the option's id, and the option's name as the board spells
9229    /// it — which is the name a read of the item reports once it sits there.
9230    fn column_for(
9231        &self,
9232        fields: &Value,
9233        kind: ItemKind,
9234        category: StatusCategory,
9235        target: &StatusTarget,
9236    ) -> Result<Option<(String, String, String)>, SourceError> {
9237        let Some(wanted) = target.option() else {
9238            return Ok(None);
9239        };
9240        let missing = |detail: &str| SourceError::Refused {
9241            message: format!(
9242                "{} status {} of source {} needs the board Status option {wanted:?}, and \
9243                 {detail}; next: add that option to the board, which `onetaskgraph sources \
9244                 fields {} --apply` does, or point status_mapping.{}.{} of this source at one \
9245                 it has",
9246                kind.marker(),
9247                category_name(category),
9248                self.name,
9249                self.name,
9250                category_name(category),
9251                kind.marker()
9252            ),
9253        };
9254        let Some(field) = Board::field(fields, "Status")? else {
9255            return Err(missing("this board has no Status field"));
9256        };
9257        if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
9258            return Err(missing(
9259                "this board's Status field is not a single-select field",
9260            ));
9261        }
9262        let option = field
9263            .get("options")
9264            .and_then(Value::as_array)
9265            .and_then(|options| {
9266                options.iter().find(|option| {
9267                    option
9268                        .get("name")
9269                        .and_then(Value::as_str)
9270                        .is_some_and(|name| name.eq_ignore_ascii_case(wanted))
9271                })
9272            });
9273        match option {
9274            None => Err(missing("this board does not have it")),
9275            Some(option) => Ok(Some((
9276                required_str(field, "id")?.to_owned(),
9277                required_str(option, "id")?.to_owned(),
9278                required_str(option, "name")?.to_owned(),
9279            ))),
9280        }
9281    }
9282
9283    /// The refusal a status that closes an issue is answered with over a board draft.
9284    fn closes_a_draft(&self, category: StatusCategory) -> SourceError {
9285        SourceError::Refused {
9286            message: format!(
9287                "status {} of source {} closes the item's issue, and GitHub draft items have \
9288                 no open or closed state",
9289                category_name(category),
9290                self.name
9291            ),
9292        }
9293    }
9294
9295    /// What a status write to one item needs of the board: the board's id and the
9296    /// definition of its `Status` field, read off the item when the item says both.
9297    ///
9298    /// The same reasoning as [`Self::fields_for`]: a node read of the item names its board,
9299    /// and its `Status` value carries that field's definition, options and all. An item that
9300    /// does not say — no board id, or no `Status` value to read the field off — takes them
9301    /// from [`Self::board_fields`], which reads no item.
9302    async fn status_board(&self, item: &Resolved) -> Result<BoardFields, SourceError> {
9303        if let Some(board) = item.carried_board() {
9304            return Ok(board);
9305        }
9306        if item.defines("Status")
9307            && let Some(board_id) = item.named_board()
9308        {
9309            return Ok(BoardFields {
9310                id: board_id,
9311                fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
9312            });
9313        }
9314        self.board_fields().await
9315    }
9316
9317    /// Set one task's or one project's status and nothing else; see
9318    /// [`TaskSource::set_task_status`] and [`TaskSource::set_project_status`].
9319    async fn set_status(
9320        &self,
9321        id: &NativeId,
9322        kind: ItemKind,
9323        category: StatusCategory,
9324    ) -> Result<Option<Status>, SourceError> {
9325        // Refused before anything is read, in the words a write of the same status is.
9326        let target = self.resolved_target(kind, category)?;
9327        // An item read by issue reference carries only what this write needs, so what it
9328        // becomes is never remembered for a later read to be answered from.
9329        let held = self.take_held(id)?;
9330        let by_reference = held.is_some();
9331        let bound = match held {
9332            Some(item) => Some(item),
9333            None => self.bound_item(id).await?,
9334        };
9335        let Some(mut item) = bound.filter(|item| item.kind == BoardKind::Work(kind)) else {
9336            return Ok(None);
9337        };
9338        let board = self.status_board(&item).await?;
9339        let (field, option, name) = self
9340            .column_for(&board.fields, kind, category, &target)?
9341            .ok_or_else(|| SourceError::Malformed {
9342                message: format!(
9343                    "status {} of source {} names no board Status option",
9344                    category_name(category),
9345                    self.name
9346                ),
9347            })?;
9348        // The card already shows the target's option. That alone is not the status: an open
9349        // issue under a terminal card reads that card's category while GitHub, its
9350        // notifications and a search of open issues all say the work is not finished, and a
9351        // closed issue under an open column's card reads as its closure. So the write is no
9352        // write only where the issue's open or closed state is also what the target needs —
9353        // closed, for a reason reading this category, for a terminal one; open for a column.
9354        let at_option = item
9355            .option
9356            .as_deref()
9357            .is_some_and(|held| held.eq_ignore_ascii_case(&name));
9358        let issue = item.content_kind == ContentKind::Issue;
9359        let state_holds = match &target {
9360            StatusTarget::Terminal(_, _) => {
9361                !issue || (item.closed && closed_category(item.reason.as_deref()) == category)
9362            }
9363            _ => !issue || !item.closed,
9364        };
9365        if item.status.category == category && at_option && state_holds {
9366            return Ok(Some(item.status));
9367        }
9368        match &target {
9369            StatusTarget::Terminal(_, reason) => {
9370                if item.content_kind == ContentKind::DraftIssue {
9371                    return Err(self.closes_a_draft(category));
9372                }
9373                // The option first, so a refused selection leaves an open issue open rather
9374                // than closed behind a card that still reads open. A card already showing it
9375                // is sent nothing: only the issue's state is out of line.
9376                if !at_option {
9377                    self.set_item_field(
9378                        board.id.as_str(),
9379                        &item.item_id,
9380                        &field,
9381                        json!({"singleSelectOptionId": option}),
9382                    )
9383                    .await?;
9384                }
9385                // An issue already closed in a way that reads as this category keeps its state
9386                // and its reason: only its card was out of line, and closing it again would
9387                // overwrite a reason — a duplicate's — that says more than this write does.
9388                let already = item.closed && item.status.category == category;
9389                if !already {
9390                    self.update_content(
9391                        ContentKind::Issue,
9392                        &item.id,
9393                        json!({"stateInput": state_input(Some(&target))}),
9394                    )
9395                    .await?;
9396                }
9397                let reason = if already {
9398                    item.reason.clone()
9399                } else {
9400                    Some(reason.reason().to_owned())
9401                };
9402                item.closed = true;
9403                item.status = self
9404                    .statuses
9405                    .status(kind, Some(&name), true, reason.as_deref());
9406                item.option = Some(name);
9407                item.reason = reason;
9408            }
9409            StatusTarget::Column(_) => {
9410                // An option is what an open item's status is, so a closed issue is reopened
9411                // first — sitting closed in the column, it would read back as closed. A draft has
9412                // no state to reopen.
9413                if item.content_kind == ContentKind::Issue && item.closed {
9414                    self.update_content(
9415                        ContentKind::Issue,
9416                        &item.id,
9417                        json!({"stateInput": state_input(Some(&target))}),
9418                    )
9419                    .await?;
9420                    item.closed = false;
9421                }
9422                if !at_option {
9423                    self.set_item_field(
9424                        board.id.as_str(),
9425                        &item.item_id,
9426                        &field,
9427                        json!({"singleSelectOptionId": option}),
9428                    )
9429                    .await?;
9430                }
9431                item.status = self.statuses.status(kind, Some(&name), false, None);
9432                item.option = Some(name);
9433            }
9434            StatusTarget::Disabled(_) => {
9435                unreachable!("resolved_target refused a disabled status")
9436            }
9437        }
9438        let status = item.status.clone();
9439        if !by_reference {
9440            self.remember_written(item, false)?;
9441        }
9442        Ok(Some(status))
9443    }
9444
9445    /// Replace one task's `delivered_by` and nothing else; see
9446    /// [`TaskSource::set_delivered_by`].
9447    ///
9448    /// One update of the body, which differs from the body GitHub holds only inside the
9449    /// metadata slot — see [`with_slot`]. A body that would not change is not sent at all.
9450    async fn replace_delivered_by(
9451        &self,
9452        id: &NativeId,
9453        delivered_by: &[TaskRef],
9454    ) -> Result<Option<()>, SourceError> {
9455        let entries = TaskRef::listed(
9456            TaskRef::DELIVERED_BY_KEY,
9457            id,
9458            Some(&self.name),
9459            delivered_by.to_vec(),
9460        )
9461        .map_err(|message| SourceError::Refused { message })?;
9462        let Some(mut item) = self
9463            .bound_item(id)
9464            .await?
9465            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9466        else {
9467            return Ok(None);
9468        };
9469        let mut slot = item.slot.clone();
9470        set_task_list(&mut slot, TaskRef::DELIVERED_BY_KEY, &entries);
9471        self.write_slot(&mut item, &slot).await?;
9472        item.delivered_by = entries;
9473        self.remember_written(item, false)?;
9474        Ok(Some(()))
9475    }
9476
9477    /// Set one caller key of the metadata slot of one issue of `kind`, and nothing else;
9478    /// see [`TaskSource::set_task_metadata`].
9479    ///
9480    /// `None` when this board holds no item by that id, or holds one of another kind. The
9481    /// answer is the item as this source now reads it, so what a caller is told the key
9482    /// holds is what the slot holds.
9483    ///
9484    /// A key already holding the value is answered without a write, compared as JSON rather
9485    /// than as the body's bytes: a slot a person spelled with other whitespace would
9486    /// otherwise be re-encoded, which is a write that changes nothing the caller asked for.
9487    async fn set_slot_key(
9488        &self,
9489        id: &NativeId,
9490        kind: BoardKind,
9491        key: &MetadataKey,
9492        value: &Value,
9493    ) -> Result<Option<Resolved>, SourceError> {
9494        let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
9495            return Ok(None);
9496        };
9497        if item.slot.get(key.as_str()) == Some(value) {
9498            return Ok(Some(item));
9499        }
9500        let mut slot = item.slot.clone();
9501        slot.insert(key.as_str().to_owned(), value.clone());
9502        // A key a board text field projects moves that field first, so the body — the value's
9503        // one authoritative home — is written last, as every write of an existing item is.
9504        if self
9505            .metadata_fields
9506            .iter()
9507            .any(|projection| &*projection.key == key.as_str())
9508        {
9509            let board = self.projection_board(&item).await?;
9510            let (writes, projected) = self.projection_writes(
9511                &board.fields,
9512                Some(&item.projected),
9513                &slot,
9514                Some(&[key.as_str()]),
9515            )?;
9516            let (mut values, mut clears) = (Vec::new(), Vec::new());
9517            for write in &writes {
9518                write.join(&mut values, &mut clears);
9519            }
9520            self.set_item_fields(board.id.as_str(), &item.item_id, &values, &clears)
9521                .await?;
9522            item.projected = projected;
9523        }
9524        self.write_slot(&mut item, &slot).await?;
9525        self.remember_written(item.clone(), false)?;
9526        Ok(Some(item))
9527    }
9528
9529    /// What a projection write to `item` needs of the board, read off the item when it says
9530    /// enough, as [`Self::fields_for`] reads it.
9531    async fn projection_board(&self, item: &Resolved) -> Result<BoardFields, SourceError> {
9532        if let Some(board) = item.carried_board() {
9533            return Ok(board);
9534        }
9535        if let Some(board_id) = item.named_board()
9536            && self
9537                .metadata_fields
9538                .iter()
9539                .all(|projection| item.defines(&projection.field))
9540        {
9541            return Ok(BoardFields {
9542                id: board_id,
9543                fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
9544            });
9545        }
9546        self.board_fields().await
9547    }
9548
9549    /// Put `slot` in one item's metadata slot with a single update of its body, and bring
9550    /// `item` up to what that write left.
9551    ///
9552    /// The body sent differs from the body GitHub holds only inside the slot — see
9553    /// [`with_slot`] — and a body that would not change is not sent at all. It goes through
9554    /// the mutation the item's content takes, so a board draft's body is written with
9555    /// `updateProjectV2DraftIssue` exactly as an issue's is with `updateIssue`.
9556    async fn write_slot(
9557        &self,
9558        item: &mut Resolved,
9559        slot: &BTreeMap<String, Value>,
9560    ) -> Result<(), SourceError> {
9561        let held = item.raw_body.clone().unwrap_or_default();
9562        let body = with_slot(&held, slot)?;
9563        if body != held {
9564            self.update_content(item.content_kind, &item.id, json!({"body": body}))
9565                .await?;
9566        }
9567        let (visible, slot) = self.visible(Some(body.clone()))?;
9568        item.body = visible.filter(|value| !value.is_empty());
9569        item.raw_body = Some(body);
9570        item.slot = slot;
9571        Ok(())
9572    }
9573
9574    /// This instance's target for a category written to an item of `kind`, refusing one
9575    /// that kind has no option for — before anything is read or written.
9576    ///
9577    /// Nothing here mutates the board's option set to make room for a status. GitHub
9578    /// documents `UpdateProjectV2FieldInput.singleSelectOptions` as *"provided values
9579    /// overwrite existing options"*, so no addition is additive and a mistake destroys the
9580    /// field and every item's status.
9581    fn resolved_target(
9582        &self,
9583        kind: ItemKind,
9584        category: StatusCategory,
9585    ) -> Result<StatusTarget, SourceError> {
9586        let target = self.statuses.target(kind, category).clone();
9587        let StatusTarget::Disabled(why) = target else {
9588            return Ok(target);
9589        };
9590        let refusal = why.refusal(&self.name, category, kind);
9591        // Why there is no shipped default, which is the question a person meeting this
9592        // refusal on a source that never mentioned the category asks.
9593        let shipped_none = match category {
9594            StatusCategory::Draft => Some(
9595                "draft has no shipped default because GitHub draft issues cannot have \
9596                 sub-issues, and this source stores a project's tasks as its issue's sub-issues",
9597            ),
9598            StatusCategory::Unknown => Some(
9599                "unknown has no shipped default because this board keeps no open-ended status \
9600                 word: every word classified unknown is written to the one board Status option \
9601                 status_mapping.unknown names",
9602            ),
9603            _ => None,
9604        };
9605        Err(match (refusal, shipped_none, why) {
9606            (SourceError::Refused { message }, Some(note), UnmappedStatus::Unconfigured) => {
9607                SourceError::Refused {
9608                    message: format!("{message}; {note}"),
9609                }
9610            }
9611            (refusal, _, _) => refusal,
9612        })
9613    }
9614
9615    /// What writing `priority` does to one item's `Priority` field on this board, or the
9616    /// refusal naming what the board lacks.
9617    ///
9618    /// `none` is no value, so it clears the field — and asks nothing of an item that holds
9619    /// none already, or of an item not created yet. Every other priority selects the option
9620    /// the mapping names, matched case-insensitively; a board with no `Priority` field, or
9621    /// without that option, is refused rather than given one: reads and writes never create
9622    /// a field or an option.
9623    fn priority_write(
9624        &self,
9625        fields: &Value,
9626        existing: Option<&Resolved>,
9627        priority: Priority,
9628    ) -> Result<Option<PriorityWrite>, SourceError> {
9629        let Some(mapping) = &self.priorities else {
9630            return Err(self.holds_no_priority());
9631        };
9632        let Some(wanted) = mapping.option(priority) else {
9633            if !existing.is_some_and(Resolved::holds_priority) {
9634                return Ok(None);
9635            }
9636            let field =
9637                Board::field(fields, PRIORITY_FIELD)?.ok_or_else(|| SourceError::Malformed {
9638                    message: format!(
9639                        "an item holding a {PRIORITY_FIELD} value was read without that field"
9640                    ),
9641                })?;
9642            return Ok(Some(PriorityWrite::Clear {
9643                field: required_str(field, "id")?.to_owned(),
9644            }));
9645        };
9646        let missing = |detail: &str| SourceError::Refused {
9647            message: format!(
9648                "priority {priority} of source {} needs the board {PRIORITY_FIELD} option \
9649                 {wanted:?}, and {detail}; run `onetaskgraph sources fields {} --apply` to add \
9650                 it, or point priority_mapping.{priority} of this source at an option the board \
9651                 has",
9652                self.name, self.name
9653            ),
9654        };
9655        let Some(field) = Board::field(fields, PRIORITY_FIELD)? else {
9656            return Err(missing(&format!(
9657                "this board has no {PRIORITY_FIELD} field"
9658            )));
9659        };
9660        if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
9661            return Err(missing(&format!(
9662                "this board's {PRIORITY_FIELD} field is not a single-select field"
9663            )));
9664        }
9665        // An options list that is absent or not a list is an answer this source cannot read,
9666        // not a board lacking the option: `sources fields --apply` is no remedy for it.
9667        let option = field
9668            .get("options")
9669            .and_then(Value::as_array)
9670            .ok_or_else(|| SourceError::Malformed {
9671                message: format!("GitHub {PRIORITY_FIELD} field options is not an array"),
9672            })?
9673            .iter()
9674            .find(|option| {
9675                option
9676                    .get("name")
9677                    .and_then(Value::as_str)
9678                    .is_some_and(|name| name.eq_ignore_ascii_case(wanted))
9679            })
9680            .ok_or_else(|| missing("this board does not have it"))?;
9681        Ok(Some(PriorityWrite::Select {
9682            field: required_str(field, "id")?.to_owned(),
9683            option: required_str(option, "id")?.to_owned(),
9684        }))
9685    }
9686
9687    /// What writing `metadata` does to each projected text field of one item, and what those
9688    /// fields hold after it — or the refusal, before anything is sent.
9689    ///
9690    /// `held` is what the item's fields hold now, `None` for an item not created yet. `keys`
9691    /// narrows the work to the entries projecting one of those metadata keys, for a write that
9692    /// touches only them; `None` is every entry. A string the field already holds, and nothing
9693    /// for a field holding nothing, sends nothing. A value no text field can hold is refused,
9694    /// and so is a board without the field, or with a field of that name that is not a text
9695    /// field: reads and writes never create a field.
9696    fn projection_writes(
9697        &self,
9698        fields: &Value,
9699        held: Option<&BTreeMap<String, String>>,
9700        metadata: &BTreeMap<String, Value>,
9701        keys: Option<&[&str]>,
9702    ) -> Result<(Vec<ProjectionWrite>, BTreeMap<String, String>), SourceError> {
9703        let mut projected = held.cloned().unwrap_or_default();
9704        let mut writes = Vec::new();
9705        for projection in self
9706            .metadata_fields
9707            .iter()
9708            .filter(|projection| keys.is_none_or(|keys| keys.contains(&&*projection.key)))
9709        {
9710            let wanted = projection.projected(metadata, &self.name)?;
9711            let field = self.projection_field(fields, projection)?;
9712            let holding = projected.get(&*projection.field);
9713            match wanted {
9714                Projected::Text(text) if holding != Some(&text) => {
9715                    writes.push(ProjectionWrite::Set {
9716                        field,
9717                        text: text.clone(),
9718                    });
9719                    projected.insert(projection.field.to_string(), text);
9720                }
9721                Projected::Nothing if holding.is_some() => {
9722                    writes.push(ProjectionWrite::Clear { field });
9723                    projected.remove(&*projection.field);
9724                }
9725                Projected::Text(_) | Projected::Nothing => {}
9726            }
9727        }
9728        Ok((writes, projected))
9729    }
9730
9731    /// The id of the board text field one projection writes, or the refusal naming what the
9732    /// board has instead.
9733    fn projection_field(
9734        &self,
9735        fields: &Value,
9736        projection: &MetadataField,
9737    ) -> Result<String, SourceError> {
9738        let refuse = |detail: String| SourceError::Refused {
9739            message: format!(
9740                "source {} projects metadata key {:?} onto the board text field {:?}, and \
9741                 {detail}; next: run `onetaskgraph sources fields {} --apply` to create it as a \
9742                 text field, or name another field in metadata_fields",
9743                self.name, &*projection.key, &*projection.field, self.name
9744            ),
9745        };
9746        let Some(field) = Board::field(fields, &projection.field)? else {
9747            return Err(refuse("this board has no field of that name".to_owned()));
9748        };
9749        let typename = optional_str(field, "__typename")?.unwrap_or("field of another type");
9750        let data_type = optional_str(field, "dataType")?;
9751        if typename != "ProjectV2Field" || data_type != Some("TEXT") {
9752            return Err(refuse(format!(
9753                "this board's field of that name is not a text field (it is a {}), so it is \
9754                 left as it is; rename or remove that field first",
9755                data_type.unwrap_or(typename)
9756            )));
9757        }
9758        Ok(required_str(field, "id")?.to_owned())
9759    }
9760
9761    /// Apply one priority write to one board item.
9762    async fn write_priority(
9763        &self,
9764        board_id: &str,
9765        item_id: &str,
9766        write: &PriorityWrite,
9767    ) -> Result<(), SourceError> {
9768        match write {
9769            PriorityWrite::Select { field, option } => {
9770                self.set_item_field(
9771                    board_id,
9772                    item_id,
9773                    field,
9774                    json!({"singleSelectOptionId": option}),
9775                )
9776                .await
9777            }
9778            PriorityWrite::Clear { field } => {
9779                let data = self
9780                    .graphql(
9781                        graphql::CLEAR_FIELD,
9782                        json!({"input":{"projectId":board_id,"itemId":item_id,"fieldId":field},
9783                            "readPriority":false,"priorityName":PRIORITY_FIELD}),
9784                    )
9785                    .await?;
9786                let returned = data
9787                    .pointer("/clearProjectV2ItemFieldValue/projectV2Item")
9788                    .ok_or_else(|| SourceError::Malformed {
9789                        message: "GitHub field clear returned no project item".into(),
9790                    })?;
9791                if required_str(returned, "id")? != item_id {
9792                    return Err(SourceError::Malformed {
9793                        message: "GitHub field clear returned the wrong project item".into(),
9794                    });
9795                }
9796                Ok(())
9797            }
9798        }
9799    }
9800
9801    /// The refusal a priority is answered with by an instance configured with no
9802    /// `priority_mapping`, which holds none.
9803    fn holds_no_priority(&self) -> SourceError {
9804        SourceError::Refused {
9805            message: format!(
9806                "source {} holds no task priority: its configuration sets no priority_mapping; \
9807                 next: set priority_mapping on this source, then run `onetaskgraph sources \
9808                 fields {} --apply` to set its board up",
9809                self.name, self.name
9810            ),
9811        }
9812    }
9813
9814    /// Set one task's priority and nothing else; see [`TaskSource::set_task_priority`].
9815    ///
9816    /// One field write — a select, or a clear for `none` — and no title, body, label, state
9817    /// or `Status` request. Clearing a priority an item does not hold sends nothing.
9818    async fn set_priority(
9819        &self,
9820        id: &NativeId,
9821        priority: Priority,
9822    ) -> Result<Option<Priority>, SourceError> {
9823        if self.priorities.is_none() {
9824            return Err(self.holds_no_priority());
9825        }
9826        let Some(mut item) = self
9827            .bound_item(id)
9828            .await?
9829            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9830        else {
9831            return Ok(None);
9832        };
9833        if priority == Priority::None && !item.holds_priority() {
9834            return Ok(Some(priority));
9835        }
9836        // The item's own read carries the field's definition whenever it holds a value of
9837        // it, which a clear always does; a select onto an item holding none reads the board.
9838        let board = match (item.carried_board(), item.named_board()) {
9839            (Some(board), _) => board,
9840            (None, Some(id)) if item.defines(PRIORITY_FIELD) => BoardFields {
9841                id,
9842                fields: json!({"nodes": item.fields.clone(), "pageInfo": {"hasNextPage": false}}),
9843            },
9844            _ => self.board_fields().await?,
9845        };
9846        let Some(write) = self.priority_write(&board.fields, Some(&item), priority)? else {
9847            return Ok(Some(priority));
9848        };
9849        let (document, root, input) = match write {
9850            PriorityWrite::Select { field, option } => (
9851                graphql::UPDATE_FIELD,
9852                "updateProjectV2ItemFieldValue",
9853                json!({"projectId":board.id.as_str(),"itemId":item.item_id,"fieldId":field,"value":{"singleSelectOptionId":option}}),
9854            ),
9855            PriorityWrite::Clear { field } => (
9856                graphql::CLEAR_FIELD,
9857                "clearProjectV2ItemFieldValue",
9858                json!({"projectId":board.id.as_str(),"itemId":item.item_id,"fieldId":field}),
9859            ),
9860        };
9861        let data = self
9862            .graphql(
9863                document,
9864                json!({"input":input,"readPriority":true,"priorityName":PRIORITY_FIELD}),
9865            )
9866            .await?;
9867        let returned = data
9868            .get(root)
9869            .and_then(|value| value.get("projectV2Item"))
9870            .ok_or_else(|| SourceError::Malformed {
9871                message: "GitHub priority write returned no project item".into(),
9872            })?;
9873        if required_str(returned, "id")? != item.item_id {
9874            return Err(SourceError::Malformed {
9875                message: "GitHub priority write returned the wrong project item".into(),
9876            });
9877        }
9878        let value = returned
9879            .get("fieldValueByName")
9880            .ok_or_else(|| SourceError::Malformed {
9881                message: "GitHub priority write returned no priority read-back".into(),
9882            })?;
9883        if !value.is_null()
9884            && value.pointer("/field/name").and_then(Value::as_str) != Some(PRIORITY_FIELD)
9885        {
9886            return Err(SourceError::Malformed {
9887                message: "GitHub priority read-back is not a Priority field value".into(),
9888            });
9889        }
9890        let values = if value.is_null() {
9891            Vec::new()
9892        } else {
9893            vec![value.clone()]
9894        };
9895        item.priority = self.held_priority(&values)?;
9896        let answer = item.task()?.priority;
9897        self.remember_written(item, false)?;
9898        Ok(Some(answer))
9899    }
9900
9901    /// Replace one task's visible body and nothing else; see
9902    /// [`TaskSource::set_task_content`].
9903    ///
9904    /// One update of the body, which differs from the body GitHub holds only outside the
9905    /// metadata slot — the slot is kept byte for byte, so every caller key and every list
9906    /// this source keeps there reads back as it was. A body that would not change is not
9907    /// sent at all.
9908    async fn replace_content(
9909        &self,
9910        id: &NativeId,
9911        content: &str,
9912    ) -> Result<Option<()>, SourceError> {
9913        let Some(mut item) = self
9914            .bound_item(id)
9915            .await?
9916            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9917        else {
9918            return Ok(None);
9919        };
9920        let held = item.raw_body.clone().unwrap_or_default();
9921        // The task's `## Links` section, re-rendered from the links it holds, stays with it.
9922        let content = &onetaskgraph_plugin_api::relinked(content, item.body.as_deref(), &item.slot);
9923        let body = with_content(&held, &self.marked(content))?;
9924        // Checked before anything is sent: content ending in what this source reads as its own
9925        // metadata slot would read back as metadata rather than as the content it was.
9926        let (visible, slot) = self.visible(Some(body.clone()))?;
9927        if visible.as_deref().unwrap_or_default() != content || slot != item.slot {
9928            return Err(SourceError::Refused {
9929                message: format!(
9930                    "this content ends in what source {} reads as its own metadata slot \
9931                     ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
9932                     as content; next: remove that trailing block from the content",
9933                    self.name
9934                ),
9935            });
9936        }
9937        if body != held {
9938            self.update_content(item.content_kind, &item.id, json!({"body": body}))
9939                .await?;
9940        }
9941        item.body = visible.filter(|value| !value.is_empty());
9942        item.raw_body = Some(body);
9943        item.slot = slot;
9944        self.remember_written(item, false)?;
9945        Ok(Some(()))
9946    }
9947
9948    /// Apply one targeted update to one task; see [`TaskSource::update_task`].
9949    ///
9950    /// One read of the item — which carries the board's field definitions and the issue's
9951    /// `blockedBy`, so neither is read again — and then only what differs from it: the
9952    /// `Status` option and the `Priority` field together in one request, the `blockedBy`
9953    /// additions and removals the named edges differ by, and last one `updateIssue` carrying
9954    /// the title, the body — visible content and metadata slot together — and a state change.
9955    /// So an update naming any of title, body, metadata, status and priority is one read and
9956    /// at most two writes. The body goes last so that a write refused part-way leaves it, and
9957    /// the metadata in it, as it stood. A terminal status selects its option and then closes,
9958    /// as a whole write does; an open one selects its option and then reopens. The origin
9959    /// field is never written: an update is of an item that already exists, whose origin is
9960    /// what it is.
9961    ///
9962    /// The task answered is the item as those writes left it, built from the read and what was
9963    /// sent rather than read again — the same record a later read in this run answers from.
9964    ///
9965    /// Its `version` is the one the task holds after the writes: the change token the last
9966    /// mutation's own response spells — each sent as the twin selecting the whole issue, at
9967    /// the price of the plain document — or, where that mutation shows no whole issue (several
9968    /// board fields written together, or `blockedBy` alone), the token one read right after
9969    /// the writes spells. Never the token the item was read at before them. Against GitHub
9970    /// itself that token has not settled yet (`change_token::SETTLED`), so a read gives none
9971    /// until it has, and a write held to it before then is refused rather than let through;
9972    /// once settled, a read gives exactly this token unless the task changed again.
9973    async fn targeted_update(
9974        &self,
9975        id: &NativeId,
9976        update: &TaskUpdate,
9977    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
9978        Box::pin(SPELLING.scope(
9979            std::ptr::from_ref(self) as usize,
9980            self.composed_update(id, update),
9981        ))
9982        .await
9983    }
9984
9985    /// [`Self::targeted_update`], inside the scope that has its mutations answer whole.
9986    async fn composed_update(
9987        &self,
9988        id: &NativeId,
9989        update: &TaskUpdate,
9990    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
9991        // Everything this source can refuse without reading the item is refused first, in the
9992        // words a whole write of the same fields is refused with.
9993        update.consistent()?;
9994        // A duplicate close is the `cancelled` it implies where it names no status.
9995        let closing = update.duplicate_of.as_ref().map(|_| TaskUpdate {
9996            status: update.effective_status(),
9997            ..update.clone()
9998        });
9999        let update = closing.as_ref().unwrap_or(update);
10000        if update.assignees.is_some() && !self.assignees {
10001            return Err(onetaskgraph_plugin_api::unwritable_field(KIND, "assignees"));
10002        }
10003        if update
10004            .title
10005            .as_deref()
10006            .is_some_and(|title| title.starts_with(DESIGN_TITLE_PREFIX))
10007        {
10008            return Err(SourceError::Refused {
10009                message: format!(
10010                    "the title of this task begins {DESIGN_TITLE_PREFIX:?}, which is how source {} \
10011                     spells a document, so it would read back as one rather than as a task; \
10012                     retitle it",
10013                    self.name
10014                ),
10015            });
10016        }
10017        if let Some(delivers) = &update.delivers {
10018            TaskRef::listed(
10019                TaskRef::DELIVERS_KEY,
10020                id,
10021                Some(&self.name),
10022                delivers.clone(),
10023            )
10024            .map_err(|message| SourceError::Refused { message })?;
10025        }
10026        if self.priorities.is_none()
10027            && update
10028                .priority
10029                .is_some_and(|priority| priority != Priority::None)
10030        {
10031            return Err(self.holds_no_priority());
10032        }
10033        let target = update
10034            .status
10035            .as_ref()
10036            .map(|status| self.resolved_target(ItemKind::Task, status.category))
10037            .transpose()?;
10038        let Some(mut item) = self
10039            .bound_item(id)
10040            .await?
10041            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
10042        else {
10043            return Ok(None);
10044        };
10045        let before = item.task()?;
10046        // The issue a duplicate close names as its survivor, refused naming both before anything
10047        // is written when it is not an issue of this board's own.
10048        let survivor = match &update.duplicate_of {
10049            Some(survivor) => Some(self.duplicate_survivor(id, &item, survivor).await?),
10050            None => None,
10051        };
10052        // The people it is to be assigned to, by node id, when they are not exactly whom it
10053        // holds: looked up — unless this process already has — and refused for a login GitHub
10054        // does not know, before anything is sent.
10055        let assignee_ids = match &update.assignees {
10056            Some(people)
10057                if item
10058                    .assignees
10059                    .as_deref()
10060                    .is_none_or(|held| !assignees::same_people(held, people)) =>
10061            {
10062                if item.content_kind == ContentKind::DraftIssue {
10063                    return Err(self.assigns_a_draft());
10064                }
10065                self.resolve_people(people).await?;
10066                Some(self.people_ids(people, &item.written_name())?)
10067            }
10068            _ => None,
10069        };
10070
10071        let mut status_move = None;
10072        if let (Some(status), Some(target)) = (&update.status, target) {
10073            let board = self.status_board(&item).await?;
10074            let (field, option, name) = self
10075                .column_for(&board.fields, ItemKind::Task, status.category, &target)?
10076                .ok_or_else(|| SourceError::Malformed {
10077                    message: format!(
10078                        "status {} of source {} names no board Status option",
10079                        category_name(status.category),
10080                        self.name
10081                    ),
10082                })?;
10083            let terminal = matches!(target, StatusTarget::Terminal(_, _));
10084            if terminal && item.content_kind == ContentKind::DraftIssue {
10085                return Err(self.closes_a_draft(status.category));
10086            }
10087            // A duplicate close lands closed as `DUPLICATE`, which reads `cancelled` as not
10088            // planned does; an issue already closed as one is not closed again.
10089            let reason = match (&target, &survivor) {
10090                (StatusTarget::Terminal(_, _), Some(_)) => Some(DUPLICATE_REASON),
10091                (StatusTarget::Terminal(_, reason), None) => Some(reason.reason()),
10092                _ => None,
10093            };
10094            let landed = self
10095                .statuses
10096                .status(ItemKind::Task, Some(&name), terminal, reason);
10097            let option_moves = item
10098                .option
10099                .as_deref()
10100                .is_none_or(|held| !held.eq_ignore_ascii_case(&name));
10101            let state_moves = item.content_kind == ContentKind::Issue
10102                && (item.closed != terminal
10103                    || (terminal && item.status != landed)
10104                    || (survivor.is_some() && item.reason.as_deref() != Some(DUPLICATE_REASON)));
10105            if let Some(moves) = Moves::of(option_moves, state_moves) {
10106                status_move = Some(StatusMove {
10107                    board: board.id,
10108                    field,
10109                    option,
10110                    name,
10111                    target,
10112                    landed,
10113                    moves,
10114                });
10115            }
10116        }
10117
10118        let mut priority_move = None;
10119        if let Some(priority) = update.priority
10120            && self.priorities.is_some()
10121            && item.priority != HeldPriority::Read(priority)
10122        {
10123            let board = match (item.carried_board(), item.named_board()) {
10124                (Some(board), _) => board,
10125                (None, Some(board)) if item.defines(PRIORITY_FIELD) => BoardFields {
10126                    id: board,
10127                    fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
10128                },
10129                _ => self.board_fields().await?,
10130            };
10131            if let Some(write) = self.priority_write(&board.fields, Some(&item), priority)? {
10132                priority_move = Some((board.id, write, priority));
10133            }
10134        }
10135
10136        // The metadata keys this update names that a board text field projects, and what
10137        // that does to those fields — refused, as a whole write refuses it, before anything
10138        // is sent.
10139        let touched: Vec<&str> = update
10140            .metadata_set
10141            .keys()
10142            .chain(update.metadata_remove.iter())
10143            .map(MetadataKey::as_str)
10144            .collect();
10145        let mut projection_move = None;
10146        if self
10147            .metadata_fields
10148            .iter()
10149            .any(|projection| touched.contains(&&*projection.key))
10150        {
10151            let mut metadata = item.slot.clone();
10152            for (key, value) in &update.metadata_set {
10153                metadata.insert(key.as_str().to_owned(), value.clone());
10154            }
10155            for key in &update.metadata_remove {
10156                metadata.remove(key.as_str());
10157            }
10158            let board = self.projection_board(&item).await?;
10159            let (writes, projected) = self.projection_writes(
10160                &board.fields,
10161                Some(&item.projected),
10162                &metadata,
10163                Some(&touched),
10164            )?;
10165            projection_move = Some((board.id, writes, projected));
10166        }
10167
10168        // Resolved before the body is composed, because a far end `blockedBy` cannot name is
10169        // recorded in the slot, and the slot travels in the one body update below.
10170        let edges = match &update.depends_on {
10171            Some(edges) => Some(
10172                self.partition_edges(
10173                    BoardKind::Work(ItemKind::Task),
10174                    item.content_kind,
10175                    item.blocked_by.as_deref(),
10176                    edges,
10177                )
10178                .await?,
10179            ),
10180            None => None,
10181        };
10182
10183        // A record primed from what a producer wrote holds no body anybody read, so an update
10184        // changing the body reads it first: by the `Status` write's own answer when the update
10185        // moves the option — the mutation answering with the issue whole — and otherwise by
10186        // reading the issue. The body is then composed against what GitHub holds now.
10187        let mut option_selected = false;
10188        // The mark stays until a read lands, so an update that writes no body, or one whose
10189        // read fails, leaves the next update of it to read the body too.
10190        if (update.content.is_some()
10191            || !update.metadata_set.is_empty()
10192            || !update.metadata_remove.is_empty()
10193            || update.delivers.is_some()
10194            || update.repositories.is_some()
10195            || edges.is_some())
10196            && self.is_unread(id)
10197        {
10198            let live = match status_move.as_ref().filter(|moving| moving.moves.option()) {
10199                Some(moving) => {
10200                    option_selected = true;
10201                    Some(
10202                        self.select_reading_body(
10203                            moving.board.as_str(),
10204                            &item.item_id,
10205                            &moving.field,
10206                            &moving.option,
10207                        )
10208                        .await?,
10209                    )
10210                }
10211                None => {
10212                    self.forget(id)?;
10213                    let Some(read) = self.item_by_id(id).await? else {
10214                        return Ok(None);
10215                    };
10216                    read.raw_body
10217                }
10218            };
10219            let (visible, read_slot) = self.visible(live.clone())?;
10220            self.mark_read(id);
10221            item.raw_body = live;
10222            item.body = visible;
10223            item.slot = read_slot;
10224        }
10225
10226        let mut slot = item.slot.clone();
10227        for (key, value) in &update.metadata_set {
10228            slot.insert(key.as_str().to_owned(), value.clone());
10229        }
10230        for key in &update.metadata_remove {
10231            slot.remove(key.as_str());
10232        }
10233        if let Some(delivers) = &update.delivers {
10234            set_task_list(&mut slot, TaskRef::DELIVERS_KEY, delivers);
10235        }
10236        // The list a whole write records, by the same rule: none when it is exactly the issue's
10237        // own repository, or empty with no issue repository to derive, and otherwise the list.
10238        if let Some(repositories) = &update.repositories {
10239            let derivable = item
10240                .own_repository
10241                .as_ref()
10242                .map_or(repositories.is_empty(), |own| {
10243                    repositories.as_slice() == std::slice::from_ref(own)
10244                });
10245            if derivable {
10246                slot.remove(Repository::METADATA_KEY);
10247            } else {
10248                slot.insert(
10249                    Repository::METADATA_KEY.to_owned(),
10250                    Value::Array(
10251                        repositories
10252                            .iter()
10253                            .map(|repository| Value::String(repository.as_str().to_owned()))
10254                            .collect(),
10255                    ),
10256                );
10257            }
10258        }
10259        if let Some((_, recorded)) = &edges {
10260            record_edges(&mut slot, recorded);
10261        }
10262        let held = item.raw_body.clone().unwrap_or_default();
10263        // A content write keeps the task's `## Links` section, re-rendered from the links the
10264        // slot holds once written.
10265        let relinked = update
10266            .content
10267            .as_deref()
10268            .map(|content| onetaskgraph_plugin_api::relinked(content, item.body.as_deref(), &slot));
10269        let content = match &relinked {
10270            Some(content) => with_content(&held, &self.marked(content))?,
10271            None => held.clone(),
10272        };
10273        // A slot holding what it held is kept byte for byte, compared as JSON rather than as
10274        // the body's bytes, as a metadata write compares it: a slot a person spelled with
10275        // other whitespace would otherwise be re-encoded, which is a write nobody asked for.
10276        let body = if slot == item.slot {
10277            content
10278        } else {
10279            with_slot(&content, &slot)?
10280        };
10281        // Checked before anything is sent, as a content write checks it: content ending in
10282        // what this source reads as its own slot would read back as metadata.
10283        let (visible, read) = self.visible(Some(body.clone()))?;
10284        let wanted = relinked.as_deref().or(item.body.as_deref());
10285        if visible.as_deref().unwrap_or_default() != wanted.unwrap_or_default() || read != slot {
10286            return Err(SourceError::Refused {
10287                message: format!(
10288                    "this content ends in what source {} reads as its own metadata slot \
10289                     ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
10290                     as content; next: remove that trailing block from the content",
10291                    self.name
10292                ),
10293            });
10294        }
10295        let recorded_moves =
10296            slot.get(DependencyEdge::RECORDED_KEY) != item.slot.get(DependencyEdge::RECORDED_KEY);
10297
10298        // One `updateIssue` carries all three, because every mutation spends the secondary
10299        // limiter and the title, body and state are one mutation's inputs.
10300        let mut fields = serde_json::Map::new();
10301        if let Some(title) = update.title.as_ref().filter(|title| **title != item.title) {
10302            fields.insert("title".to_owned(), json!(title));
10303        }
10304        if body != held {
10305            fields.insert("body".to_owned(), json!(body));
10306        }
10307        // A duplicate's closure is `closeIssue`'s, sent after this update: `stateInput` names
10308        // no survivor.
10309        if let Some(moving) = status_move
10310            .as_ref()
10311            .filter(|moving| moving.moves.state() && survivor.is_none())
10312        {
10313            fields.insert("stateInput".to_owned(), state_input(Some(&moving.target)));
10314        }
10315        let closes_as_duplicate = status_move
10316            .as_ref()
10317            .is_some_and(|moving| moving.moves.state())
10318            && survivor.is_some();
10319        // The assignees ride the same mutation: replacing whoever the issue holds, in the one
10320        // `updateIssue` this update already ends with — or as the one it sends for them alone.
10321        if let Some(ids) = &assignee_ids {
10322            fields.insert("assigneeIds".to_owned(), json!(ids));
10323        }
10324        // **The body is written last, and that is the guarantee a refusal part-way keeps.**
10325        // GitHub runs no two requests as one, and runs one document's mutation fields in order
10326        // without undoing an earlier field when a later one fails — so a body written before a
10327        // board field the board then refused would be left changed. Written after every other
10328        // write has landed, a refusal anywhere leaves the item's body, and every metadata key
10329        // it carries, exactly as they stood. So the `Status` option and the `Priority` field go
10330        // first, together in one request — a terminal option selected before the issue
10331        // closes, as a whole write does — then the `blockedBy` difference, then the body.
10332        let mut board_writes: Vec<(&BoardId, (String, Value))> = Vec::new();
10333        let mut clears: Vec<(&BoardId, &str)> = Vec::new();
10334        if let Some(moving) = status_move
10335            .as_ref()
10336            .filter(|moving| moving.moves.option() && !option_selected)
10337        {
10338            board_writes.push((
10339                &moving.board,
10340                (
10341                    moving.field.clone(),
10342                    json!({"singleSelectOptionId": moving.option}),
10343                ),
10344            ));
10345        }
10346        match &priority_move {
10347            Some((board, PriorityWrite::Select { field, option }, _)) => board_writes.push((
10348                board,
10349                (field.clone(), json!({"singleSelectOptionId": option})),
10350            )),
10351            Some((board, PriorityWrite::Clear { field }, _)) => clears.push((board, field)),
10352            None => {}
10353        }
10354        if let Some((board, writes, _)) = &projection_move {
10355            for write in writes {
10356                let (mut values, mut cleared) = (Vec::new(), Vec::new());
10357                write.join(&mut values, &mut cleared);
10358                board_writes.extend(values.into_iter().map(|value| (board, value)));
10359                clears.extend(cleared.into_iter().map(|field| (board, field)));
10360            }
10361        }
10362        let mut boards: Vec<&BoardId> = board_writes.iter().map(|(board, _)| *board).collect();
10363        boards.extend(clears.iter().map(|(board, _)| *board));
10364        boards.dedup_by(|one, other| one.as_str() == other.as_str());
10365        for board in boards {
10366            let writes = board_writes
10367                .iter()
10368                .filter(|(on, _)| on.as_str() == board.as_str())
10369                .map(|(_, write)| write.clone())
10370                .collect::<Vec<_>>();
10371            let cleared = clears
10372                .iter()
10373                .filter(|(on, _)| on.as_str() == board.as_str())
10374                .map(|(_, field)| *field)
10375                .collect::<Vec<_>>();
10376            self.set_item_fields(board.as_str(), &item.item_id, &writes, &cleared)
10377                .await?;
10378        }
10379        // Whether anything is sent: what the version answered has to come after.
10380        let sends = option_selected
10381            || !board_writes.is_empty()
10382            || !clears.is_empty()
10383            || !fields.is_empty()
10384            || closes_as_duplicate;
10385        let mut blocked_by_moved = false;
10386        if let Some((native, _)) = &edges
10387            && item.content_kind == ContentKind::Issue
10388        {
10389            blocked_by_moved = self
10390                .reconcile_blocked_by(
10391                    &item.id,
10392                    native,
10393                    Issue::Existing(item.blocked_by.as_deref()),
10394                )
10395                .await?;
10396        }
10397        if !fields.is_empty() {
10398            self.update_content(item.content_kind, &item.id, Value::Object(fields))
10399                .await?;
10400        }
10401        // Last, the duplicate's closure, with the survivor GitHub links it to: the card already
10402        // shows the `cancelled` option, so a refusal here leaves an open issue at a terminal
10403        // card, which the next write of the same status closes.
10404        if let (true, Some(survivor)) = (closes_as_duplicate, &survivor) {
10405            self.graphql(
10406                graphql::CLOSE_ISSUE,
10407                json!({"input":{"issueId":item.id.0,"stateReason":DUPLICATE_REASON,
10408                                "duplicateIssueId":survivor.0}}),
10409            )
10410            .await?;
10411        }
10412
10413        // The `blockedBy` this item was read with is what the write just changed, so it is no
10414        // answer any more: a later write in this command would reconcile against it — re-adding
10415        // what it kept and never removing what it dropped — and a forward-edge read would
10416        // answer with it. Left unknown, each asks GitHub instead.
10417        if blocked_by_moved {
10418            item.blocked_by = None;
10419        }
10420        if let Some(title) = &update.title {
10421            item.title.clone_from(title);
10422        }
10423        item.body = visible.filter(|value| !value.is_empty());
10424        item.raw_body = (!body.is_empty() || item.raw_body.is_some()).then_some(body);
10425        item.slot = slot;
10426        if let Some(delivers) = &update.delivers {
10427            item.delivers.clone_from(delivers);
10428        }
10429        if let Some(repositories) = &update.repositories {
10430            item.repositories.clone_from(repositories);
10431        }
10432        if let Some(moving) = status_move {
10433            item.closed = matches!(moving.target, StatusTarget::Terminal(_, _))
10434                && item.content_kind == ContentKind::Issue;
10435            if moving.moves.state() {
10436                item.reason = match &moving.target {
10437                    StatusTarget::Terminal(_, _) if survivor.is_some() => {
10438                        Some(DUPLICATE_REASON.to_owned())
10439                    }
10440                    StatusTarget::Terminal(_, reason) => Some(reason.reason().to_owned()),
10441                    _ => None,
10442                };
10443            }
10444            item.status = moving.landed;
10445            item.option = Some(moving.name);
10446        }
10447        if let Some((_, _, priority)) = priority_move {
10448            item.priority = HeldPriority::Read(priority);
10449        }
10450        if let Some((_, _, projected)) = projection_move {
10451            item.projected = projected;
10452        }
10453        // Only a write that assigned anyone moves whom the item holds, and they are who GitHub
10454        // says they are; one naming the people it already holds leaves its read as it was.
10455        if let (Some(people), Some(_)) = (&update.assignees, &assignee_ids) {
10456            item.assignees = Some(self.spelled(people));
10457        }
10458        let mut task = item.task()?;
10459        let mut written = update.changed(&before, &task);
10460        if blocked_by_moved || recorded_moves {
10461            written.insert(UpdatedField::DependsOn);
10462        }
10463        if closes_as_duplicate {
10464            written.insert(UpdatedField::DuplicateOf);
10465        }
10466        if sends || blocked_by_moved {
10467            // The token the item was read at is not the one it holds now. A batch of updates
10468            // holding this one's writes back reads every task it wrote once they are sent.
10469            task.version = if self.holding_writes_of(id) {
10470                None
10471            } else {
10472                self.version_after_write(id).await
10473            };
10474        }
10475        self.remember_written(item, false)?;
10476        Ok(Some(TaskUpdateOutcome {
10477            task,
10478            written,
10479            delivers_before: before.delivers,
10480        }))
10481    }
10482
10483    /// The issue `survivor` names, the one a duplicate close of `id` links GitHub's closure to:
10484    /// refused, naming both, when it is not an issue of this board's own source — a task of
10485    /// another source, a board draft, an item this board does not hold — or is `id` itself.
10486    async fn duplicate_survivor(
10487        &self,
10488        id: &NativeId,
10489        item: &Resolved,
10490        survivor: &TaskRef,
10491    ) -> Result<NativeId, SourceError> {
10492        let refused = |why: String| SourceError::Refused {
10493            message: format!(
10494                "{} cannot be closed as a duplicate of {survivor}: {why}; next: name an issue of \
10495                 source {} as the survivor",
10496                TaskRef::qualified(&self.name, id),
10497                self.name
10498            ),
10499        };
10500        let (source, native) = survivor.parts(self.name.as_str());
10501        if source != self.name.as_str() {
10502            return Err(refused(format!(
10503                "it is not a GitHub issue of source {}, which GitHub links a duplicate to",
10504                self.name
10505            )));
10506        }
10507        let native = NativeId(native.to_owned());
10508        if native == *id || native == item.id {
10509            return Err(refused("a task cannot be a duplicate of itself".to_owned()));
10510        }
10511        match self.bound_item(&native).await? {
10512            Some(held) if held.content_kind == ContentKind::Issue => Ok(held.id),
10513            Some(_) => Err(refused(
10514                "it is a board draft, which is no issue GitHub can link a duplicate to".to_owned(),
10515            )),
10516            None => Err(refused(format!("source {} holds no such issue", self.name))),
10517        }
10518    }
10519
10520    /// The change token the task `id` holds after the writes a targeted update just sent: the
10521    /// one the last mutation's own response showed, or, where none showed the whole issue, the
10522    /// one a read made now spells. `None` when that read cannot say — never the token the
10523    /// task was read at before the writes.
10524    async fn version_after_write(&self, id: &NativeId) -> Option<String> {
10525        // A response that showed the issue whole answers, a token or none: a read made now
10526        // would read the same parts.
10527        if let Some(answered) = self.written_answer(id) {
10528            return answered;
10529        }
10530        // An item this command created is answered from its own record, not read.
10531        if self.created().ok()?.iter().any(|own| own.id == *id) {
10532            return None;
10533        }
10534        let read = self.item_by_id(id).await.ok()??;
10535        let token = read.written_version()?;
10536        self.remember_written_token(&read, token.clone());
10537        Some(token)
10538    }
10539
10540    /// Replace one issue's visible body and its [`MetadataKey::TEMPLATE_KEY`] slot entry
10541    /// together, and nothing else; see [`TaskSource::set_task_rendering`].
10542    ///
10543    /// One update of the body: the content outside the slot, and inside it that one entry,
10544    /// every other entry kept as it was. This source keeps no template answers — an issue has
10545    /// no room beside itself that is not its body, and answers written there would duplicate
10546    /// what the content already says and count against GitHub's body limit — so `answers`
10547    /// reaches nothing here. A body that would not change is not sent at all.
10548    async fn replace_rendering(
10549        &self,
10550        id: &NativeId,
10551        kind: BoardKind,
10552        content: &str,
10553        provenance: &Value,
10554        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
10555    ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
10556        let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
10557            return Ok(None);
10558        };
10559        let held = item.raw_body.clone().unwrap_or_default();
10560        let mut slot = item.slot.clone();
10561        slot.insert(MetadataKey::TEMPLATE_KEY.to_owned(), provenance.clone());
10562        let rewritten;
10563        let content = if let Some(assets) = assets {
10564            let uploads = self
10565                .upload_assets(item.own_repository.as_ref(), assets)
10566                .await?;
10567            rewritten =
10568                onetaskgraph_plugin_api::serve_asset_references(content, &mut slot, &uploads);
10569            rewritten.as_str()
10570        } else {
10571            content
10572        };
10573        let relinked = onetaskgraph_plugin_api::relinked(content, item.body.as_deref(), &slot);
10574        let content = relinked.as_str();
10575        let body = with_slot(&with_content(&held, &self.marked(content))?, &slot)?;
10576        // Checked before anything is sent, as a content write checks it.
10577        let (visible, read) = self.visible(Some(body.clone()))?;
10578        if visible.as_deref().unwrap_or_default() != content || read != slot {
10579            return Err(SourceError::Refused {
10580                message: format!(
10581                    "this content ends in what source {} reads as its own metadata slot \
10582                     ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
10583                     as content; next: remove that trailing block from the template",
10584                    self.name
10585                ),
10586            });
10587        }
10588        if body != held {
10589            self.update_content(item.content_kind, &item.id, json!({"body": body}))
10590                .await?;
10591        }
10592        item.body = visible.filter(|value| !value.is_empty());
10593        item.raw_body = Some(body);
10594        // The content as a read answers it: without the `## Links` section of a linked task.
10595        let answered = onetaskgraph_plugin_api::read_content(Some(content.to_owned()), &read);
10596        item.slot = read;
10597        self.remember_written(item, false)?;
10598        Ok(Some(onetaskgraph_plugin_api::AssetsWritten {
10599            id: id.clone(),
10600            content: answered,
10601        }))
10602    }
10603
10604    async fn set_item_field(
10605        &self,
10606        board_id: &str,
10607        item_id: &str,
10608        field_id: &str,
10609        value: Value,
10610    ) -> Result<(), SourceError> {
10611        let data = self
10612            .graphql(
10613                graphql::UPDATE_FIELD,
10614                json!({"input":{
10615                    "projectId":board_id,"itemId":item_id,"fieldId":field_id,"value":value
10616                },"readPriority":false,"priorityName":PRIORITY_FIELD}),
10617            )
10618            .await?;
10619        field_update_item(&data, item_id).map(|_| ())
10620    }
10621
10622    /// GitHub accepts one value per field mutation; aliases combine those mutations in
10623    /// one request — writes in the order given, then clears. A lone write is
10624    /// [`graphql::UPDATE_FIELD`] and a lone clear [`graphql::CLEAR_FIELD`]; more than one
10625    /// request's slots hold go in further requests of the same document, in order. Every
10626    /// returned item id is checked, including optional aliases.
10627    async fn set_item_fields(
10628        &self,
10629        board: &str,
10630        item: &str,
10631        fields: &[(String, Value)],
10632        clears: &[&str],
10633    ) -> Result<(), SourceError> {
10634        if !(fields.is_empty() && clears.is_empty())
10635            && self.hold_fields(board, item, fields, clears)?
10636        {
10637            return Ok(());
10638        }
10639        match (fields, clears) {
10640            ([], []) => return Ok(()),
10641            ([(field, value)], []) => {
10642                return self.set_item_field(board, item, field, value.clone()).await;
10643            }
10644            ([], [field]) => {
10645                return self
10646                    .write_priority(
10647                        board,
10648                        item,
10649                        &PriorityWrite::Clear {
10650                            field: (*field).to_owned(),
10651                        },
10652                    )
10653                    .await;
10654            }
10655            _ => {}
10656        }
10657        // Any field of the request stands in for an input a slot leaves out, which GitHub
10658        // still requires to be well formed although it never runs it.
10659        let filler = fields
10660            .first()
10661            .map_or_else(|| clears[0], |(field, _)| field.as_str());
10662        let mut writes = fields.iter();
10663        let mut cleared = clears.iter();
10664        loop {
10665            let batch: Vec<&(String, Value)> =
10666                writes.by_ref().take(FIELD_WRITE_SLOTS.len()).collect();
10667            let batch_clears: Vec<&&str> = cleared.by_ref().take(FIELD_CLEAR_SLOTS.len()).collect();
10668            if batch.is_empty() && batch_clears.is_empty() {
10669                return Ok(());
10670            }
10671            let mut variables = serde_json::Map::new();
10672            for (index, slot) in FIELD_WRITE_SLOTS.iter().enumerate() {
10673                let input = match batch.get(index) {
10674                    Some((field, value)) => {
10675                        json!({"projectId":board,"itemId":item,"fieldId":field,"value":value})
10676                    }
10677                    None => json!({"projectId":board,"itemId":item,"fieldId":filler,
10678                                   "value":{"text":""}}),
10679                };
10680                variables.insert(slot.variable.to_owned(), input);
10681                variables.insert(slot.include.to_owned(), json!(index < batch.len()));
10682            }
10683            for (index, slot) in FIELD_CLEAR_SLOTS.iter().enumerate() {
10684                let field = batch_clears.get(index).map_or(filler, |field| **field);
10685                variables.insert(
10686                    slot.variable.to_owned(),
10687                    json!({"projectId":board,"itemId":item,"fieldId":field}),
10688                );
10689                variables.insert(slot.include.to_owned(), json!(index < batch_clears.len()));
10690            }
10691            let data = self
10692                .graphql(graphql::UPDATE_FIELDS, Value::Object(variables))
10693                .await?;
10694            let sent = FIELD_WRITE_SLOTS[..batch.len()]
10695                .iter()
10696                .chain(&FIELD_CLEAR_SLOTS[..batch_clears.len()]);
10697            for slot in sent {
10698                let alias = slot.alias;
10699                let returned = data
10700                    .get(alias)
10701                    .and_then(|value| value.get("projectV2Item"))
10702                    .ok_or_else(|| SourceError::Malformed {
10703                        message: format!("GitHub field update {alias} returned no project item"),
10704                    })?;
10705                if required_str(returned, "id")? != item {
10706                    return Err(SourceError::Malformed {
10707                        message: format!(
10708                            "GitHub field update {alias} returned the wrong project item"
10709                        ),
10710                    });
10711                }
10712            }
10713        }
10714    }
10715
10716    async fn native_dependency_ids(&self, id: &NativeId) -> Result<Vec<String>, SourceError> {
10717        let mut after: Option<String> = None;
10718        let mut ids = Vec::new();
10719        loop {
10720            let data = self
10721                .graphql(
10722                    graphql::ISSUE_DEPENDENCIES,
10723                    json!({"id":id.0,"first":MAX_PAGE_SIZE,"after":after}),
10724                )
10725                .await?;
10726            let connection =
10727                data.pointer("/node/blockedBy")
10728                    .ok_or_else(|| SourceError::Malformed {
10729                        message: "GitHub dependency response has no blockedBy connection".into(),
10730                    })?;
10731            ids.extend(
10732                connection
10733                    .get("nodes")
10734                    .and_then(Value::as_array)
10735                    .ok_or_else(|| SourceError::Malformed {
10736                        message: "GitHub dependency response nodes is not an array".into(),
10737                    })?
10738                    .iter()
10739                    .map(|value| required_str(value, "id").map(str::to_owned))
10740                    .collect::<Result<Vec<_>, _>>()?,
10741            );
10742            let next = next_cursor(connection)?;
10743            if let Some(next) = &next {
10744                validate_cursor_progress(after.as_deref(), &next.0)?;
10745            }
10746            after = next.map(|cursor| cursor.0);
10747            if after.is_none() {
10748                return Ok(ids);
10749            }
10750        }
10751    }
10752
10753    async fn dependencies(
10754        &self,
10755        id: &NativeId,
10756        near_kind: ItemKind,
10757        direction: Direction,
10758        page: &PageRequest,
10759    ) -> Result<Page<DependencyEdge>, SourceError> {
10760        validate_page(page)?;
10761        let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
10762        let cursor = page.cursor.as_ref().map(|c| c.0.as_str());
10763        let recorded = recorded_offset(cursor, direction)?;
10764        // What this issue is blocked by, when a read of it by its own id in this command
10765        // already carried the whole connection — a copy reads the item it writes before it
10766        // reads its edges — and the page asked for is the whole of it, or the recorded tail
10767        // after it. Answered from that read, in the shape the dependency read answers in;
10768        // anything else is asked of GitHub.
10769        let carried = match direction {
10770            Direction::DependsOn => self
10771                .resolved_cache()?
10772                .get(id)
10773                .filter(|item| item.content_kind == ContentKind::Issue)
10774                .and_then(|item| Some((item.blocked_by.clone()?, item.raw_body.clone()))),
10775            Direction::DependedOnBy => None,
10776        }
10777        .filter(|(nodes, _)| recorded.is_some() || (cursor.is_none() && nodes.len() <= limit));
10778        // Asked for even in the recorded phase, whose page reads nothing from the
10779        // connection: `__typename` is what says whether this item has a native
10780        // relationship at all, and that is what decides which far ends the reserved key is
10781        // allowed to hold.
10782        let data = match carried {
10783            Some((nodes, body)) => json!({"node":{"__typename":"Issue","body":body,
10784                "blockedBy":{"nodes":nodes,"pageInfo":{"hasNextPage":false,"endCursor":null}}}}),
10785            None => {
10786                let after = if recorded.is_some() { None } else { cursor };
10787                let first = page.limit.min(MAX_PAGE_SIZE);
10788                match direction {
10789                    Direction::DependsOn => {
10790                        self.graphql(
10791                            graphql::ISSUE_DEPENDS_ON,
10792                            json!({"id":id.0,"first":first,"after":after,"owner":self.owner,
10793                                   "number":self.project_number,
10794                                   "boardItems":BOARD_ITEMS_PAGE_SIZE}),
10795                        )
10796                        .await?
10797                    }
10798                    Direction::DependedOnBy => {
10799                        self.graphql(
10800                            graphql::ISSUE_DEPENDED_ON_BY,
10801                            json!({"id":id.0,"first":first,"after":after}),
10802                        )
10803                        .await?
10804                    }
10805                }
10806            }
10807        };
10808        let draft_slot = draft_slot(&data, id, self.project_number)?;
10809        let node =
10810            data.get("node")
10811                .filter(|v| !v.is_null())
10812                .ok_or_else(|| SourceError::Refused {
10813                    message: format!(
10814                        "GitHub item {} was not found or does not support dependencies",
10815                        id.0
10816                    ),
10817                })?;
10818        let connection_name = match direction {
10819            Direction::DependsOn => "blockedBy",
10820            Direction::DependedOnBy => "blocking",
10821        };
10822        // A draft has neither `blockedBy` nor `blocking`, so nothing it depends on can be
10823        // named natively and the reserved key may hold any far end. An issue's connections
10824        // hold issues, and this source reads them at the near item's own level.
10825        let natively_names = (required_str(node, "__typename")? == "Issue").then_some(near_kind);
10826        if let Some(offset) = recorded {
10827            return Ok(recorded_page(
10828                self.recorded_edges(
10829                    id,
10830                    near_kind,
10831                    direction,
10832                    natively_names,
10833                    node,
10834                    draft_slot.as_ref(),
10835                )
10836                .await?,
10837                offset,
10838                limit,
10839            ));
10840        }
10841        if natively_names.is_none() {
10842            return Ok(recorded_page(
10843                self.recorded_edges(
10844                    id,
10845                    near_kind,
10846                    direction,
10847                    natively_names,
10848                    node,
10849                    draft_slot.as_ref(),
10850                )
10851                .await?,
10852                0,
10853                limit,
10854            ));
10855        }
10856        let connection = node
10857            .get(connection_name)
10858            .ok_or_else(|| SourceError::Malformed {
10859                message: "GitHub dependency response is missing its connection".into(),
10860            })?;
10861        let nodes = connection
10862            .get("nodes")
10863            .and_then(Value::as_array)
10864            .ok_or_else(|| SourceError::Malformed {
10865                message: "GitHub dependency response nodes is not an array".into(),
10866            })?;
10867        // `from` depends on `to`, always. GitHub spells the same relationship from either
10868        // end — `blockedBy` lists what this item waits on, `blocking` lists what waits on
10869        // it — so the near item is `from` in one direction and `to` in the other.
10870        let items = nodes
10871            .iter()
10872            .map(|value| {
10873                let related = NativeId(required_str(value, "id")?.into());
10874                let related_kind = related_kind(value, self.sub_issues)?;
10875                let (from, to) = match direction {
10876                    Direction::DependsOn => (
10877                        DependencyEndpoint::from_native(id.clone(), near_kind),
10878                        DependencyEndpoint::from_native(related, related_kind),
10879                    ),
10880                    Direction::DependedOnBy => (
10881                        DependencyEndpoint::from_native(related, related_kind),
10882                        DependencyEndpoint::from_native(id.clone(), near_kind),
10883                    ),
10884                };
10885                Ok(DependencyEdge {
10886                    from,
10887                    to,
10888                    kind: DependencyKind::Blocks,
10889                })
10890            })
10891            .collect::<Result<Vec<_>, SourceError>>()?;
10892        let mut next = next_cursor(connection)?;
10893        if let Some(next) = &next {
10894            validate_cursor_progress(cursor, &next.0)?;
10895        }
10896        // The recorded far ends ride on the last page of `blockedBy`, whose answer carried the
10897        // body they are recorded in, as far as the page has room — so they cost no request of
10898        // their own — and only what does not fit is resumed by a cursor.
10899        let mut items = items;
10900        if next.is_none() {
10901            let recorded = self
10902                .recorded_edges(
10903                    id,
10904                    near_kind,
10905                    direction,
10906                    natively_names,
10907                    node,
10908                    draft_slot.as_ref(),
10909                )
10910                .await?;
10911            let room = limit.saturating_sub(items.len());
10912            let total = recorded.len();
10913            items.extend(recorded.into_iter().take(room));
10914            if total > room {
10915                next = Some(Cursor(format!("{RECORDED_CURSOR}{room}")));
10916            }
10917        }
10918        Ok(Page { items, next })
10919    }
10920
10921    /// The edges this item records under [`DependencyEdge::RECORDED_KEY`], which is where
10922    /// a far end in another source has to live: no GitHub issue relationship can name one.
10923    ///
10924    /// Only forwards. The reverse of a recorded edge is derived from the far end, and this
10925    /// source never writes one down.
10926    ///
10927    /// The metadata lives in the item's own body slot, and `node` is the dependency read's
10928    /// own answer, which carries an issue's body — so an issue's recorded edges cost no
10929    /// request beyond the read already made, and reading the board for them would be a
10930    /// walk of every item for one field of one. A draft has no body in that answer, because
10931    /// a draft is not an issue, so a draft's are read off its own read by id — never off a
10932    /// listing of the board, which can be behind on the very item asked about.
10933    async fn recorded_edges(
10934        &self,
10935        id: &NativeId,
10936        near_kind: ItemKind,
10937        direction: Direction,
10938        natively_names: Option<ItemKind>,
10939        node: &Value,
10940        draft_slot: Option<&Option<BTreeMap<String, Value>>>,
10941    ) -> Result<Vec<DependencyEdge>, SourceError> {
10942        if direction != Direction::DependsOn {
10943            return Ok(Vec::new());
10944        }
10945        let slot = match (node.get("body"), draft_slot) {
10946            (Some(body), _) if natively_names.is_some() => {
10947                metadata_body(body.as_str().map(str::to_owned))?.1
10948            }
10949            // A draft the dependency read itself answered: this board's, or none of its.
10950            (_, Some(Some(slot))) => slot.clone(),
10951            (_, Some(None)) => return Ok(Vec::new()),
10952            _ => {
10953                let Some(item) = self.bound_item(id).await? else {
10954                    return Ok(Vec::new());
10955                };
10956                item.slot
10957            }
10958        };
10959        DependencyEdge::recorded(&slot, id, near_kind, &self.name, natively_names)
10960            .map_err(|message| SourceError::Malformed { message })
10961    }
10962
10963    /// Why `creation_owners` refuses a create filed in `target`, or `None` when it allows it —
10964    /// every create when the list is empty.
10965    fn owner_refusal(&self, target: &RepositoryTarget) -> Option<String> {
10966        if self.creation_owners.is_empty()
10967            || self
10968                .creation_owners
10969                .iter()
10970                .any(|owner| owner.eq_ignore_ascii_case(&target.owner))
10971        {
10972            return None;
10973        }
10974        Some(format!(
10975            "source {} would create the issue in repository {}, owned by {}, and its \
10976             creation_owners allows only repositories of {}",
10977            self.name,
10978            target.slug(),
10979            target.owner,
10980            self.creation_owners.join(", ")
10981        ))
10982    }
10983
10984    fn configured_repository(&self) -> Result<&RepositoryTarget, SourceError> {
10985        self.repository
10986            .as_ref()
10987            .ok_or_else(|| SourceError::Refused {
10988                message: format!(
10989                    "source {} has no repository configured, and a GitHub Projects board has no \
10990                 repository of its own to create an issue in; set repository: owner/name on \
10991                 this source",
10992                    self.name
10993                ),
10994            })
10995    }
10996
10997    /// The repository one new issue is created in, under the rule [`RepositoryTarget`]
10998    /// states.
10999    ///
11000    /// The fallback is demanded first, whichever arm answers: a write without a configured
11001    /// repository is refused naming the field exactly as it was before the rule existed,
11002    /// so a source that could not write before cannot write now, rather than writing for
11003    /// the one item whose own field happens to decide it.
11004    ///
11005    /// Everything this refuses is refused before `createIssue`, so a refusal leaves no
11006    /// issue behind: an entry that is not a repository on [`RepositoryTarget::HOST`], an
11007    /// entry owned by someone other than the owner of the parent issue's repository —
11008    /// GitHub accepts a sub-issue from another repository of the same owner and from no
11009    /// other, so `addSubIssue` would refuse it after the issue existed — a parent the
11010    /// board does not hold, and a parent that is a draft, which GitHub gives no sub-issues,
11011    /// both of which `addSubIssue` would likewise refuse too late. Whether the entry exists
11012    /// and is visible to the token is checked where its node id is resolved, still before
11013    /// `createIssue`. The parent is read by its own id through [`Self::item_by_id`] — never
11014    /// looked up in a listing of the board, which can be minutes behind an issue its own
11015    /// `projectItems` already places on it — and that read answers first from this process's
11016    /// own record, so a project created moments ago in this command answers though GitHub
11017    /// has not caught up.
11018    async fn creation_target(
11019        &self,
11020        incoming: &Incoming<'_>,
11021    ) -> Result<RepositoryTarget, SourceError> {
11022        let what = format!(
11023            "{} {:?}",
11024            incoming.written.kind().describes(),
11025            incoming.title
11026        );
11027        let target = self
11028            .creation_rule(incoming.repositories, incoming.parent, &what)
11029            .await?;
11030        // The engine asks `creation_refusal` before anything of a copy is written; this holds
11031        // every other create to the same restriction, before `createIssue`.
11032        match self.owner_refusal(&target) {
11033            Some(message) => Err(SourceError::Refused { message }),
11034            None => Ok(target),
11035        }
11036    }
11037
11038    /// [`Self::creation_target`]'s rule over what it reads of the item — its `repositories`
11039    /// and the project issue it is filed under — with `what` naming the item in a refusal: the
11040    /// one place the rule is, so the create, [`TaskSource::creation_repository`] and the
11041    /// write-time read of who can read the issue ([`TaskSource::visibility`]) cannot answer
11042    /// differently.
11043    ///
11044    /// On a source declared private, an item's one named repository is read for its
11045    /// visibility first — once per engine hold, see the `visibility` module — and one that
11046    /// does not read private decides nothing: the issue is created in the parent's
11047    /// repository, else the configured one. A read that cannot be answered refuses.
11048    async fn creation_rule(
11049        &self,
11050        repositories: &[Repository],
11051        parent: Option<&NativeId>,
11052        what: &str,
11053    ) -> Result<RepositoryTarget, SourceError> {
11054        let parent = match parent {
11055            Some(parent) => Some(self.bound_item(parent).await?.ok_or_else(|| {
11056                SourceError::Refused {
11057                    message: format!(
11058                        "GitHub project issue {} was not found on the board of source {}, so {} \
11059                         cannot be filed under it",
11060                        parent.0, self.name, what
11061                    ),
11062                }
11063            })?),
11064            None => None,
11065        };
11066        let parents_repository = parent
11067            .as_ref()
11068            .map(|parent| {
11069                // A draft is on the board and so is found, but it has no repository to
11070                // place a task in and GitHub gives it no sub-issues, so `addSubIssue`
11071                // would refuse the task only once `createIssue` had made it.
11072                if parent.content_kind == ContentKind::DraftIssue {
11073                    return Err(SourceError::Refused {
11074                        message: format!(
11075                            "GitHub project item {} on the board of source {} is a draft, \
11076                             which cannot have sub-issues, so {} cannot be filed under it",
11077                            parent.id.0, self.name, what
11078                        ),
11079                    });
11080                }
11081                // An issue's repository is where a sub-issue is placed and whose owner it
11082                // is compared against, so a parent whose repository this source cannot
11083                // spell as `owner/name` — GitHub's login grammar is wider than this
11084                // source's floor — is one nothing can be filed under.
11085                parent
11086                    .own_repository
11087                    .as_ref()
11088                    .and_then(|origin| RepositoryTarget::from_origin(origin).ok())
11089                    .ok_or_else(|| SourceError::Malformed {
11090                        message: format!(
11091                            "GitHub project issue {} on the board of source {} is in {}, which \
11092                             is not a {}/owner/name repository this source can place {} in",
11093                            parent.id.0,
11094                            self.name,
11095                            parent
11096                                .own_repository
11097                                .as_ref()
11098                                .map_or("no repository", Repository::as_str),
11099                            RepositoryTarget::HOST,
11100                            what
11101                        ),
11102                    })
11103            })
11104            .transpose()?;
11105        self.creation_rule_in_repository(repositories, parents_repository, what)
11106            .await
11107    }
11108
11109    async fn creation_rule_in_repository(
11110        &self,
11111        repositories: &[Repository],
11112        parents_repository: Option<RepositoryTarget>,
11113        what: &str,
11114    ) -> Result<RepositoryTarget, SourceError> {
11115        let fallback = self.configured_repository()?;
11116        match repositories {
11117            [named] => {
11118                let target =
11119                    RepositoryTarget::from_origin(named).map_err(|_| SourceError::Refused {
11120                        message: format!(
11121                            "{} names repository {}, which is not a {}/owner/name repository \
11122                             source {} can create an issue in; name one that is, or name none",
11123                            what,
11124                            named.as_str(),
11125                            RepositoryTarget::HOST,
11126                            self.name
11127                        ),
11128                    })?;
11129                // On a source declared private, an issue whose one named repository does not
11130                // read private is created where an item naming none is: the item still names
11131                // that repository in its metadata slot, and its issue stays private.
11132                if self.is_declared_private()
11133                    && self.repository_visibility(&target).await?
11134                        != onetaskgraph_plugin_api::Visibility::Private
11135                {
11136                    return Ok(parents_repository.unwrap_or_else(|| fallback.clone()));
11137                }
11138                if let Some(parents) = &parents_repository
11139                    && parents.owner != target.owner
11140                {
11141                    return Err(SourceError::Refused {
11142                        message: format!(
11143                            "{} names repository {}, owned by {}, but its project's issue is in \
11144                             {}, owned by {}, and GitHub files a sub-issue only in a repository \
11145                             of the same owner as its parent issue; name a repository of {}, or \
11146                             name none",
11147                            what,
11148                            target.slug(),
11149                            target.owner,
11150                            parents.slug(),
11151                            parents.owner,
11152                            parents.owner
11153                        ),
11154                    });
11155                }
11156                Ok(target)
11157            }
11158            _ => Ok(parents_repository.unwrap_or_else(|| fallback.clone())),
11159        }
11160    }
11161
11162    /// The node id of the repository `incoming` is being created in, or the refusal naming
11163    /// the item and the repository the token cannot see.
11164    ///
11165    /// Resolved once per command per repository; see [`Self::repository_cache`].
11166    async fn repository_id(
11167        &self,
11168        repository: &RepositoryTarget,
11169        incoming: &Incoming<'_>,
11170    ) -> Result<String, SourceError> {
11171        if let Some(id) = self.repository_cache()?.get(repository).cloned() {
11172            return Ok(id);
11173        }
11174        let data = self
11175            .graphql(
11176                graphql::REPOSITORY,
11177                json!({"owner":repository.owner,"name":repository.name}),
11178            )
11179            .await?;
11180        self.repository_read(&data, repository, incoming)
11181    }
11182
11183    /// The repository's node id out of an answer carrying the `repository` root, held for
11184    /// the rest of this command, or the refusal naming the item that cannot be created in it.
11185    fn repository_read(
11186        &self,
11187        data: &Value,
11188        repository: &RepositoryTarget,
11189        incoming: &Incoming<'_>,
11190    ) -> Result<String, SourceError> {
11191        let node = data
11192            .get("repository")
11193            .filter(|value| !value.is_null())
11194            .ok_or_else(|| SourceError::Refused {
11195                message: format!(
11196                    "GitHub repository {} was not found or is not visible to the token, so {} \
11197                     {:?} cannot be created in it",
11198                    repository.slug(),
11199                    incoming.written.kind().describes(),
11200                    incoming.title
11201                ),
11202            })?;
11203        let id = required_str(node, "id")?.to_owned();
11204        self.repository_cache()?
11205            .insert(repository.clone(), id.clone());
11206        Ok(id)
11207    }
11208
11209    fn repository_cache(
11210        &self,
11211    ) -> Result<std::sync::MutexGuard<'_, BTreeMap<RepositoryTarget, String>>, SourceError> {
11212        self.repository_cache
11213            .lock()
11214            .map_err(|_| SourceError::Unavailable {
11215                message: "this source's record of the destination repository was left \
11216                          inconsistent by an earlier failure; next: run the command again"
11217                    .into(),
11218            })
11219    }
11220
11221    /// Create or update one board item, whichever kind it is.
11222    async fn write_item(
11223        &self,
11224        incoming: &Incoming<'_>,
11225        target: Option<&NativeId>,
11226        depends_on: &[DependencyEdge],
11227    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
11228        let prepared = self.prepare_write(incoming, target, depends_on).await?;
11229        let landed = match &prepared.destination {
11230            // Its content is written last, by `complete_write`, once everything else has landed.
11231            WriteDestination::Existing(item) => Landed {
11232                content_id: item.id.clone(),
11233                item_id: Some(item.item_id.clone()),
11234                url: item.url.clone(),
11235                number: item.number,
11236            },
11237            WriteDestination::New(target) => {
11238                if self.deferring()? {
11239                    self.create_filed_issue(
11240                        prepared.board.id.as_str(),
11241                        target,
11242                        incoming,
11243                        &prepared.body,
11244                    )
11245                    .await?
11246                } else {
11247                    self.create_and_file_issue(
11248                        prepared.board.id.as_str(),
11249                        target,
11250                        incoming,
11251                        &prepared.body,
11252                    )
11253                    .await?
11254                }
11255            }
11256        };
11257        self.complete_write(incoming, prepared, landed).await
11258    }
11259
11260    /// Everything one write of `incoming` reads and decides before it sends anything: what is
11261    /// there now, where a new item is created, the board's fields, and every value refused while
11262    /// nothing has been written — the item's body included.
11263    async fn prepare_write(
11264        &self,
11265        incoming: &Incoming<'_>,
11266        target: Option<&NativeId>,
11267        depends_on: &[DependencyEdge],
11268    ) -> Result<Prepared, SourceError> {
11269        // Refused before anything is read or written: a task or a project titled the way
11270        // this board spells a document would land as an issue this same source reads back
11271        // as a document, so the field this destination cannot carry is named rather than
11272        // written and silently reclassified.
11273        if let Written::Work(kind, _) = incoming.written
11274            && incoming.title.starts_with(DESIGN_TITLE_PREFIX)
11275        {
11276            return Err(SourceError::Refused {
11277                message: format!(
11278                    "the title of this {} begins {DESIGN_TITLE_PREFIX:?}, which is how source {} \
11279                     spells a document, so it would read back as one rather than as a {}; \
11280                     retitle it, or copy it as a document",
11281                    kind.marker(),
11282                    self.name,
11283                    kind.marker()
11284                ),
11285            });
11286        }
11287        // The destination is read by its own id, and whether this board holds it is decided
11288        // by that read — its own `projectItems` — rather than by whether a listing of the
11289        // board happens to include it yet. See the module documentation.
11290        // An existing issue is never moved; a new one is created where the rule says — and
11291        // knowing where is what lets the board's fields and that repository's id be read
11292        // together, before anything below needs either.
11293        let destination = match target {
11294            Some(target) => {
11295                WriteDestination::Existing(Box::new(self.bound_item(target).await?.ok_or_else(
11296                    || SourceError::Refused {
11297                        message: format!("GitHub destination item {} was not found", target.0),
11298                    },
11299                )?))
11300            }
11301            None => {
11302                let target = self.creation_target(incoming).await?;
11303                self.creation_context(&target, incoming).await?;
11304                WriteDestination::New(target)
11305            }
11306        };
11307        let existing = destination.existing();
11308        let board = self
11309            .fields_for(
11310                existing,
11311                incoming.metadata.contains_key(ORIGIN_KEY),
11312                incoming.written.status().is_some(),
11313                incoming
11314                    .priority
11315                    .is_some_and(|priority| priority != Priority::None),
11316            )
11317            .await?;
11318        let status_target = incoming
11319            .written
11320            .work_status()
11321            .map(|(kind, status)| self.resolved_target(kind, status.category))
11322            .transpose()?;
11323        let column = match (incoming.written.work_status(), status_target.as_ref()) {
11324            (Some((kind, status)), Some(target)) => {
11325                self.column_for(&board.fields, kind, status.category, target)?
11326            }
11327            _ => None,
11328        };
11329        // Resolved before anything is created, for the reason the column above is: a
11330        // priority this board has no option for is refused while nothing has been written.
11331        let priority_write = match incoming.priority {
11332            Some(priority) => self.priority_write(&board.fields, existing, priority)?,
11333            None => None,
11334        };
11335        // And for the reason the priority is: a value no projected field can hold, or a board
11336        // that cannot hold the field, is refused while nothing has been written.
11337        let (projections, projected) = self.projection_writes(
11338            &board.fields,
11339            existing.map(|item| &item.projected),
11340            incoming.metadata,
11341            None,
11342        )?;
11343        let content_kind = existing.map_or(ContentKind::Issue, |item| item.content_kind);
11344        if content_kind == ContentKind::DraftIssue {
11345            if let (Some(StatusTarget::Terminal(_, _)), Some(status)) =
11346                (status_target.as_ref(), incoming.written.status())
11347            {
11348                return Err(self.closes_a_draft(status.category));
11349            }
11350            if incoming.parent.is_some() {
11351                return Err(SourceError::Refused {
11352                    message: "GitHub draft items cannot be a project's sub-issue".into(),
11353                });
11354            }
11355        }
11356        // The people it is to be assigned to are looked up — unless this process already has —
11357        // and a login GitHub does not know refused, while nothing has been written.
11358        if let Some(people) = incoming.assignees
11359            && existing.is_none_or(|item| {
11360                item.assignees
11361                    .as_deref()
11362                    .is_none_or(|held| !assignees::same_people(held, people))
11363            })
11364        {
11365            if content_kind == ContentKind::DraftIssue {
11366                return Err(self.assigns_a_draft());
11367            }
11368            self.resolve_people(people).await?;
11369            self.people_ids(
11370                people,
11371                &existing.map_or_else(
11372                    || format!("the new {}", incoming.title),
11373                    Resolved::written_name,
11374                ),
11375            )?;
11376        }
11377        match existing {
11378            Some(item) if content_kind == ContentKind::Issue => {
11379                if item.labels != incoming.labels {
11380                    return Err(SourceError::Refused {
11381                        message: "GitHub issue labels differ from the labels being written".into(),
11382                    });
11383                }
11384            }
11385            _ => {
11386                if !incoming.labels.is_empty() {
11387                    return Err(SourceError::Refused {
11388                        message: "GitHub items created by this destination carry no labels".into(),
11389                    });
11390                }
11391            }
11392        }
11393
11394        // The repository the issue really lives in is what the slot below is written against,
11395        // so a single entry that is where the issue is created travels as no key at all, and
11396        // the read side derives it back from the issue.
11397        let own_repository = match &destination {
11398            WriteDestination::Existing(item) => item.own_repository.clone(),
11399            WriteDestination::New(target) => Some(
11400                Repository::try_from(target.origin())
11401                    .map_err(|message| SourceError::Config { message })?,
11402            ),
11403        };
11404        let (native, fallback) = self
11405            .partition_edges(
11406                incoming.written.kind(),
11407                content_kind,
11408                existing.and_then(|item| item.blocked_by.as_deref()),
11409                depends_on,
11410            )
11411            .await?;
11412        let mut slot = slot_metadata(incoming, own_repository.as_ref(), &fallback);
11413        let content = match incoming.assets {
11414            Some(assets) => {
11415                let uploads = self.upload_assets(own_repository.as_ref(), assets).await?;
11416                let rewritten = onetaskgraph_plugin_api::serve_asset_references(
11417                    incoming.content.unwrap_or_default(),
11418                    &mut slot,
11419                    &uploads,
11420                );
11421                incoming.content.map(|_| rewritten)
11422            }
11423            None => incoming.content.map(str::to_owned),
11424        };
11425        // A write over an existing item keeps its `## Links` section, re-rendered from the
11426        // links it holds.
11427        let content = content.map(|content| {
11428            onetaskgraph_plugin_api::relinked(
11429                &content,
11430                existing.and_then(|item| item.body.as_deref()),
11431                incoming.metadata,
11432            )
11433        });
11434        let marked = content.as_deref().map(|content| self.marked(content));
11435        let body = compose_body(marked.as_deref(), &slot)?;
11436        // Read before anything is created, for the reason the field below is: a value
11437        // this destination cannot store has to refuse, and refusing after `createIssue`
11438        // would leave an issue behind that nothing asked for. The engine writes a
11439        // qualified id here; a caller handing this key anything else is told so rather
11440        // than having it silently stored as no origin at all.
11441        // 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.
11442        let origin = match incoming.metadata.get(ORIGIN_KEY) {
11443            None => "",
11444            Some(Value::String(origin)) => origin.as_str(),
11445            Some(other) => {
11446                return Err(SourceError::Refused {
11447                    message: format!(
11448                        "{ORIGIN_KEY} holds a qualified id spelled as a string, and this item's \
11449                         is {other}"
11450                    ),
11451                });
11452            }
11453        };
11454        // Resolved before anything is created: a board that cannot carry the copy origin
11455        // has to refuse the write, and refusing it after `createIssue` would leave an
11456        // issue behind that nothing asked for.
11457        let origin_field = match Board::field(&board.fields, ORIGIN_FIELD)? {
11458            Some(field) => {
11459                if required_str(field, "__typename")? != "ProjectV2Field" {
11460                    return Err(SourceError::Refused {
11461                        message: format!(
11462                            "GitHub board source-owned {ORIGIN_FIELD} field is not a text field"
11463                        ),
11464                    });
11465                }
11466                Some(required_str(field, "id")?.to_owned())
11467            }
11468            None if incoming.metadata.contains_key(ORIGIN_KEY) => {
11469                return Err(SourceError::Refused {
11470                    message: format!(
11471                        "GitHub board has no source-owned {ORIGIN_FIELD} text field, and the \
11472                         item carries {ORIGIN_KEY}; add a text field named {ORIGIN_FIELD} to \
11473                         the board"
11474                    ),
11475                });
11476            }
11477            None => None,
11478        };
11479
11480        Ok(Prepared {
11481            origin: origin.to_owned(),
11482            destination,
11483            board,
11484            status_target,
11485            column,
11486            priority_write,
11487            projections,
11488            projected,
11489            content_kind,
11490            own_repository,
11491            native,
11492            slot,
11493            content,
11494            body,
11495            origin_field,
11496        })
11497    }
11498
11499    /// Everything one write does once the item it writes exists: its board fields, its
11500    /// relationships and — for an item that was already there — its content last, then what this
11501    /// process remembers of it.
11502    ///
11503    /// While this source is holding writes back — see [`TaskSource::begin_deferred_writes`] — an
11504    /// item this command created has its fields, its closing and its edges held for
11505    /// [`TaskSource::finish_writes`] rather than sent here.
11506    async fn complete_write(
11507        &self,
11508        incoming: &Incoming<'_>,
11509        prepared: Prepared,
11510        landed: Landed,
11511    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
11512        let Prepared {
11513            destination,
11514            board,
11515            status_target,
11516            column,
11517            priority_write,
11518            projections,
11519            projected,
11520            content_kind,
11521            own_repository,
11522            native,
11523            slot,
11524            content,
11525            body,
11526            origin,
11527            origin_field,
11528        } = prepared;
11529        let existing = destination.existing();
11530        let origin = origin.as_str();
11531        let Landed {
11532            content_id,
11533            item_id,
11534            url,
11535            number,
11536        } = landed;
11537
11538        // Only what differs from the item as this write read it is sent: a priority the item
11539        // already holds is not, so an unchanged re-copy writes no field and a person's edit of
11540        // it since that read is left alone.
11541        let priority_write = priority_write.filter(|_| {
11542            !existing.is_some_and(|item| {
11543                incoming.priority.map(HeldPriority::Read) == Some(item.priority.clone())
11544            })
11545        });
11546        let written_option = column.as_ref().map(|(_, _, name)| name.clone());
11547        let column = column
11548            .filter(|(_, _, name)| existing.is_none_or(|item| item.option.as_ref() != Some(name)))
11549            .map(|(field, option, _)| (field, option));
11550        // Creating an item here is several calls — `createIssue`, which files it on the
11551        // board, then its board fields, the parent and the dependencies — and GitHub can fail
11552        // at any of them. Everything this source can refuse *before* the first of those is
11553        // already checked above, so what is left is GitHub itself failing part way. When it
11554        // does over an item this call created, the issue is taken back: a write that
11555        // refused must not leave an item behind that nobody asked for, and one that does
11556        // makes the retry create a second.
11557        // Whether the board-field write carrying a moved origin was answered as landing whole.
11558        // When it was refused, GitHub does not say which of its fields ran before the one that
11559        // failed, so the origin may or may not have moved.
11560        let mut origin_landed = false;
11561        // An item this command created while writes are held back has every part that can land
11562        // later held for `finish_writes` — its own create filed it on the board and under its
11563        // project already — and so does a later write of it in the same command.
11564        let holding = (existing.is_none() && self.deferring()?) || self.holds_back(&content_id)?;
11565        let landed = if holding {
11566            self.hold_back(
11567                &board.id,
11568                &content_id,
11569                existing,
11570                origin_field.as_deref(),
11571                origin,
11572                column,
11573                status_target.as_ref(),
11574                priority_write.as_ref(),
11575                &projections,
11576                &native,
11577            )
11578        } else if let Some(item_id) = item_id.as_deref() {
11579            self.finish_write(
11580                board.id.as_str(),
11581                incoming,
11582                &content_id,
11583                item_id,
11584                content_kind,
11585                existing,
11586                origin_field.as_deref(),
11587                origin,
11588                column,
11589                status_target.as_ref(),
11590                priority_write.as_ref(),
11591                &projections,
11592                &native,
11593                &mut origin_landed,
11594            )
11595            .await
11596        } else {
11597            // An issue a create filed on the board itself has no board item this process
11598            // knows until `finish_writes` reads it, so nothing but a held-back write may land
11599            // on it before then.
11600            Err(SourceError::Malformed {
11601                message: format!(
11602                    "issue {} was written before the board item GitHub filed it as was read",
11603                    content_id.0
11604                ),
11605            })
11606        };
11607        // An existing item's title, body and state go last, in one `updateIssue`, once its board
11608        // fields and its relationships have landed: a refusal of any of those then leaves its
11609        // body — and the metadata slot inside it — exactly as it stood.
11610        let landed = match (landed, existing) {
11611            (Ok(()), Some(item)) => {
11612                self.update_existing(item, incoming, &body, status_target.as_ref())
11613                    .await
11614            }
11615            (landed, _) => landed,
11616        };
11617        if let Err(error) = landed {
11618            match existing {
11619                // Best effort, and the write's own failure is what the caller is told: a
11620                // refusal naming the tidy-up would hide why the write failed at all.
11621                None => {
11622                    let _ = self.delete_issue(&content_id).await;
11623                }
11624                // The origin field is the one piece of an existing item's metadata written
11625                // before its body, so a write refused after it puts it back as it was. When
11626                // that is refused too, the write's own failure is still what the caller is
11627                // told — with what it left behind added, because the item's metadata is then
11628                // not as it stood and a caller retrying has to know which key moved.
11629                Some(item) => {
11630                    let before = item.origin.as_deref().unwrap_or("");
11631                    if let Some(field) = origin_field.as_deref()
11632                        && before != origin
11633                        && let Err(restore) = self
11634                            .set_item_field(
11635                                board.id.as_str(),
11636                                &item.item_id,
11637                                field,
11638                                json!({"text": before}),
11639                            )
11640                            .await
11641                    {
11642                        let left = if origin_landed {
11643                            format!(
11644                                "its {ORIGIN_KEY} was moved to {origin:?} before that and could \
11645                                 not be put back to {before:?} ({restore}), so item {} still \
11646                                 holds {origin:?} there",
11647                                item.id.0
11648                            )
11649                        } else {
11650                            format!(
11651                                "the refused write carried its {ORIGIN_KEY} from {before:?} to \
11652                                 {origin:?}, GitHub does not say whether that part of it ran, \
11653                                 and putting it back to {before:?} was refused ({restore}), so \
11654                                 item {} holds {origin:?} or {before:?} there",
11655                                item.id.0
11656                            )
11657                        };
11658                        return Err(noting(
11659                            error,
11660                            &format!(
11661                                "; {left}; next: set {ORIGIN_KEY} on it back to {before:?}, or \
11662                                 run the write again"
11663                            ),
11664                        ));
11665                    }
11666                }
11667            }
11668            return Err(error);
11669        }
11670
11671        let written_status = match (incoming.written.work_status(), status_target.as_ref()) {
11672            (Some((kind, _)), Some(StatusTarget::Terminal(_, reason))) => {
11673                self.statuses
11674                    .status(kind, written_option.as_deref(), true, Some(reason.reason()))
11675            }
11676            (Some((kind, _)), Some(StatusTarget::Column(_))) => {
11677                self.statuses
11678                    .status(kind, written_option.as_deref(), false, None)
11679            }
11680            (Some((_, status)), _) => status.clone(),
11681            (None, _) => Status {
11682                category: StatusCategory::Unknown,
11683                name: "Open".to_owned(),
11684            },
11685        };
11686
11687        // So the rest of this command reads what it just did rather than what the board
11688        // said before it. See `remember_written` for which half takes it.
11689        let remembered = Resolved {
11690            // Empty for an issue whose board item is not read yet: `finish_writes` reads it
11691            // and `learn_item` puts it here.
11692            // 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.
11693            item_id: item_id.unwrap_or_default(),
11694            id: content_id.clone(),
11695            content_kind,
11696            kind: incoming.written.kind(),
11697            title: incoming.title.to_owned(),
11698            // The visible half of the body this write composed, split back off it the
11699            // way a read splits it — so what this record reports is what a read of the
11700            // same issue reports, rather than the person's text with the metadata slot
11701            // still on the end of it.
11702            body: self.visible(body.clone())?.0,
11703            raw_body: body.clone(),
11704            // A document has no status of its own; what it reads back as is whatever
11705            // the issue's own state says, which is what a re-read reports.
11706            status: written_status,
11707            option: written_option.or_else(|| existing.and_then(|item| item.option.clone())),
11708            priority: match incoming.priority {
11709                Some(priority) => HeldPriority::Read(priority),
11710                None => existing.map_or(HeldPriority::Read(Priority::None), |item| {
11711                    item.priority.clone()
11712                }),
11713            },
11714            // What `state_input` asked for: closed for a terminal target, open for any other
11715            // status, and the issue's own state left as it was by a document write.
11716            closed: content_kind == ContentKind::Issue
11717                && match status_target.as_ref() {
11718                    Some(StatusTarget::Terminal(_, _)) => true,
11719                    Some(_) => false,
11720                    None => existing.is_some_and(|item| item.closed),
11721                },
11722            reason: match status_target.as_ref() {
11723                Some(StatusTarget::Terminal(_, reason)) if content_kind == ContentKind::Issue => {
11724                    Some(reason.reason().to_owned())
11725                }
11726                Some(_) => None,
11727                None => existing.and_then(|item| item.reason.clone()),
11728            },
11729            delivers: incoming.delivers.to_vec(),
11730            delivered_by: incoming.delivered_by.to_vec(),
11731            labels: incoming.labels.to_vec(),
11732            parent: incoming.parent.cloned(),
11733            issue_parent: None,
11734            origin: (!origin.is_empty()).then(|| origin.to_owned()),
11735            projected,
11736            number,
11737            // In the update path this is the item's own url, read off `existing` where the
11738            // record above was bound, so one expression serves both halves.
11739            url,
11740            created_at: existing.and_then(|item| item.created_at),
11741            updated_at: existing.and_then(|item| item.updated_at),
11742            // What this write moved is GitHub's to say, so a record of it gives no token until
11743            // it is read again.
11744            item_updated_at: None,
11745            comment_count: None,
11746            relationship_events: None,
11747            served_at: None,
11748            facets: None,
11749            own_repository,
11750            repositories: incoming.repositories.to_vec(),
11751            classification: incoming.classification,
11752            slot,
11753            board_id: Some(board.id.as_str().to_owned()),
11754            fields: board
11755                .fields
11756                .get("nodes")
11757                .and_then(Value::as_array)
11758                .cloned()
11759                .unwrap_or_default(),
11760            board_fields: Some(board.fields.clone()),
11761            // What this write left the relationship holding is known by id alone, and a
11762            // later read of its edges needs each far end's kind, so it reads them again.
11763            blocked_by: None,
11764            // The people it named, which its own answer was held to; none named keeps the
11765            // item's, and creates a task of an opted-in source unassigned.
11766            assignees: match incoming.assignees {
11767                Some(people) => Some(people.to_vec()),
11768                None => match existing {
11769                    Some(item) => item.assignees.clone(),
11770                    None => (self.assignees
11771                        && matches!(incoming.written, Written::Work(ItemKind::Task, _)))
11772                    .then(Vec::new),
11773                },
11774            },
11775        };
11776        self.remember_written(remembered, existing.is_none())?;
11777        Ok(onetaskgraph_plugin_api::AssetsWritten {
11778            id: content_id,
11779            content,
11780        })
11781    }
11782
11783    /// Everything a write does after the item exists: its board fields, its parent, and
11784    /// its dependencies.
11785    ///
11786    /// Split out of `write_item` so there is one place a failure past the point of no
11787    /// return is caught, rather than a tidy-up repeated at each `?` above.
11788    // llmlint: ignore[suppressions_justified] This is the tail of `write_item` lifted out
11789    // so there is one place a failure past the point of no return is caught, and its
11790    // arguments are exactly the values that tail already had in scope. Bundling them into a
11791    // struct would describe no concept — it would be "the arguments of this function" — and
11792    // would put the whole of `write_item`'s locals behind one more indirection.
11793    #[allow(clippy::too_many_arguments)]
11794    async fn finish_write(
11795        &self,
11796        board_id: &str,
11797        incoming: &Incoming<'_>,
11798        content_id: &NativeId,
11799        item_id: &str,
11800        content_kind: ContentKind,
11801        existing: Option<&Resolved>,
11802        origin_field: Option<&str>,
11803        origin: &str,
11804        column: Option<(String, String)>,
11805        status_target: Option<&StatusTarget>,
11806        priority: Option<&PriorityWrite>,
11807        projections: &[ProjectionWrite],
11808        native: &[String],
11809        origin_landed: &mut bool,
11810    ) -> Result<(), SourceError> {
11811        let (fields, clears) = field_writes(
11812            existing,
11813            origin_field,
11814            origin,
11815            column,
11816            priority,
11817            projections,
11818        );
11819        self.set_item_fields(board_id, item_id, &fields, &clears)
11820            .await?;
11821        *origin_landed = true;
11822
11823        // An existing issue closes in the `updateIssue` its write ends with; one created just
11824        // now closes here, once its option is selected.
11825        if existing.is_none()
11826            && content_kind == ContentKind::Issue
11827            && matches!(status_target, Some(StatusTarget::Terminal(_, _)))
11828        {
11829            self.update_content(
11830                ContentKind::Issue,
11831                content_id,
11832                json!({"stateInput":state_input(status_target)}),
11833            )
11834            .await?;
11835        }
11836
11837        if content_kind == ContentKind::Issue {
11838            self.reparent(
11839                existing.and_then(|item| item.parent.clone()),
11840                content_id,
11841                incoming.parent,
11842            )
11843            .await?;
11844            // A document takes part in no dependency graph, so writing one neither reads
11845            // nor changes the issue's own `blockedBy` relationships. Reconciling them
11846            // against the empty list a document write carries would *delete* whatever
11847            // relationships a person had made on that issue, which is a write nobody
11848            // asked for.
11849            if incoming.written.kind() != BoardKind::Document {
11850                let issue = match existing {
11851                    Some(item) => Issue::Existing(item.blocked_by.as_deref()),
11852                    None => Issue::Created,
11853                };
11854                self.reconcile_blocked_by(content_id, native, issue).await?;
11855            }
11856        }
11857        Ok(())
11858    }
11859
11860    /// Whether this source is holding writes back — see [`TaskSource::begin_deferred_writes`].
11861    fn deferring(&self) -> Result<bool, SourceError> {
11862        Ok(self.deferred()?.is_some())
11863    }
11864
11865    /// Whether `content` is an item this command created whose parts are held back.
11866    fn holds_back(&self, content: &NativeId) -> Result<bool, SourceError> {
11867        Ok(self
11868            .deferred()?
11869            .as_ref()
11870            .is_some_and(|deferred| deferred.holds(content)))
11871    }
11872
11873    fn deferred(&self) -> Result<std::sync::MutexGuard<'_, Option<Deferred>>, SourceError> {
11874        self.deferred.lock().map_err(|_| SourceError::Unavailable {
11875            message: "this source's record of the writes it is holding back was left \
11876                      inconsistent by an earlier failure; next: run the command again"
11877                .into(),
11878        })
11879    }
11880
11881    /// Creates one issue filed on the board and under its project by the `createIssue` itself —
11882    /// `projectV2Ids` naming the board and `parentIssueId` the project — which is what a copy
11883    /// creates with: one request where adding it to the board and filing it under its project
11884    /// were two more. GitHub adds the board item after answering, so its id is not known here;
11885    /// [`TaskSource::finish_writes`] reads it.
11886    async fn create_filed_issue(
11887        &self,
11888        board_id: &str,
11889        repository: &RepositoryTarget,
11890        incoming: &Incoming<'_>,
11891        body: &Option<String>,
11892    ) -> Result<Landed, SourceError> {
11893        let repository_id = self.repository_id(repository, incoming).await?;
11894        let mut input = filed_input(&repository_id, board_id, incoming, body);
11895        self.assigning(&mut input, incoming)?;
11896        let data = match self
11897            .graphql(graphql::CREATE_ISSUE, json!({"input": &input}))
11898            .await
11899        {
11900            Ok(data) => data,
11901            Err(error) => return Err(self.refusing_people(&input, error)),
11902        };
11903        let created = data
11904            .pointer("/createIssue/issue")
11905            .filter(|value| !value.is_null())
11906            .ok_or_else(|| SourceError::Malformed {
11907                message: "GitHub issue creation returned no issue".into(),
11908            })?;
11909        let landed = self.created_landed(created).await?;
11910        // An issue GitHub created assigned otherwise than asked is refused and taken back; a
11911        // delete GitHub refuses too is answered beside the refusal, naming the issue left.
11912        if let Err(error) = self.assigned_as_asked(&input, Some(created)) {
11913            return Err(self.taken_back(&landed.content_id, created, error).await);
11914        }
11915        Ok(landed)
11916    }
11917
11918    /// Keep the address `createIssue` answered for the issue `content`, for
11919    /// [`TaskSource::written_location`].
11920    fn note_written(&self, content: &NativeId, url: Option<&str>) {
11921        if let Some(url) = url {
11922            self.written
11923                .lock()
11924                .unwrap_or_else(std::sync::PoisonError::into_inner)
11925                .insert(content.clone(), url.to_owned());
11926        }
11927    }
11928
11929    /// What one `createIssue` answered, as the item it created — or, when its number cannot be
11930    /// read, the refusal, after taking the issue back.
11931    async fn created_landed(&self, created: &Value) -> Result<Landed, SourceError> {
11932        let content_id = NativeId(required_nonblank_str(created, "id")?.to_owned());
11933        let url = optional_str(created, "url")?.map(str::to_owned);
11934        let number = match created_issue_number(created) {
11935            Ok(number) => number,
11936            Err(error) => {
11937                let _ = self.delete_issue(&content_id).await;
11938                return Err(error);
11939            }
11940        };
11941        self.note_written(&content_id, url.as_deref());
11942        Ok(Landed {
11943            content_id,
11944            item_id: None,
11945            url,
11946            number,
11947        })
11948    }
11949
11950    /// Hold back everything a write of the created item `content` would send after creating it,
11951    /// for [`TaskSource::finish_writes`]: the same field values, closing and edges
11952    /// `finish_write` sends, the parent excepted, which its create already named. A later write
11953    /// of the same item replaces what it changes.
11954    // 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.
11955    #[allow(clippy::too_many_arguments)]
11956    fn hold_back(
11957        &self,
11958        board_id: &BoardId,
11959        content: &NativeId,
11960        existing: Option<&Resolved>,
11961        origin_field: Option<&str>,
11962        origin: &str,
11963        column: Option<(String, String)>,
11964        status_target: Option<&StatusTarget>,
11965        priority: Option<&PriorityWrite>,
11966        projections: &[ProjectionWrite],
11967        native: &[String],
11968    ) -> Result<(), SourceError> {
11969        let status = column.map(|(field, option)| {
11970            let name = self
11971                .fields_cache()
11972                .ok()
11973                .and_then(|fields| {
11974                    fields.as_ref().and_then(|board| {
11975                        option_name(&board.fields, &field, &option).map(str::to_owned)
11976                    })
11977                })
11978                .unwrap_or_default();
11979            (field, option, name)
11980        });
11981        let (fields, clears) =
11982            field_writes(existing, origin_field, origin, None, priority, projections);
11983        let close = match status_target {
11984            Some(StatusTarget::Terminal(_, reason)) => Some(*reason),
11985            _ => None,
11986        };
11987        let mut deferred = self.deferred()?;
11988        let deferred = deferred.get_or_insert_with(Deferred::default);
11989        if let Deferred::Nothing = deferred {
11990            *deferred = Deferred::Held {
11991                board: board_id.clone(),
11992                created: Vec::new(),
11993            };
11994        }
11995        let Deferred::Held { created, .. } = deferred else {
11996            unreachable!("held back on the line above");
11997        };
11998        let held = match created.iter().position(|held| held.content == *content) {
11999            Some(at) => &mut created[at],
12000            None => {
12001                created.push(HeldBack {
12002                    content: content.clone(),
12003                    fields: Vec::new(),
12004                    status: None,
12005                    clears: Vec::new(),
12006                    close: None,
12007                    edges: Vec::new(),
12008                });
12009                created.last_mut().expect("just held")
12010            }
12011        };
12012        for (field, value) in fields {
12013            held.fields.retain(|(held, _)| *held != field);
12014            held.clears.retain(|held| *held != field);
12015            held.fields.push((field, value));
12016        }
12017        for field in clears {
12018            held.fields.retain(|(held, _)| held != field);
12019            if !held.clears.iter().any(|held| held == field) {
12020                held.clears.push(field.to_owned());
12021            }
12022        }
12023        if status.is_some() {
12024            held.status = status;
12025        }
12026        if close.is_some() {
12027            held.close = close;
12028        }
12029        // Nothing of an item created in this command has been sent but its create, so the edges
12030        // it is to have are exactly the ones its latest write names.
12031        held.edges = native.iter().map(|far| NativeId(far.clone())).collect();
12032        Ok(())
12033    }
12034
12035    /// Create every task of `writes`, together, filed on the board and under each one's
12036    /// project: [`graphql::CREATE_ISSUES`], [`MUTATION_BATCH`] to a request.
12037    ///
12038    /// Each is prepared as [`Self::write_item`] prepares one — every refusal a write owes made
12039    /// before the first request — then created, then completed with its parts held back. A
12040    /// request refused part way leaves the issues it did create, which are taken back, with the
12041    /// rest of this call's, before the refusal is answered.
12042    async fn create_together(
12043        &self,
12044        writes: &[ItemWrite<Task>],
12045    ) -> Result<Vec<NativeId>, SourceError> {
12046        let incomings: Vec<Incoming<'_>> = writes
12047            .iter()
12048            .map(|write| self.task_incoming(write, None))
12049            .collect::<Result<_, _>>()?;
12050        // Every person these creates assign, looked up together rather than one write at a time.
12051        let people: Vec<String> = writes
12052            .iter()
12053            .filter_map(|write| write.item.assignees.clone())
12054            .flatten()
12055            .collect();
12056        self.resolve_people(&people).await?;
12057        let mut prepared = Vec::with_capacity(writes.len());
12058        for (incoming, write) in incomings.iter().zip(writes) {
12059            if write.target.is_some() {
12060                return Err(SourceError::Malformed {
12061                    message: "a write naming its target was handed to a batch of creates".into(),
12062                });
12063            }
12064            prepared.push(
12065                self.prepare_write(incoming, None, &write.depends_on)
12066                    .await?,
12067            );
12068        }
12069        let mut inputs = Vec::with_capacity(prepared.len());
12070        for (incoming, prepared) in incomings.iter().zip(&prepared) {
12071            let WriteDestination::New(target) = &prepared.destination else {
12072                return Err(SourceError::Malformed {
12073                    message: "an update was decided for a write handed to a batch of creates"
12074                        .into(),
12075                });
12076            };
12077            let repository_id = self.repository_id(target, incoming).await?;
12078            let mut input = filed_input(
12079                &repository_id,
12080                prepared.board.id.as_str(),
12081                incoming,
12082                &prepared.body,
12083            );
12084            self.assigning(&mut input, incoming)?;
12085            inputs.push(input);
12086        }
12087        let mut landed: Vec<Landed> = Vec::with_capacity(inputs.len());
12088        let refused = 'create: {
12089            for chunk in inputs.chunks(MUTATION_BATCH) {
12090                let mut variables = serde_json::Map::new();
12091                for slot in 0..MUTATION_BATCH {
12092                    variables.insert(
12093                        format!("create{slot}"),
12094                        chunk.get(slot).cloned().unwrap_or_else(|| chunk[0].clone()),
12095                    );
12096                    variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12097                }
12098                let data = match self
12099                    .graphql(graphql::CREATE_ISSUES, Value::Object(variables))
12100                    .await
12101                {
12102                    Ok(data) => data,
12103                    Err(error) => break 'create Some(error),
12104                };
12105                let mut refusal = data.get(ANSWER_ERRORS).map(|errors| {
12106                    let said: Vec<&str> = errors
12107                        .as_array()
12108                        .into_iter()
12109                        .flatten()
12110                        .filter_map(|error| error.get("message").and_then(Value::as_str))
12111                        .collect();
12112                    SourceError::Refused {
12113                        message: if said.is_empty() {
12114                            "GitHub returned GraphQL errors".to_owned()
12115                        } else {
12116                            said.join("; ")
12117                        },
12118                    }
12119                });
12120                for (slot, input) in chunk.iter().enumerate() {
12121                    match data
12122                        .pointer(&format!("/create{slot}/issue"))
12123                        .filter(|value| !value.is_null())
12124                    {
12125                        Some(created) => match self.created_landed(created).await {
12126                            Ok(landed_one) => {
12127                                landed.push(landed_one);
12128                                // Taken back with the rest, as any refusal here is.
12129                                if let Err(error) = self.assigned_as_asked(input, Some(created)) {
12130                                    refusal.get_or_insert(error);
12131                                }
12132                            }
12133                            Err(error) => {
12134                                refusal.get_or_insert(error);
12135                            }
12136                        },
12137                        // An alias GitHub refused answers nothing, and the refusal says why.
12138                        None => {
12139                            refusal.get_or_insert(SourceError::Malformed {
12140                                message: "GitHub issue creation returned no issue".into(),
12141                            });
12142                        }
12143                    }
12144                }
12145                if let Some(error) = refusal {
12146                    break 'create Some(error);
12147                }
12148            }
12149            None
12150        };
12151        if let Some(error) = refused {
12152            // None of these ids reaches the caller, so an issue GitHub will not take back is
12153            // named here or by nobody.
12154            let ids: Vec<&NativeId> = landed.iter().map(|created| &created.content_id).collect();
12155            let left = self.delete_issues(&ids).await;
12156            let left: Vec<&str> = left.iter().map(|id| id.0.as_str()).collect();
12157            return Err(left_behind(error, &left));
12158        }
12159        let created: Vec<NativeId> = landed
12160            .iter()
12161            .map(|landed| landed.content_id.clone())
12162            .collect();
12163        let mut ids = Vec::with_capacity(landed.len());
12164        for ((incoming, prepared), landed) in incomings.iter().zip(prepared).zip(landed) {
12165            match self.complete_write(incoming, prepared, landed).await {
12166                Ok(written) => ids.push(written.id),
12167                // 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.
12168                Err(error) => {
12169                    let ids: Vec<&NativeId> = created.iter().collect();
12170                    let left = self.delete_issues(&ids).await;
12171                    let left: Vec<&str> = left.iter().map(|id| id.0.as_str()).collect();
12172                    return Err(left_behind(error, &left));
12173                }
12174            }
12175        }
12176        Ok(ids)
12177    }
12178
12179    /// Hold back the update of the existing issue `issue` — `members`, what its own
12180    /// [`graphql::UPDATE_ISSUE`] would send beside its id — while writes are being held back — so the updates a copy makes one after
12181    /// another go to GitHub as one request. Whatever this source held of the issue is dropped
12182    /// as the mutation itself would drop it. Answers whether it was held: never while a write
12183    /// the store's cache expects runs, which records each mutation's own answer, and never for
12184    /// an issue an update is already held for, which that one is sent ahead of.
12185    fn hold_update(&self, issue: &NativeId, members: &Value) -> Result<bool, SourceError> {
12186        if self.expected.journaling() || self.deferred()?.is_none() {
12187            return Ok(false);
12188        }
12189        let mut held = self
12190            .held_updates
12191            .lock()
12192            .map_err(|_| SourceError::Unavailable {
12193                message: "issue updates held back were left inconsistent; run the command again"
12194                    .into(),
12195            })?;
12196        if held.iter().any(|earlier| earlier.issue == *issue) {
12197            return Ok(false);
12198        }
12199        let named = |value: &str| issue.0 == value;
12200        self.resolved_cache()?
12201            .retain(|id, item| !named(&id.0) && !named(&item.item_id));
12202        self.read_ahead()?.retain(|id, item| {
12203            !named(&id.0) && !item.as_ref().is_some_and(|item| named(&item.item_id))
12204        });
12205        self.carried()?
12206            .retain(|id, item| !named(&id.0) && !named(&item.item_id));
12207        held.push(HeldUpdate::new(issue, members));
12208        Ok(true)
12209    }
12210
12211    /// Send every update [`Self::hold_update`] held back: one alone as [`graphql::UPDATE_ISSUE`]
12212    /// sends it, several as aliased `updateIssue`s of [`graphql::UPDATE_ISSUES`],
12213    /// [`MUTATION_BATCH`] to a request. Each counts one write, as it would alone.
12214    async fn send_held_updates(&self) -> Result<(), SourceError> {
12215        let held = std::mem::take(&mut *self.held_updates.lock().map_err(|_| {
12216            SourceError::Unavailable {
12217                message: "issue updates held back were left inconsistent; run the command again"
12218                    .into(),
12219            }
12220        })?);
12221        if let [one] = held.as_slice() {
12222            return self
12223                .send_update(
12224                    graphql::UPDATE_ISSUE,
12225                    "/updateIssue/issue",
12226                    &one.issue,
12227                    one.input.clone(),
12228                )
12229                .await;
12230        }
12231        for chunk in held.chunks(MUTATION_BATCH) {
12232            let mut variables = serde_json::Map::new();
12233            for slot in 0..MUTATION_BATCH {
12234                variables.insert(
12235                    format!("update{slot}"),
12236                    chunk.get(slot).unwrap_or(&chunk[0]).input.clone(),
12237                );
12238                variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12239            }
12240            let data = match self
12241                .graphql(graphql::UPDATE_ISSUES, Value::Object(variables))
12242                .await
12243            {
12244                Ok(data) => data,
12245                Err(error) => {
12246                    for held in chunk {
12247                        self.forget_people(&held.input);
12248                    }
12249                    return Err(error);
12250                }
12251            };
12252            let inputs: Vec<&Value> = chunk.iter().map(|held| &held.input).collect();
12253            check_aliased_answers(
12254                graphql::UPDATE_ISSUES,
12255                &data,
12256                "update",
12257                &inputs,
12258                &[("issue", "id")],
12259            )?;
12260            for (slot, held) in chunk.iter().enumerate() {
12261                self.assigned_as_asked(&held.input, data.pointer(&format!("/update{slot}/issue")))?;
12262            }
12263        }
12264        Ok(())
12265    }
12266
12267    /// Send everything held back since [`TaskSource::begin_deferred_writes`]: one read of the
12268    /// created items' board items, then their field values and edges together in requests of
12269    /// [`WRITE_BATCH`], then their closes in requests of [`MUTATION_BATCH`]. Anything refused
12270    /// takes back every issue held, [`DELETE_BATCH`] to a request, and answers the refusal.
12271    async fn send_held_back(&self) -> Result<(), SourceError> {
12272        let Some(Deferred::Held { board, created }) = self.deferred()?.take() else {
12273            return Ok(());
12274        };
12275        if created.is_empty() {
12276            return Ok(());
12277        }
12278        let sent = self.send_deferred(board.as_str(), &created).await;
12279        if let Err(error) = sent {
12280            // Best effort, and the failure is what the caller is told, as a write of one item
12281            // that fails part way takes back what it created: the copy that held these back
12282            // journalled every one, so one this cannot take back its undo tries again, and says
12283            // so when it cannot either.
12284            let ids: Vec<&NativeId> = created.iter().map(|held| &held.content).collect();
12285            let _ = self.delete_issues(&ids).await;
12286            return Err(error);
12287        }
12288        Ok(())
12289    }
12290
12291    /// The requests [`Self::send_held_back`] makes.
12292    async fn send_deferred(&self, board: &str, created: &[HeldBack]) -> Result<(), SourceError> {
12293        let items = self.created_board_items(board, created).await?;
12294        let mut fields: Vec<Value> = Vec::new();
12295        let mut closes: Vec<Value> = Vec::new();
12296        let mut edges: Vec<Value> = Vec::new();
12297        for held in created {
12298            let (item, status) = &items[&held.content];
12299            let mut values = held.fields.clone();
12300            // A status the board already shows — set by a workflow a person turned on to file
12301            // new items at it — is not written again.
12302            if let Some((field, option, name)) = &held.status
12303                && status.as_deref() != Some(name.as_str())
12304            {
12305                values.insert(0, (field.clone(), json!({"singleSelectOptionId": option})));
12306            }
12307            for (field, value) in values {
12308                fields.push(json!({"projectId":board,"itemId":item,"fieldId":field,"value":value}));
12309            }
12310            if let Some(reason) = held.close {
12311                closes.push(json!({"id": held.content.0, "stateInput": closed_input(reason)}));
12312            }
12313            for far in &held.edges {
12314                edges.push(json!({"issueId": held.content.0, "blockingIssueId": far.0}));
12315            }
12316            if !held.clears.is_empty() {
12317                let clears: Vec<&str> = held.clears.iter().map(String::as_str).collect();
12318                self.set_item_fields(board, item, &[], &clears).await?;
12319            }
12320        }
12321        // Each alias answers with what it wrote, which is what its input named: the board item a
12322        // field value is set on, the issue closed, the issue blocked and the one blocking it.
12323        let field_answer: &[(&str, &str)] = &[("projectV2Item", "itemId")];
12324        let close_answer: &[(&str, &str)] = &[("issue", "id")];
12325        let block_answer: &[(&str, &str)] =
12326            &[("issue", "issueId"), ("blockingIssue", "blockingIssueId")];
12327        // Every field value, then every edge, as one ordered list sent `WRITE_BATCH` aliases to a
12328        // request: a request holding both kinds is the one document carrying both, so a plan's
12329        // values and edges cost one request where they fit in one.
12330        let writes: Vec<HeldWrite<'_>> = fields
12331            .iter()
12332            .map(HeldWrite::Field)
12333            .chain(edges.iter().map(HeldWrite::Edge))
12334            .collect();
12335        for chunk in writes.chunks(WRITE_BATCH) {
12336            let values: Vec<&Value> = chunk
12337                .iter()
12338                .filter_map(|write| match write {
12339                    HeldWrite::Field(input) => Some(*input),
12340                    HeldWrite::Edge(_) => None,
12341                })
12342                .collect();
12343            let blocks: Vec<&Value> = chunk
12344                .iter()
12345                .filter_map(|write| match write {
12346                    HeldWrite::Edge(input) => Some(*input),
12347                    HeldWrite::Field(_) => None,
12348                })
12349                .collect();
12350            let (document, sends) = match (values.is_empty(), blocks.is_empty()) {
12351                (false, false) => (graphql::WRITE_FIELDS_AND_EDGES, ["sendField", "sendBlock"]),
12352                (false, true) => (graphql::WRITE_FIELD_VALUES, ["send", "send"]),
12353                _ => (graphql::ADD_BLOCKED_BYS, ["send", "send"]),
12354            };
12355            let mut variables = serde_json::Map::new();
12356            let kinds = [
12357                ("field", &values, sends[0], field_answer),
12358                ("block", &blocks, sends[1], block_answer),
12359            ];
12360            for (prefix, inputs, send, _) in &kinds {
12361                if inputs.is_empty() {
12362                    continue;
12363                }
12364                for slot in 0..WRITE_BATCH {
12365                    variables.insert(
12366                        format!("{prefix}{slot}"),
12367                        (*inputs.get(slot).unwrap_or(&inputs[0])).clone(),
12368                    );
12369                    variables.insert(format!("{send}{slot}"), json!(slot < inputs.len()));
12370                }
12371            }
12372            let data = self.graphql(document, Value::Object(variables)).await?;
12373            for (prefix, inputs, _, answers) in kinds {
12374                check_aliased_answers(document, &data, prefix, inputs, answers)?;
12375            }
12376        }
12377        for chunk in closes.chunks(MUTATION_BATCH) {
12378            let mut variables = serde_json::Map::new();
12379            for slot in 0..MUTATION_BATCH {
12380                variables.insert(
12381                    format!("close{slot}"),
12382                    chunk.get(slot).cloned().unwrap_or_else(|| chunk[0].clone()),
12383                );
12384                variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12385            }
12386            let data = self
12387                .graphql(graphql::CLOSE_ISSUES, Value::Object(variables))
12388                .await?;
12389            let inputs: Vec<&Value> = chunk.iter().collect();
12390            check_aliased_answers(graphql::CLOSE_ISSUES, &data, "close", &inputs, close_answer)?;
12391        }
12392        for held in created {
12393            self.learn_item(&held.content, &items[&held.content].0)?;
12394        }
12395        Ok(())
12396    }
12397
12398    /// The board item each of `created` is on this board, with its `Status` as the board set it:
12399    /// [`graphql::CREATED_BOARD_ITEMS`], read again — after a wait of a second, then two, four,
12400    /// eight and sixteen — for only those GitHub has not filed yet.
12401    ///
12402    /// **Membership is never assumed.** `createIssue`'s `projectV2Ids` files an issue some time
12403    /// after GitHub answered the create — the feasibility spike saw 0.45 to 1.84 seconds, and no
12404    /// create answer carrying the item — so only a read says it is there. One still absent once
12405    /// those reads are spent is filed with [`graphql::ADD_TO_BOARD`], one write each; GitHub
12406    /// filing it meanwhile refuses that "Content already exists in this project", which says it
12407    /// is placed, and one more read finds the item rather than a second one being made.
12408    async fn created_board_items(
12409        &self,
12410        board: &str,
12411        created: &[HeldBack],
12412    ) -> Result<BTreeMap<NativeId, (String, Option<String>)>, SourceError> {
12413        let mut found: BTreeMap<NativeId, (String, Option<String>)> = BTreeMap::new();
12414        let unfiled = |found: &BTreeMap<NativeId, (String, Option<String>)>| -> Vec<NativeId> {
12415            created
12416                .iter()
12417                .map(|held| held.content.clone())
12418                .filter(|id| !found.contains_key(id))
12419                .collect()
12420        };
12421        let mut wait = Duration::from_secs(1);
12422        for attempt in 0..6 {
12423            let absent = unfiled(&found);
12424            if absent.is_empty() {
12425                return Ok(found);
12426            }
12427            if attempt > 0 {
12428                self.clock
12429                    .sleep_because(wait, pacing::cause::BOARD_FILING)
12430                    .await;
12431                wait = wait.saturating_mul(2);
12432            }
12433            self.read_created_items(board, &absent, &mut found).await?;
12434        }
12435        let mut placed_meanwhile = Vec::new();
12436        for id in unfiled(&found) {
12437            match self
12438                .graphql(
12439                    graphql::ADD_TO_BOARD,
12440                    json!({"input":{"projectId":board,"contentId":id.0}}),
12441                )
12442                .await
12443            {
12444                Ok(added) => {
12445                    let item = added
12446                        .pointer("/addProjectV2ItemById/item")
12447                        .filter(|value| !value.is_null())
12448                        .ok_or_else(|| SourceError::Malformed {
12449                            message: "GitHub board addition returned no project item".into(),
12450                        })?;
12451                    found.insert(id, (required_nonblank_str(item, "id")?.to_owned(), None));
12452                }
12453                Err(error) if already_on_the_board(&error) => placed_meanwhile.push(id),
12454                Err(error) => return Err(error),
12455            }
12456        }
12457        if !placed_meanwhile.is_empty() {
12458            self.read_created_items(board, &placed_meanwhile, &mut found)
12459                .await?;
12460        }
12461        let absent = unfiled(&found);
12462        if absent.is_empty() {
12463            return Ok(found);
12464        }
12465        let absent: Vec<&str> = absent.iter().map(|id| id.0.as_str()).collect();
12466        Err(SourceError::Unavailable {
12467            message: format!(
12468                "GitHub created {} filed on board {board} and, after 31 seconds and adding {} \
12469                 to it, still answers {} on no item of it: {}; next: run the copy again once \
12470                 GitHub has caught up",
12471                if absent.len() == 1 {
12472                    "an issue"
12473                } else {
12474                    "issues"
12475                },
12476                if absent.len() == 1 { "it" } else { "them" },
12477                if absent.len() == 1 { "it" } else { "them" },
12478                absent.join(", ")
12479            ),
12480        })
12481    }
12482
12483    /// One [`graphql::CREATED_BOARD_ITEMS`] read of each of `ids`, [`COPY_DETAIL_BATCH`] to a
12484    /// request, adding to `found` the board item of every one GitHub has filed on `board`.
12485    async fn read_created_items(
12486        &self,
12487        board: &str,
12488        ids: &[NativeId],
12489        found: &mut BTreeMap<NativeId, (String, Option<String>)>,
12490    ) -> Result<(), SourceError> {
12491        for chunk in ids.chunks(COPY_DETAIL_BATCH) {
12492            let mut variables = serde_json::Map::new();
12493            for slot in 0..COPY_DETAIL_BATCH {
12494                variables.insert(
12495                    format!("id{slot}"),
12496                    json!(chunk.get(slot).unwrap_or(&chunk[0]).0),
12497                );
12498                variables.insert(format!("read{slot}"), json!(slot < chunk.len()));
12499            }
12500            variables.insert("boardItems".into(), json!(BOARD_ITEMS_PAGE_SIZE));
12501            variables.insert("statusName".into(), json!(STATUS_FIELD));
12502            let data = self
12503                .graphql(graphql::CREATED_BOARD_ITEMS, Value::Object(variables))
12504                .await?;
12505            for (slot, id) in chunk.iter().enumerate() {
12506                // An answer for another issue than the one asked about says nothing of
12507                // where that one is filed, and its board item is not this one's.
12508                let node = data.get(format!("i{slot}")).filter(|node| !node.is_null());
12509                let named = node.map(|node| node.get("id").and_then(Value::as_str));
12510                if let Some(named) = named
12511                    && named != Some(id.0.as_str())
12512                {
12513                    return Err(SourceError::Malformed {
12514                        message: format!(
12515                            "GitHub answered the board items of {} when asked for those of {}",
12516                            named.unwrap_or("an issue it did not name"),
12517                            id.0
12518                        ),
12519                    });
12520                }
12521                // An issue GitHub does not answer yet is not filed yet; one it answers is
12522                // read whole, its connection, each board item's board and its status, and
12523                // any of them unreadable is refused rather than read as not filed.
12524                let Some(node) = node else { continue };
12525                let malformed = |what: &str| SourceError::Malformed {
12526                    message: format!("GitHub answered the board items of {} with {what}", id.0),
12527                };
12528                let nodes = node
12529                    .pointer("/projectItems/nodes")
12530                    .and_then(Value::as_array)
12531                    .ok_or_else(|| malformed("no list of board items"))?;
12532                let mut item = None;
12533                for node in nodes {
12534                    let on = node
12535                        .pointer("/project/id")
12536                        .and_then(Value::as_str)
12537                        .ok_or_else(|| malformed("a board item naming no board"))?;
12538                    if on == board {
12539                        item = Some(node);
12540                    }
12541                }
12542                if let Some(item) = item {
12543                    let status = match item.get("status") {
12544                        None | Some(Value::Null) => None,
12545                        Some(status) => Some(
12546                            status
12547                                .get("name")
12548                                .and_then(Value::as_str)
12549                                .ok_or_else(|| malformed("a status that names no option"))?
12550                                .to_owned(),
12551                        ),
12552                    };
12553                    found.insert(
12554                        id.clone(),
12555                        (required_nonblank_str(item, "id")?.to_owned(), status),
12556                    );
12557                }
12558            }
12559        }
12560        Ok(())
12561    }
12562
12563    /// The board item id of `content`, which this process created and remembered without one,
12564    /// in every half of its own view.
12565    fn learn_item(&self, content: &NativeId, item: &str) -> Result<(), SourceError> {
12566        if let Some(held) = self.resolved_cache()?.get_mut(content) {
12567            held.item_id = item.to_owned();
12568        }
12569        if let Some(held) = self.created()?.iter_mut().find(|held| held.id == *content) {
12570            held.item_id = item.to_owned();
12571        }
12572        Ok(())
12573    }
12574
12575    /// Ask together which items each of `origins` names, and what creating an item reads; see
12576    /// [`TaskSource::read_ahead_origins_for_copy`]. An origin whose answer runs past its first
12577    /// page is left to its own lookup.
12578    async fn origins_ahead(&self, origins: &[String]) -> Result<(), SourceError> {
12579        if self.repository.is_none() {
12580            return Ok(());
12581        }
12582        let unasked: Vec<&String> = {
12583            let held = self.narrowed_cache()?;
12584            let mut unasked: Vec<&String> = Vec::new();
12585            for origin in origins {
12586                if !held.contains_key(&Narrowing::Origin(origin.clone()).key())
12587                    && !unasked.contains(&origin)
12588                {
12589                    unasked.push(origin);
12590                }
12591            }
12592            unasked
12593        };
12594        if unasked.is_empty() {
12595            return Ok(());
12596        }
12597        // One batch is held back for the read ahead that follows, which may carry a project's
12598        // members beside it in the same request.
12599        if unasked.len() <= ORIGIN_BATCH {
12600            let mut pending =
12601                self.pending_origins
12602                    .lock()
12603                    .map_err(|_| SourceError::Unavailable {
12604                        message:
12605                            "origins held for a read ahead were left inconsistent; run the command \
12606                          again"
12607                                .into(),
12608                    })?;
12609            for origin in unasked {
12610                if !pending.contains(origin) {
12611                    pending.push(origin.clone());
12612                }
12613            }
12614            return Ok(());
12615        }
12616        let unasked: Vec<String> = unasked.into_iter().cloned().collect();
12617        self.send_origin_lookups(&unasked, None).await
12618    }
12619
12620    /// Hold, for [`TaskSource::member_classifications`] of `project`, each member's
12621    /// classification and repositories as the members page `data` carries them — when that page
12622    /// is every member, each one names `project` as its parent, and every record it holds is
12623    /// readable. Any other page holds nothing, so the members are read as they always were.
12624    fn hold_member_classes(&self, project: &NativeId, data: &Value) -> Result<(), SourceError> {
12625        let Some(page) = data
12626            .pointer("/members/subIssues")
12627            .filter(|page| !page.is_null())
12628        else {
12629            return Ok(());
12630        };
12631        if page
12632            .pointer("/pageInfo/hasNextPage")
12633            .and_then(Value::as_bool)
12634            != Some(false)
12635        {
12636            return Ok(());
12637        }
12638        let Some(nodes) = page.get("nodes").and_then(Value::as_array) else {
12639            return Ok(());
12640        };
12641        let mut members = Vec::with_capacity(nodes.len());
12642        for node in nodes {
12643            if node.pointer("/parent/id").and_then(Value::as_str) != Some(project.0.as_str()) {
12644                return Ok(());
12645            }
12646            let Some(body) = node.get("body").and_then(Value::as_str) else {
12647                return Ok(());
12648            };
12649            // Every node here is filed under `project`, which `BoardKind::of` reads as one of its
12650            // tasks whatever its marker says, so each is a member the full read would classify.
12651            let Ok((_, slot)) = metadata_body(Some(body.to_owned())) else {
12652                return Ok(());
12653            };
12654            let Ok(classification) = Classification::from_metadata(&slot) else {
12655                return Ok(());
12656            };
12657            let repositories = if slot.contains_key(Repository::METADATA_KEY) {
12658                let Ok(repositories) = Repository::from_metadata(&slot) else {
12659                    return Ok(());
12660                };
12661                repositories
12662            } else {
12663                let Some(origin) = node
12664                    .pointer("/repository/nameWithOwner")
12665                    .and_then(Value::as_str)
12666                else {
12667                    return Ok(());
12668                };
12669                let Ok(own) = Repository::try_from(format!("{}/{origin}", RepositoryTarget::HOST))
12670                else {
12671                    return Ok(());
12672                };
12673                vec![own]
12674            };
12675            members.push((classification, repositories));
12676        }
12677        self.member_classes
12678            .lock()
12679            .map_err(|_| SourceError::Unavailable {
12680                message: "a project's members held for its classification were left \
12681                          inconsistent; run the command again"
12682                    .into(),
12683            })?
12684            .insert(project.clone(), members);
12685        Ok(())
12686    }
12687
12688    /// Send every origin held back for the read ahead, beside the members of `members` when it
12689    /// names a project — or nothing, when none is held.
12690    async fn send_pending_origins(&self, members: Option<&NativeId>) -> Result<(), SourceError> {
12691        let pending = std::mem::take(&mut *self.pending_origins.lock().map_err(|_| {
12692            SourceError::Unavailable {
12693                message: "origins held for a read ahead were left inconsistent; run the command \
12694                          again"
12695                    .into(),
12696            }
12697        })?);
12698        if pending.is_empty() {
12699            return Ok(());
12700        }
12701        self.send_origin_lookups(&pending, members).await
12702    }
12703
12704    /// [`graphql::ORIGIN_LOOKUPS`] of `unasked`, [`ORIGIN_BATCH`] to a request — the first one
12705    /// [`graphql::ORIGIN_LOOKUPS_WITH_MEMBERS`], carrying the members of `members`, when it names
12706    /// a project — holding each origin's answer and, from a members page that is the whole of
12707    /// them, each member's classification.
12708    async fn send_origin_lookups(
12709        &self,
12710        unasked: &[String],
12711        members: Option<&NativeId>,
12712    ) -> Result<(), SourceError> {
12713        let Some(repository) = self.repository.clone() else {
12714            return Ok(());
12715        };
12716        let mut members = members;
12717        for chunk in unasked.chunks(ORIGIN_BATCH) {
12718            let mut variables = json!({"owner":self.owner,"number":self.project_number,
12719                "type":"ISSUE","lookupFirst":ORIGIN_LOOKUPS_PAGE_SIZE,"nestedFirst":NESTED_PAGE_SIZE,
12720                "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true,
12721                "repositoryOwner":repository.owner,"repositoryName":repository.name});
12722            for slot in 0..ORIGIN_BATCH {
12723                let origin = chunk.get(slot).unwrap_or(&chunk[0]);
12724                variables[format!("filter{slot}")] =
12725                    json!(format!("{ORIGIN_FIELD}:{}", quoted(origin)));
12726                variables[format!("search{slot}")] = json!(
12727                    self.board_search(Some(&format!("in:body {}", quoted(&as_stored(origin)))))
12728                );
12729                variables[format!("ask{slot}")] = json!(slot < chunk.len());
12730            }
12731            let project = members.take();
12732            let document = match project {
12733                Some(project) => {
12734                    variables["project"] = json!(project.0);
12735                    variables["memberFirst"] = json!(MEMBER_PAGE_SIZE);
12736                    graphql::ORIGIN_LOOKUPS_WITH_MEMBERS
12737                }
12738                None => graphql::ORIGIN_LOOKUPS,
12739            };
12740            let data = self.graphql(document, variables).await?;
12741            self.fields_read(&data)?;
12742            if let Some(project) = project {
12743                self.hold_member_classes(project, &data)?;
12744            }
12745            if let Some(node) = data.get("repository").filter(|value| !value.is_null()) {
12746                let id = required_nonblank_str(node, "id")?.to_owned();
12747                self.repository_cache()?.insert(repository.clone(), id);
12748                if let Some(numeric) = node
12749                    .get("databaseId")
12750                    .and_then(Value::as_u64)
12751                    .and_then(std::num::NonZeroU64::new)
12752                {
12753                    self.numeric_repositories
12754                        .lock()
12755                        .await
12756                        .insert(repository.clone(), numeric);
12757                }
12758            }
12759            for (slot, origin) in chunk.iter().enumerate() {
12760                let items = data
12761                    .pointer(&format!("/o{slot}/projectV2/items"))
12762                    .filter(|value| !value.is_null())
12763                    .ok_or_else(|| SourceError::Refused {
12764                        message: format!(
12765                            "GitHub project {}/{} was not found or is not visible to the token",
12766                            self.owner, self.project_number
12767                        ),
12768                    })?;
12769                let searched =
12770                    data.get(format!("s{slot}"))
12771                        .ok_or_else(|| SourceError::Malformed {
12772                            message: "GitHub search response has no search connection".into(),
12773                        })?;
12774                if resumed(items, None)?.has_more() || resumed(searched, None)?.has_more() {
12775                    continue;
12776                }
12777                let mut found: Vec<Resolved> = Vec::new();
12778                for item in optional_nodes(Some(items), "project items")?
12779                    .into_iter()
12780                    .flatten()
12781                {
12782                    if let Some(resolved) = self.resolve(item)?
12783                        && resolved.content_kind == ContentKind::Issue
12784                        && !found.iter().any(|held| held.id == resolved.id)
12785                    {
12786                        found.push(resolved);
12787                    }
12788                }
12789                for node in optional_nodes(Some(searched), "search")?
12790                    .into_iter()
12791                    .flatten()
12792                {
12793                    if let Some(resolved) = self.resolve_issue(node).await?
12794                        && !found.iter().any(|held| held.id == resolved.id)
12795                    {
12796                        found.push(resolved);
12797                    }
12798                }
12799                self.narrowed_cache()?
12800                    .insert(Narrowing::Origin((*origin).clone()).key(), found);
12801            }
12802        }
12803        Ok(())
12804    }
12805
12806    /// Delete every issue of `ids`, [`DELETE_BATCH`] to a request with
12807    /// [`graphql::DELETE_ISSUES`], and answer those still there: each a request's answer does not
12808    /// confirm, every one of a request refused whole included.
12809    async fn delete_issues(&self, ids: &[&NativeId]) -> Vec<NativeId> {
12810        let mut left = Vec::new();
12811        for chunk in ids.chunks(DELETE_BATCH) {
12812            let mut variables = serde_json::Map::new();
12813            for slot in 0..DELETE_BATCH {
12814                let id = chunk.get(slot).unwrap_or(&chunk[0]);
12815                variables.insert(format!("delete{slot}"), json!({"issueId": id.0}));
12816                variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12817            }
12818            let data = self
12819                .graphql(graphql::DELETE_ISSUES, Value::Object(variables))
12820                .await
12821                .unwrap_or(Value::Null);
12822            for (slot, id) in chunk.iter().enumerate() {
12823                // Confirmed only by the repository the deleted issue was in, named by a
12824                // non-blank id: anything else says nothing of whether the issue is gone.
12825                let confirmed = data
12826                    .pointer(&format!("/delete{slot}/repository/id"))
12827                    .and_then(Value::as_str)
12828                    .is_some_and(|id| !id.trim().is_empty());
12829                if !confirmed {
12830                    left.push((*id).clone());
12831                }
12832            }
12833        }
12834        left
12835    }
12836
12837    /// Delete one issue, which takes its board item with it.
12838    async fn delete_issue(&self, id: &NativeId) -> Result<(), SourceError> {
12839        let data = self
12840            .graphql(graphql::DELETE_ISSUE, json!({"input":{"issueId":id.0}}))
12841            .await?;
12842        data.pointer("/deleteIssue/repository")
12843            .filter(|value| !value.is_null())
12844            .ok_or_else(|| SourceError::Malformed {
12845                message: "GitHub issue deletion returned no repository".into(),
12846            })?;
12847        self.forget(id)?;
12848        Ok(())
12849    }
12850
12851    /// Remove one item this copy created, so a copy that could not finish leaves the board
12852    /// as it found it.
12853    ///
12854    /// Deleting the issue takes its board item with it, so there is no second mutation to
12855    /// keep in step. An id the board does not hold is not an error: the item is already
12856    /// gone, which is the state this asks for. Which that is, is decided by reading the item
12857    /// by its own id — a listing of the board can still be missing an item it holds, and
12858    /// reading that as *already gone* would leave behind the very item this was asked to
12859    /// take back.
12860    async fn delete_item(&self, id: &NativeId) -> Result<(), SourceError> {
12861        let Some(item) = self.bound_item(id).await? else {
12862            return Ok(());
12863        };
12864        if item.content_kind == ContentKind::DraftIssue {
12865            return Err(SourceError::Refused {
12866                message: format!(
12867                    "GitHub item {} is a draft, and this source removes an item by deleting \
12868                     its issue; next: remove it from the board by hand",
12869                    id.0
12870                ),
12871            });
12872        }
12873        let data = self
12874            .graphql(graphql::DELETE_ISSUE, json!({"input":{"issueId":id.0}}))
12875            .await?;
12876        data.pointer("/deleteIssue/repository")
12877            .filter(|value| !value.is_null())
12878            .ok_or_else(|| SourceError::Malformed {
12879                message: "GitHub issue deletion returned no repository".into(),
12880            })?;
12881        self.forget(id)?;
12882        Ok(())
12883    }
12884
12885    /// The issue a comment call on `task` is about, or `None` when this board holds no such
12886    /// task.
12887    ///
12888    /// Resolved exactly as [`TaskSource::get_task`] resolves it, so the comment verbs and a
12889    /// read of the task cannot disagree about which ids name one: a project or a document of
12890    /// this board is not a task here either.
12891    ///
12892    /// A **draft** is a task with nowhere to keep a comment, because GitHub keeps comments on
12893    /// issues and a draft is not one. It is refused rather than answered with an empty page,
12894    /// which would read as a task nobody has commented on yet.
12895    async fn commented_issue(&self, task: &NativeId) -> Result<Option<NativeId>, SourceError> {
12896        let cached = self.resolved_cache()?.get(task).cloned();
12897        let Some(item) = (match cached {
12898            Some(item) => Some(item),
12899            None => self.item_by_id(task).await?,
12900        })
12901        .filter(|item| item.kind == BoardKind::Work(ItemKind::Task)) else {
12902            return Ok(None);
12903        };
12904        if item.content_kind == ContentKind::DraftIssue {
12905            return Err(self.draft_has_no_comments(task));
12906        }
12907        Ok(Some(item.id))
12908    }
12909
12910    /// The refusal a comment call on a board draft is answered with: GitHub keeps comments on
12911    /// issues, and a draft is not one.
12912    fn draft_has_no_comments(&self, task: &NativeId) -> SourceError {
12913        SourceError::Refused {
12914            message: format!(
12915                "task {} of source {} is a draft item on the board, and GitHub keeps \
12916                 comments on issues alone, so a draft has none to read or write; next: \
12917                 convert the draft to an issue on the board, then comment on the issue it \
12918                 becomes",
12919                task.0, self.name
12920            ),
12921        }
12922    }
12923
12924    /// One task and a page of its comments, read with [`graphql::ISSUE_DETAIL`] in one
12925    /// request — or `None` when this board holds no task by that id.
12926    ///
12927    /// What `task show` and a comment listing read. A draft is a task with no comments, so it
12928    /// is answered with the draft and the refusal, at the price of the draft's own read.
12929    async fn issue_detail(
12930        &self,
12931        id: &NativeId,
12932        page: &PageRequest,
12933    ) -> Result<Option<TaskDetailRead>, SourceError> {
12934        let after = page.cursor.as_ref().map(|cursor| cursor.0.as_str());
12935        let asked = self
12936            .graphql(
12937                graphql::ISSUE_DETAIL,
12938                json!({"id":id.0,"first":page.limit.min(MAX_PAGE_SIZE),"after":after,
12939                       "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
12940                       "duplicates":true}),
12941            )
12942            .await;
12943        let data = match asked {
12944            Ok(data) => data,
12945            Err(error) if unresolvable_node(&error) => return Ok(None),
12946            Err(error) => return Err(error),
12947        };
12948        // `node` is null for an id that names nothing, and absent only from an answer this
12949        // source cannot read — never the same thing.
12950        let node = data.get("node").ok_or_else(|| SourceError::Malformed {
12951            message: format!("GitHub answered the read of {} with no node", id.0),
12952        })?;
12953        self.detail_of(id, node, true, after).await
12954    }
12955
12956    /// Several tasks, each with the first page of its comments when `comments` is set, read
12957    /// [`DETAIL_BATCH`] at a time with [`graphql::ISSUE_DETAILS`] — one answer per id, in
12958    /// order.
12959    ///
12960    /// A batch GitHub refuses because one of its ids resolves to no node at all is read again
12961    /// one item at a time, so that id is answered as missing and the others as themselves; any
12962    /// other refusal is every id of that batch's answer.
12963    async fn issue_details(
12964        &self,
12965        ids: &[NativeId],
12966        comments: Option<&PageRequest>,
12967    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
12968        let mut read = Vec::with_capacity(ids.len());
12969        for batch in ids.chunks(DETAIL_BATCH) {
12970            match self
12971                .graphql(graphql::ISSUE_DETAILS, detail_batch(batch, comments))
12972                .await
12973            {
12974                Ok(data) => {
12975                    for (slot, id) in batch.iter().enumerate() {
12976                        // Every alias asked for is answered, null for an id naming nothing;
12977                        // one missing is an answer this source cannot read.
12978                        let read_one = match data.get(format!("i{slot}")) {
12979                            Some(node) => self.detail_of(id, node, comments.is_some(), None).await,
12980                            None => Err(SourceError::Malformed {
12981                                message: format!(
12982                                    "GitHub answered a batch read with no item for {}",
12983                                    id.0
12984                                ),
12985                            }),
12986                        };
12987                        read.push(read_one);
12988                    }
12989                }
12990                Err(error) if unresolvable_node(&error) => {
12991                    for id in batch {
12992                        read.push(match comments {
12993                            Some(page) => self.issue_detail(id, page).await,
12994                            None => self.task_read(id).await,
12995                        });
12996                    }
12997                }
12998                Err(error) => read.extend(batch.iter().map(|_| Err(error.clone()))),
12999            }
13000        }
13001        read
13002    }
13003
13004    /// One task and nothing of its comments, as [`TaskSource::get_task`] reads it.
13005    async fn task_read(&self, id: &NativeId) -> Result<Option<TaskDetailRead>, SourceError> {
13006        Ok(self.get_task(id).await?.map(|task| TaskDetailRead {
13007            task,
13008            comments: None,
13009        }))
13010    }
13011
13012    /// What one node a detail read reached says: the task this board holds by `id`, with the
13013    /// page of comments the node carries when `commented` — or `None` for a node that is no
13014    /// task of this board.
13015    ///
13016    /// Resolved as [`Self::item_by_id`] resolves an item: a draft is read again as a draft,
13017    /// and an item this process created answers from this process's own record, which a node
13018    /// read taken moments after the write can still be behind.
13019    async fn detail_of(
13020        &self,
13021        id: &NativeId,
13022        node: &Value,
13023        commented: bool,
13024        after: Option<&str>,
13025    ) -> Result<Option<TaskDetailRead>, SourceError> {
13026        if node.is_null() {
13027            return Ok(None);
13028        }
13029        let draft = optional_str(node, "__typename")? == Some("DraftIssue");
13030        // An issue answered under one id is that id's, or the answer is not one this source
13031        // can report: reporting another issue's task and comments under the qualified id asked
13032        // for would be the one wrong answer here. A draft's own read checks the same.
13033        if !draft
13034            && optional_str(node, "__typename")? == Some("Issue")
13035            && required_str(node, "id")? != id.0
13036        {
13037            return Err(SourceError::Malformed {
13038                message: format!(
13039                    "GitHub answered the read of {} with issue {}",
13040                    id.0,
13041                    required_str(node, "id")?
13042                ),
13043            });
13044        }
13045        let item = if draft {
13046            self.draft_by_id(id).await?
13047        } else {
13048            self.resolve_issue(node).await?
13049        };
13050        // A read that carried the whole of what the issue is blocked by — a copy's — is kept
13051        // for this command, so the dependency read the copy makes next is answered from it.
13052        if let Some(read) = item.as_ref().filter(|item| item.blocked_by.is_some()) {
13053            self.resolved_cache()?.insert(read.id.clone(), read.clone());
13054        }
13055        let Some(item) = item.filter(|item| item.kind == BoardKind::Work(ItemKind::Task)) else {
13056            return Ok(None);
13057        };
13058        let own = self.created()?.iter().find(|own| own.id == *id).cloned();
13059        let task = own.unwrap_or(item).task()?;
13060        let comments = match (commented, draft) {
13061            (false, _) => None,
13062            (true, true) => Some(Err(self.draft_has_no_comments(id))),
13063            (true, false) => Some(comment_page(node, &id.0, after).map(Some)),
13064        };
13065        if commented && !draft && after.is_none() {
13066            self.expected.learn_comments(id, node);
13067        }
13068        Ok(Some(TaskDetailRead { task, comments }))
13069    }
13070
13071    /// Whether the comment `comment` is one of `issue`'s own.
13072    ///
13073    /// Read before an edit or a removal is sent, because GitHub's comment mutations take the
13074    /// comment's id and nothing else: a comment id given against the wrong task would
13075    /// otherwise change a comment on some other issue entirely. An id that names nothing, or
13076    /// names something that is not an issue comment, is a comment this task does not have —
13077    /// which is what GitHub refusing to resolve it means too.
13078    async fn comment_is_on(
13079        &self,
13080        issue: &NativeId,
13081        comment: &NativeId,
13082    ) -> Result<bool, SourceError> {
13083        Ok(self.comment_on(issue, comment).await?.is_some())
13084    }
13085
13086    /// The body the comment `comment` holds, exactly as GitHub holds it, when it is one of
13087    /// `issue`'s own — the read [`Self::comment_is_on`] makes, answering with what it selected.
13088    async fn comment_on(
13089        &self,
13090        issue: &NativeId,
13091        comment: &NativeId,
13092    ) -> Result<Option<String>, SourceError> {
13093        // A write the store's cache expects knows which comments its issue held, and their
13094        // bodies, at the version it expects: what this read would answer.
13095        if let Some(primed) = self.expected.primed_comment(issue, comment) {
13096            return Ok(primed);
13097        }
13098        let asked = self
13099            .graphql(graphql::COMMENT_ISSUE, json!({"id":comment.0}))
13100            .await;
13101        let data = match asked {
13102            Ok(data) => data,
13103            Err(error) if unresolvable_node(&error) => return Ok(None),
13104            Err(error) => return Err(error),
13105        };
13106        let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
13107            return Ok(None);
13108        };
13109        if optional_str(node, "__typename")? != Some("IssueComment") {
13110            return Ok(None);
13111        }
13112        let on = node.get("issue").ok_or_else(|| SourceError::Malformed {
13113            message: format!("GitHub issue comment {} names no issue", comment.0),
13114        })?;
13115        if required_str(on, "id")? != issue.0 {
13116            return Ok(None);
13117        }
13118        Ok(Some(required_str(node, "body")?.to_owned()))
13119    }
13120
13121    /// Which far ends this item's own `blockedBy` relationship holds, and which it cannot.
13122    async fn partition_edges(
13123        &self,
13124        near_kind: BoardKind,
13125        near_content: ContentKind,
13126        carried: Option<&[Value]>,
13127        depends_on: &[DependencyEdge],
13128    ) -> Result<(Vec<String>, Vec<DependencyEdge>), SourceError> {
13129        let mut native = Vec::new();
13130        let mut fallback = Vec::new();
13131        let far_ends: Vec<(&DependencyEdge, &str, bool, Option<&Value>)> = depends_on
13132            .iter()
13133            .map(|edge| {
13134                // An opaque far end names another tracker, so it is never this board's own.
13135                let same_source = edge.to.designator().is_none()
13136                    && edge
13137                        .to
13138                        .source()
13139                        .is_none_or(|source| source == self.name.as_str());
13140                // A qualified id's source segment runs to its *first* colon — `GlobalId` and
13141                // `DependencyEndpoint::source` both read it that way — and a native id may hold
13142                // colons of its own, so the far end is everything after that one separator.
13143                // Splitting at the last would truncate `work:urn:task:7` to `7`.
13144                let far_id = if edge.to.is_qualified() {
13145                    edge.to
13146                        .id()
13147                        .split_once(':')
13148                        .map_or(edge.to.id(), |(_, native)| native)
13149                } else {
13150                    edge.to.id()
13151                };
13152                // One that already blocks the near issue was answered by that issue's own
13153                // read, which carried each of its blockers' kinds — an issue every one — so it
13154                // is not read again.
13155                let blocking = carried.and_then(|nodes| {
13156                    nodes
13157                        .iter()
13158                        .find(|node| node.get("id").and_then(Value::as_str) == Some(far_id))
13159                });
13160                (edge, far_id, same_source, blocking)
13161            })
13162            .collect();
13163        // Every other same-source far end is read by its own id, exactly as the item it is a
13164        // far end of is: whether this board holds it is that read's answer, never a listing's.
13165        // They are read together, [`DETAIL_BATCH`] to a request, rather than one each.
13166        let mut unread: Vec<NativeId> = Vec::new();
13167        for (_, far_id, same_source, blocking) in &far_ends {
13168            let id = NativeId((*far_id).to_owned());
13169            if *same_source && blocking.is_none() && !unread.contains(&id) {
13170                unread.push(id);
13171            }
13172        }
13173        let read: BTreeMap<NativeId, Option<Resolved>> = unread
13174            .iter()
13175            .cloned()
13176            .zip(self.items_by_ids(&unread).await?)
13177            .collect();
13178        for (edge, far_id, same_source, blocking) in far_ends {
13179            let far = match (same_source, blocking) {
13180                (false, _) => None,
13181                (true, Some(node)) => Some(FarEnd {
13182                    kind: if required_str(node, "title")?.starts_with(DESIGN_TITLE_PREFIX) {
13183                        BoardKind::Document
13184                    } else {
13185                        BoardKind::Work(related_kind(node, self.sub_issues)?)
13186                    },
13187                    content_kind: ContentKind::Issue,
13188                }),
13189                (true, None) => {
13190                    let read = read
13191                        .get(&NativeId(far_id.to_owned()))
13192                        .cloned()
13193                        .flatten()
13194                        .ok_or_else(|| SourceError::Refused {
13195                            message: format!("GitHub dependency item {far_id} was not found"),
13196                        })?;
13197                    Some(FarEnd {
13198                        kind: read.kind,
13199                        content_kind: read.content_kind,
13200                    })
13201                }
13202            };
13203            let far = far.as_ref();
13204            // The caller says which kind the far end is, and this board holds the far end
13205            // itself, so a disagreement is settled here rather than stored: recorded, the
13206            // wrong kind would read back as a cross-level edge that never existed; written
13207            // natively, it would name a relationship of a different level than the caller
13208            // asked for.
13209            //
13210            // A far end this board holds as a *document* fails the same comparison and is
13211            // refused by the same sentence: `ItemKind` has no document variant because
13212            // nothing may point at one, so no caller can name it correctly and the refusal
13213            // is the only honest answer.
13214            if let Some(disagreeing) = far.filter(|far| far.kind != BoardKind::Work(edge.to.kind)) {
13215                return Err(SourceError::Refused {
13216                    message: format!(
13217                        "GitHub dependency item {far_id} is a {} of this board, and this item \
13218                         names it as a {}; record the kind it is",
13219                        disagreeing.kind.describes(),
13220                        edge.to.kind.marker()
13221                    ),
13222                });
13223            }
13224            // A draft has neither `blockedBy` nor `blocking`, so no edge of one is native
13225            // however the far end is spelled — and one classified native here would be
13226            // written nowhere at all, because a draft's native reconciliation never runs.
13227            let native_here = near_content == ContentKind::Issue
13228                && far.is_some_and(|far| {
13229                    far.content_kind == ContentKind::Issue
13230                        && BoardKind::Work(edge.to.kind) == near_kind
13231                });
13232            if native_here {
13233                native.push(far_id.to_owned());
13234            } else {
13235                fallback.push(edge.clone());
13236            }
13237        }
13238        Ok((native, fallback))
13239    }
13240
13241    async fn update_existing(
13242        &self,
13243        item: &Resolved,
13244        incoming: &Incoming<'_>,
13245        body: &Option<String>,
13246        status_target: Option<&StatusTarget>,
13247    ) -> Result<(), SourceError> {
13248        let title = incoming.written_title();
13249        // A terminal status closes the issue here, in the same mutation as its body: its board
13250        // option was selected before this, so a close never lands on an item whose board cannot
13251        // show it.
13252        let mut fields = match item.content_kind {
13253            ContentKind::DraftIssue => json!({"title":title,"body":body}),
13254            ContentKind::Issue => json!({"title":title,"body":body,
13255                                         "stateInput":state_input(status_target)}),
13256        };
13257        // The people it is to be assigned to, replacing whoever it holds — sent only when they
13258        // are not exactly those, and looked up before anything of this write was sent.
13259        if let Some(people) = incoming.assignees
13260            && item
13261                .assignees
13262                .as_deref()
13263                .is_none_or(|held| !assignees::same_people(held, people))
13264        {
13265            if item.content_kind == ContentKind::DraftIssue {
13266                return Err(self.assigns_a_draft());
13267            }
13268            fields["assigneeIds"] = json!(self.people_ids(people, &item.written_name())?);
13269        }
13270        // Only the members whose value differs from the item as this write read it are sent,
13271        // and nothing at all when none does — whether or not the store's cache expects a
13272        // version of it. A member left out is one GitHub leaves as it is, so a person's edit
13273        // of it since that read is kept rather than overwritten with what it already held,
13274        // and a re-copy of an unchanged item costs no mutation.
13275        if let Some(members) = fields.as_object_mut() {
13276            if members.get("title").and_then(Value::as_str) == Some(item.title.as_str()) {
13277                members.remove("title");
13278            }
13279            let body_unchanged = match (members.get("body"), item.raw_body.as_deref()) {
13280                (Some(Value::String(sent)), Some(held)) => sent == held,
13281                (Some(Value::Null), held) => held.is_none_or(str::is_empty),
13282                _ => false,
13283            };
13284            if body_unchanged {
13285                members.remove("body");
13286            }
13287            // An issue already in the state the target asks for keeps it: an open one stays
13288            // open, and a closed one whose closure reads as the target's category keeps its
13289            // reason — a duplicate's says more than this write would.
13290            let unchanged_state = match status_target {
13291                Some(StatusTarget::Terminal(_, reason)) => {
13292                    item.closed
13293                        && closed_category(item.reason.as_deref())
13294                            == closed_category(Some(reason.reason()))
13295                }
13296                Some(StatusTarget::Column(_) | StatusTarget::Disabled(_)) => !item.closed,
13297                None => true,
13298            };
13299            if unchanged_state {
13300                members.remove("stateInput");
13301            }
13302            if members.is_empty() {
13303                return Ok(());
13304            }
13305        }
13306        self.update_content(item.content_kind, &item.id, fields)
13307            .await
13308    }
13309
13310    /// Update one board item's content with exactly `fields` beside its id, through the
13311    /// mutation its kind takes: `updateIssue` for an issue, `updateProjectV2DraftIssue` for
13312    /// a draft.
13313    ///
13314    /// Every input field either mutation leaves out is a field GitHub leaves as it is, which
13315    /// is what lets a narrow write carry the one thing it changes and nothing else.
13316    async fn update_content(
13317        &self,
13318        kind: ContentKind,
13319        id: &NativeId,
13320        fields: Value,
13321    ) -> Result<(), SourceError> {
13322        let (operation, id_key, pointer) = match kind {
13323            ContentKind::DraftIssue => (
13324                graphql::UPDATE_DRAFT,
13325                "draftIssueId",
13326                "/updateProjectV2DraftIssue/draftIssue",
13327            ),
13328            ContentKind::Issue => (graphql::UPDATE_ISSUE, "id", "/updateIssue/issue"),
13329        };
13330        if kind == ContentKind::Issue && self.hold_issue(&fields)? {
13331            return Ok(());
13332        }
13333        if kind == ContentKind::Issue && self.hold_update(id, &fields)? {
13334            return Ok(());
13335        }
13336        let mut input = fields;
13337        input[id_key] = json!(id.0);
13338        self.send_update(operation, pointer, id, input).await
13339    }
13340
13341    /// Send one item's update, `input`, as `operation`, and hold GitHub's answer at `pointer`
13342    /// to naming that item, `id`.
13343    async fn send_update(
13344        &self,
13345        operation: &str,
13346        pointer: &str,
13347        id: &NativeId,
13348        input: Value,
13349    ) -> Result<(), SourceError> {
13350        let data = match self.graphql(operation, json!({"input":&input})).await {
13351            Ok(data) => data,
13352            Err(error) => return Err(self.refusing_people(&input, error)),
13353        };
13354        let returned = data
13355            .pointer(pointer)
13356            .ok_or_else(|| SourceError::Malformed {
13357                message: "GitHub item update returned no item".into(),
13358            })?;
13359        if required_str(returned, "id")? != id.0 {
13360            return Err(SourceError::Malformed {
13361                message: "GitHub item update returned the wrong item".into(),
13362            });
13363        }
13364        self.assigned_as_asked(&input, Some(returned))
13365    }
13366
13367    /// Creates one issue, files it on the board, and reports what a read of it would say:
13368    /// its content id, its board item id, and the web address GitHub gave it.
13369    ///
13370    /// Two calls rather than one: `createIssue` answers with an issue that is on no board,
13371    /// and `addProjectV2ItemById` is what puts it there. Filing it at creation through
13372    /// `CreateIssueInput.projectV2Ids` was tried and is not done: GitHub answered with no
13373    /// board item, and the `addProjectV2ItemById` that then had to follow was refused
13374    /// "Content already exists in this project". A terminal status is not written here:
13375    /// `finish_write` selects its option first and closes the issue after, so a close never
13376    /// lands on an item whose board cannot show it.
13377    ///
13378    /// The address and the number come back here because this is the only place either is
13379    /// known before GitHub's own board read catches up — an item this run created answers
13380    /// the reads that follow it out of the record below, and one remembered without them
13381    /// would report no location and no key for the rest of the run.
13382    async fn create_and_file_issue(
13383        &self,
13384        board_id: &str,
13385        repository: &RepositoryTarget,
13386        incoming: &Incoming<'_>,
13387        body: &Option<String>,
13388    ) -> Result<Landed, SourceError> {
13389        let repository_id = self.repository_id(repository, incoming).await?;
13390        let mut input = json!({
13391            "repositoryId":repository_id,"title":incoming.written_title(),"body":body
13392        });
13393        self.assigning(&mut input, incoming)?;
13394        let data = match self
13395            .graphql(graphql::CREATE_ISSUE, json!({"input": &input}))
13396            .await
13397        {
13398            Ok(data) => data,
13399            Err(error) => return Err(self.refusing_people(&input, error)),
13400        };
13401        let created = data
13402            .pointer("/createIssue/issue")
13403            .filter(|value| !value.is_null())
13404            .ok_or_else(|| SourceError::Malformed {
13405                message: "GitHub issue creation returned no issue".into(),
13406            })?;
13407        let content_id = NativeId(required_str(created, "id")?.to_owned());
13408        // Assigned otherwise than asked, the issue is refused and taken back as the filed
13409        // create's is, a refused delete answered beside the refusal.
13410        if let Err(error) = self.assigned_as_asked(&input, Some(created)) {
13411            return Err(self.taken_back(&content_id, created, error).await);
13412        }
13413        // Optional although GitHub's schema makes it non-null: the issue exists by now, so
13414        // a response without it is not worth failing a landed write over — the item simply
13415        // reports no location until the board read catches up, which is what it did before.
13416        let url = optional_str(created, "url")?.map(str::to_owned);
13417        // The issue exists from here on, so an unreadable number and a refused board
13418        // filing below each try, best effort, to take it back: an issue in the repository
13419        // that is on no board is an item nobody asked for and nothing here would find again.
13420        //
13421        // Its number is optional on the same terms its address is — a landed write is not
13422        // worth failing over a member that came back missing, and such an item reports no
13423        // handle until a board read catches up. A number that is *present* and is not an
13424        // unsigned integer is still a response this source cannot read.
13425        let number = match created_issue_number(created) {
13426            Ok(number) => number,
13427            Err(error) => {
13428                let _ = self.delete_issue(&content_id).await;
13429                return Err(error);
13430            }
13431        };
13432        let added = match self
13433            .graphql(
13434                graphql::ADD_TO_BOARD,
13435                json!({"input":{"projectId":board_id,"contentId":content_id.0}}),
13436            )
13437            .await
13438        {
13439            Ok(added) => added,
13440            Err(error) => {
13441                let _ = self.delete_issue(&content_id).await;
13442                return Err(error);
13443            }
13444        };
13445        let item = added
13446            .pointer("/addProjectV2ItemById/item")
13447            .filter(|value| !value.is_null())
13448            .ok_or_else(|| SourceError::Malformed {
13449                message: "GitHub board addition returned no project item".into(),
13450            })?;
13451        self.note_written(&content_id, url.as_deref());
13452        Ok(Landed {
13453            content_id,
13454            item_id: Some(required_str(item, "id")?.to_owned()),
13455            url,
13456            number,
13457        })
13458    }
13459
13460    /// Move one issue under the project it now belongs to, or out of the one it left.
13461    async fn reparent(
13462        &self,
13463        held: Option<NativeId>,
13464        child: &NativeId,
13465        wanted: Option<&NativeId>,
13466    ) -> Result<(), SourceError> {
13467        if held.as_ref() == wanted {
13468            return Ok(());
13469        }
13470        if let Some(held) = &held {
13471            self.sub_issue(graphql::REMOVE_SUB_ISSUE, held, child, "removeSubIssue")
13472                .await?;
13473        }
13474        if let Some(wanted) = wanted {
13475            self.sub_issue(graphql::ADD_SUB_ISSUE, wanted, child, "addSubIssue")
13476                .await?;
13477        }
13478        Ok(())
13479    }
13480
13481    async fn sub_issue(
13482        &self,
13483        operation: &str,
13484        parent: &NativeId,
13485        child: &NativeId,
13486        root: &str,
13487    ) -> Result<(), SourceError> {
13488        let data = self
13489            .graphql(
13490                operation,
13491                json!({"input":{"issueId":parent.0,"subIssueId":child.0}}),
13492            )
13493            .await?;
13494        let issue =
13495            data.pointer(&format!("/{root}/issue"))
13496                .ok_or_else(|| SourceError::Malformed {
13497                    message: "GitHub sub-issue update returned no issue".into(),
13498                })?;
13499        let sub =
13500            data.pointer(&format!("/{root}/subIssue"))
13501                .ok_or_else(|| SourceError::Malformed {
13502                    message: "GitHub sub-issue update returned no sub-issue".into(),
13503                })?;
13504        if required_str(issue, "id")? != parent.0 || required_str(sub, "id")? != child.0 {
13505            return Err(SourceError::Malformed {
13506                message: "GitHub sub-issue update returned the wrong issues".into(),
13507            });
13508        }
13509        Ok(())
13510    }
13511
13512    /// Bring one issue's `blockedBy` to exactly `native`, sending only the difference, and say
13513    /// whether there was one.
13514    ///
13515    /// An issue [`Issue::Created`] by this very write is blocked by nothing yet, so its
13516    /// relationships are not read: there is nothing a read of them could find.
13517    async fn reconcile_blocked_by(
13518        &self,
13519        content_id: &NativeId,
13520        native: &[String],
13521        issue: Issue<'_>,
13522    ) -> Result<bool, SourceError> {
13523        let current = match issue {
13524            Issue::Created => Vec::new(),
13525            Issue::Existing(Some(held)) => held
13526                .iter()
13527                .map(|far| required_str(far, "id").map(str::to_owned))
13528                .collect::<Result<Vec<_>, _>>()?,
13529            Issue::Existing(None) => self.native_dependency_ids(content_id).await?,
13530        };
13531        let mut changed = false;
13532        for (operation, far_id) in current
13533            .iter()
13534            .filter(|id| !native.contains(id))
13535            .map(|id| (graphql::REMOVE_BLOCKED_BY, id))
13536            .chain(
13537                native
13538                    .iter()
13539                    .filter(|id| !current.contains(id))
13540                    .map(|id| (graphql::ADD_BLOCKED_BY, id)),
13541            )
13542        {
13543            let data = self
13544                .graphql(
13545                    operation,
13546                    json!({"input":{"issueId":content_id.0,"blockingIssueId":far_id}}),
13547                )
13548                .await?;
13549            let root = if operation == graphql::ADD_BLOCKED_BY {
13550                "addBlockedBy"
13551            } else {
13552                "removeBlockedBy"
13553            };
13554            let issue =
13555                data.pointer(&format!("/{root}/issue"))
13556                    .ok_or_else(|| SourceError::Malformed {
13557                        message: "GitHub dependency update returned no issue".into(),
13558                    })?;
13559            let blocker = data
13560                .pointer(&format!("/{root}/blockingIssue"))
13561                .ok_or_else(|| SourceError::Malformed {
13562                    message: "GitHub dependency update returned no blocking issue".into(),
13563                })?;
13564            if required_str(issue, "id")? != content_id.0 || required_str(blocker, "id")? != far_id
13565            {
13566                return Err(SourceError::Malformed {
13567                    message: "GitHub dependency update returned the wrong issues".into(),
13568                });
13569            }
13570            changed = true;
13571        }
13572        Ok(changed)
13573    }
13574}
13575
13576/// The board field values one write sends, in the order GitHub runs them, and the fields it
13577/// clears after them: the origin field when it moves, the `Status` option `column` names, the
13578/// priority, then each projected field.
13579fn field_writes<'a>(
13580    existing: Option<&Resolved>,
13581    origin_field: Option<&str>,
13582    origin: &str,
13583    column: Option<(String, String)>,
13584    priority: Option<&'a PriorityWrite>,
13585    projections: &'a [ProjectionWrite],
13586) -> (Vec<(String, Value)>, Vec<&'a str>) {
13587    let mut fields = Vec::new();
13588    if let Some(field_id) = origin_field
13589        && existing.map_or(!origin.is_empty(), |item| {
13590            item.origin.as_deref().unwrap_or("") != origin
13591        })
13592    {
13593        fields.push((field_id.to_owned(), json!({"text":origin})));
13594    }
13595    if let Some((field_id, option_id)) = column {
13596        fields.push((field_id, json!({"singleSelectOptionId":option_id})));
13597    }
13598    let mut clears = Vec::new();
13599    match priority {
13600        Some(PriorityWrite::Select { field, option }) => {
13601            fields.push((field.clone(), json!({"singleSelectOptionId":option})));
13602        }
13603        Some(PriorityWrite::Clear { field }) => clears.push(field.as_str()),
13604        None => {}
13605    }
13606    for projection in projections {
13607        projection.join(&mut fields, &mut clears);
13608    }
13609    (fields, clears)
13610}
13611
13612/// Everything one write decided before sending anything: see
13613/// [`GitHubProjectsSource::prepare_write`].
13614struct Prepared {
13615    /// What the write lands on.
13616    destination: WriteDestination,
13617    board: BoardFields,
13618    status_target: Option<StatusTarget>,
13619    /// The `Status` field, the option and the option's name the status lands on.
13620    // 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.
13621    column: Option<(String, String, String)>,
13622    priority_write: Option<PriorityWrite>,
13623    projections: Vec<ProjectionWrite>,
13624    projected: BTreeMap<String, String>,
13625    content_kind: ContentKind,
13626    own_repository: Option<Repository>,
13627    /// The far ends of the item's native blocked-by relationships.
13628    // 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.
13629    native: Vec<String>,
13630    slot: BTreeMap<String, Value>,
13631    content: Option<String>,
13632    body: Option<String>,
13633    /// The copy origin the item records, empty for none.
13634    // 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.
13635    origin: String,
13636    origin_field: Option<String>,
13637}
13638
13639/// One write a copy held back of the kinds sent together: a board field value, or a blocked-by
13640/// edge, each its input.
13641enum HeldWrite<'a> {
13642    Field(&'a Value),
13643    Edge(&'a Value),
13644}
13645
13646/// Whether `error` is GitHub refusing to file an issue on a board because it is filed there
13647/// already — what `addProjectV2ItemById` answers once `createIssue`'s `projectV2Ids` has placed
13648/// it, rather than answering with the item it holds.
13649fn already_on_the_board(error: &SourceError) -> bool {
13650    error
13651        .to_string()
13652        .contains("Content already exists in this project")
13653}
13654
13655/// Hold every alias `inputs` sent under `prefix` in `data` to answering with what its input
13656/// named — each `(root, named)` of `answers` — and refuse one that answered nothing or another
13657/// item.
13658fn check_aliased_answers(
13659    document: &str,
13660    data: &Value,
13661    prefix: &str,
13662    inputs: &[&Value],
13663    answers: &[(&str, &str)],
13664) -> Result<(), SourceError> {
13665    for (slot, input) in inputs.iter().enumerate() {
13666        for (root, named) in answers {
13667            let answered = data
13668                .pointer(&format!("/{prefix}{slot}/{root}/id"))
13669                .and_then(Value::as_str)
13670                .ok_or_else(|| SourceError::Malformed {
13671                    message: format!(
13672                        "GitHub answered {} with nothing at {prefix}{slot}",
13673                        operation_description(document)
13674                    ),
13675                })?;
13676            let asked = input.get(named).and_then(Value::as_str).unwrap_or_default();
13677            if answered != asked {
13678                return Err(SourceError::Malformed {
13679                    message: format!(
13680                        "GitHub answered {} at {prefix}{slot} with {answered}, which is not \
13681                         {asked}, the item it was asked to write",
13682                        operation_description(document)
13683                    ),
13684                });
13685            }
13686        }
13687    }
13688    Ok(())
13689}
13690
13691/// `error`, which stopped a batch of creates, and — when GitHub refused to take any of them
13692/// back — each issue of `left` it created that is still in the repository, which its caller,
13693/// never handed their ids, could not name.
13694fn left_behind(error: SourceError, left: &[&str]) -> SourceError {
13695    if left.is_empty() {
13696        return error;
13697    }
13698    SourceError::Refused {
13699        message: format!(
13700            "{error}; GitHub then refused to take back {}, which this write created and which \
13701             are still in the repository; next: delete {} before writing again",
13702            left.join(", "),
13703            if left.len() == 1 { "it" } else { "them" }
13704        ),
13705    }
13706}
13707
13708/// What one write lands on: the item it updates, as it stood, or where it creates a new one.
13709enum WriteDestination {
13710    /// The item as it stood, for an update.
13711    Existing(Box<Resolved>),
13712    /// Where a new item is created.
13713    New(RepositoryTarget),
13714}
13715
13716impl WriteDestination {
13717    /// The item an update writes over, as it stood; `None` for a create.
13718    fn existing(&self) -> Option<&Resolved> {
13719        match self {
13720            Self::Existing(item) => Some(item),
13721            Self::New(_) => None,
13722        }
13723    }
13724}
13725
13726/// One existing issue's update held back by [`GitHubProjectsSource::hold_update`]: the issue,
13727/// and the `UpdateIssueInput` its own [`graphql::UPDATE_ISSUE`] would have sent — the members
13728/// it writes beside that issue's id, which only [`Self::new`] sets.
13729struct HeldUpdate {
13730    issue: NativeId,
13731    // 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.
13732    input: Value,
13733}
13734
13735impl HeldUpdate {
13736    /// The update writing `members` — an `UpdateIssueInput` without its id — to `issue`.
13737    fn new(issue: &NativeId, members: &Value) -> Self {
13738        let mut input = members.clone();
13739        input["id"] = json!(issue.0);
13740        Self {
13741            issue: issue.clone(),
13742            input,
13743        }
13744    }
13745}
13746
13747/// What a copy has held back of the items it created; see
13748/// [`GitHubProjectsSource::hold_back`].
13749#[derive(Debug, Default)]
13750enum Deferred {
13751    /// Writes are being held back, and nothing has been held yet.
13752    #[default]
13753    Nothing,
13754    /// The items held back, every one of them on `board`.
13755    Held {
13756        /// The board every one of them is on.
13757        board: BoardId,
13758        /// Each created item, in the order it was created.
13759        created: Vec<HeldBack>,
13760    },
13761}
13762
13763impl Deferred {
13764    /// Whether `content` is one of the items held back.
13765    fn holds(&self, content: &NativeId) -> bool {
13766        match self {
13767            Self::Nothing => false,
13768            Self::Held { created, .. } => created.iter().any(|held| held.content == *content),
13769        }
13770    }
13771}
13772
13773/// One created item's parts that land once [`TaskSource::finish_writes`] is called.
13774#[derive(Debug)]
13775struct HeldBack {
13776    /// The issue.
13777    content: NativeId,
13778    /// Its board field values other than its `Status`, in the order they are written.
13779    fields: Vec<(String, Value)>,
13780    /// The `Status` field, and the option and its name that the item's status lands on.
13781    // llmlint: ignore[invalid_states_unrepresentable] The same triple `column_for` returns and `Prepared::column` carries, held back unchanged until it is sent.
13782    status: Option<(String, String, String)>,
13783    /// The fields it clears after those are written.
13784    clears: Vec<String>,
13785    /// The reason it is closed for, once its option is selected; `None` leaves it open.
13786    close: Option<ClosedState>,
13787    /// The issues it is blocked by.
13788    edges: Vec<NativeId>,
13789}
13790
13791/// The member [`answer_with_errors`] carries a response's GraphQL errors under, beside its data:
13792/// no GitHub type has a field of this name.
13793const ANSWER_ERRORS: &str = "onetaskgraphErrors";
13794
13795/// A response's `data` with its GraphQL errors beside it under [`ANSWER_ERRORS`], when it has
13796/// both — or `None`, for an answer [`GitHubProjectsSource::answer`] reads as it always has.
13797///
13798/// What [`graphql::CREATE_ISSUES`] is answered with: GitHub runs a document's mutation fields in
13799/// order and answers each one that ran, so a refusal of one alias leaves the issues the others
13800/// created named in the data beside it — the ids a copy needs to take them back.
13801fn answer_with_errors(body: &str) -> Option<Value> {
13802    let parsed: Value = serde_json::from_str(body).ok()?;
13803    let errors = parsed
13804        .get("errors")?
13805        .as_array()
13806        .filter(|errors| !errors.is_empty())?;
13807    let mut data = parsed.get("data").filter(|data| data.is_object())?.clone();
13808    data[ANSWER_ERRORS] = Value::Array(errors.clone());
13809    Some(data)
13810}
13811
13812/// The `createIssue` input that files the new issue on `board` and, when `incoming` names one,
13813/// under its project — see [`GitHubProjectsSource::create_filed_issue`].
13814fn filed_input(
13815    repository: &str,
13816    board: &str,
13817    incoming: &Incoming<'_>,
13818    body: &Option<String>,
13819) -> Value {
13820    let mut input = json!({"repositoryId":repository,"title":incoming.written_title(),
13821                           "body":body,"projectV2Ids":[board]});
13822    if let Some(parent) = incoming.parent {
13823        input["parentIssueId"] = json!(parent.0);
13824    }
13825    input
13826}
13827
13828/// The name of option `option` of field `field` among a board's `fields`.
13829fn option_name<'a>(fields: &'a Value, field: &str, option: &str) -> Option<&'a str> {
13830    fields
13831        .get("nodes")?
13832        .as_array()?
13833        .iter()
13834        .find(|node| node.get("id").and_then(Value::as_str) == Some(field))?
13835        .get("options")?
13836        .as_array()?
13837        .iter()
13838        .find(|candidate| candidate.get("id").and_then(Value::as_str) == Some(option))?
13839        .get("name")?
13840        .as_str()
13841}
13842
13843/// What a write needs to know of one far end it names: which kind of item it is, and whether
13844/// it is an issue a native relationship can name.
13845struct FarEnd {
13846    kind: BoardKind,
13847    content_kind: ContentKind,
13848}
13849
13850/// Whether the issue one write reconciles was created by that write or was already there.
13851#[derive(Clone, Copy, PartialEq, Eq)]
13852enum Issue<'a> {
13853    /// Created by this write, so it holds no relationships yet.
13854    Created,
13855    /// On the board before this write, holding whatever relationships it holds — the far
13856    /// ends of its whole `blockedBy`, when the read that reached it carried them.
13857    Existing(Option<&'a [Value]>),
13858}
13859
13860/// What resolving one node id reached; see [`GitHubProjectsSource::reach`].
13861enum Reached {
13862    /// An issue this board holds, resolved into everything this source reports about it.
13863    Held(Box<Resolved>),
13864    /// Nothing this board holds: no such node, or a node on some other board.
13865    Nothing,
13866    /// A board draft, which [`graphql::ISSUE`] reaches and reads nothing of, so it is read
13867    /// again by [`GitHubProjectsSource::draft_by_id`].
13868    Draft,
13869}
13870
13871/// What GitHub says when a string is not a node id it can resolve.
13872///
13873/// Matched because it is the ordinary answer to a project selector naming a project by its
13874/// *name*, and reporting that as a failure would make naming one impossible. It is read
13875/// off the refusal GitHub sent, never guessed from the shape of the string: this source
13876/// does not define the syntax of a GitHub node id and would be wrong about it.
13877const UNRESOLVABLE_NODE: &str = "could not resolve to a node";
13878
13879/// `error` with `note` added to the end of what it says, its kind and every other member
13880/// unchanged — so a caller still branches on the failure that happened, and reads beside it
13881/// what that failure left behind.
13882fn noting(error: SourceError, note: &str) -> SourceError {
13883    match error {
13884        SourceError::Config { message } => SourceError::Config {
13885            message: message + note,
13886        },
13887        SourceError::Auth { message } => SourceError::Auth {
13888            message: message + note,
13889        },
13890        SourceError::Refused { message } => SourceError::Refused {
13891            message: message + note,
13892        },
13893        SourceError::RateLimited {
13894            retry_after_seconds,
13895            message,
13896        } => SourceError::RateLimited {
13897            retry_after_seconds,
13898            message: Some(message.unwrap_or_default() + note),
13899        },
13900        SourceError::Unavailable { message } => SourceError::Unavailable {
13901            message: message + note,
13902        },
13903        SourceError::Malformed { message } => SourceError::Malformed {
13904            message: message + note,
13905        },
13906    }
13907}
13908
13909/// The variables of one [`graphql::ISSUE_COPY_DETAILS`] request, as [`detail_batch`] binds its
13910/// own: a slot `batch` has no id for is bound to its last id, read again at no added price.
13911fn copy_detail_batch(batch: &[NativeId], comments: &PageRequest, children: bool) -> Value {
13912    let mut variables = serde_json::Map::new();
13913    for slot in 0..COPY_DETAIL_BATCH {
13914        let id = batch.get(slot).or(batch.last()).map(|id| id.0.clone());
13915        variables.insert(format!("id{slot}"), json!(id));
13916    }
13917    variables.insert("project".to_owned(), json!(batch.first().map(|id| &id.0)));
13918    variables.insert("children".to_owned(), json!(children));
13919    variables.insert("first".to_owned(), json!(comments.limit.min(MAX_PAGE_SIZE)));
13920    variables.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
13921    variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
13922    variables.insert("duplicates".to_owned(), json!(true));
13923    Value::Object(variables)
13924}
13925
13926/// The variables of one [`graphql::ISSUE_DETAILS`] request over `batch` — at most
13927/// [`DETAIL_BATCH`] ids — each item with the first page of its comments when `comments` asks
13928/// for them.
13929///
13930/// The document is fixed-size, so a slot `batch` has no id for is bound to its last id, which
13931/// is read again at no added price.
13932fn detail_batch(batch: &[NativeId], comments: Option<&PageRequest>) -> Value {
13933    let mut variables = serde_json::Map::new();
13934    for slot in 0..DETAIL_BATCH {
13935        let id = batch.get(slot).or(batch.last()).map(|id| id.0.clone());
13936        variables.insert(format!("id{slot}"), json!(id));
13937    }
13938    variables.insert(
13939        "first".to_owned(),
13940        json!(comments.map_or(MAX_PAGE_SIZE, |page| page.limit.min(MAX_PAGE_SIZE))),
13941    );
13942    variables.insert("comments".to_owned(), json!(comments.is_some()));
13943    variables.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
13944    variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
13945    variables.insert("duplicates".to_owned(), json!(true));
13946    Value::Object(variables)
13947}
13948
13949/// Whether this refusal is GitHub saying the id names no node at all.
13950fn unresolvable_node(error: &SourceError) -> bool {
13951    matches!(error, SourceError::Refused { message }
13952        if message.to_ascii_lowercase().contains(UNRESOLVABLE_NODE))
13953}
13954
13955/// One project name, as a search qualifier which filters on it at the server.
13956///
13957/// Quoted so the whole title is one phrase rather than a bag of words, with the two
13958/// characters GitHub's own quoting grammar gives a meaning inside a quoted phrase escaped
13959/// the way it documents. A title matched here is still compared for equality afterwards:
13960/// the qualifier narrows what the server sends, and this source decides what it names.
13961fn title_qualifier(name: &str) -> String {
13962    format!("in:title {}", quoted(name))
13963}
13964
13965/// `value` as one quoted phrase of a GitHub search or a board filter, with the two
13966/// characters GitHub's quoting grammar gives a meaning inside a quoted phrase escaped the way
13967/// it documents — so a value holding a qualifier's spelling is searched for rather than
13968/// obeyed.
13969fn quoted(value: &str) -> String {
13970    let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
13971    format!("\"{escaped}\"")
13972}
13973
13974/// The search qualifier for the issues updated at or after `since`.
13975///
13976/// Written to the second, rounded down, which can only widen what the search returns.
13977fn updated_qualifier(since: DateTime<Utc>) -> String {
13978    format!("updated:>={}", since.format("%Y-%m-%dT%H:%M:%S+00:00"))
13979}
13980
13981/// The search terms that narrow a board-scoped issue search to a task query's text and
13982/// metadata predicates, or `None` when it carries neither.
13983///
13984/// The text is one quoted phrase, searched `in:title`, `in:body` or both as its fields say,
13985/// and each metadata value is one more quoted phrase, which GitHub finds in the body because
13986/// its index covers the metadata comment the value is stored in. GitHub ANDs the phrases and
13987/// matches each in any field the `in:` qualifier names, so a query naming a title search and
13988/// a metadata value searches both fields for both — wider than asked, never narrower, and
13989/// every candidate is confirmed in process afterwards.
13990///
13991/// **This narrows a text search, and that is this source's declared semantics.** GitHub
13992/// matches whole tokens where a substring rule would match inside a word, so an item holding
13993/// the text only inside a longer word is not returned. A text of nothing but whitespace
13994/// matches every item, so it narrows nothing and is not sent.
13995fn narrowing_qualifiers(query: &TaskQuery) -> Option<String> {
13996    let text = query
13997        .text
13998        .as_ref()
13999        .filter(|text| !text.terms.trim().is_empty());
14000    if text.is_none() && query.metadata.is_empty() {
14001        return None;
14002    }
14003    let (title, body) = match text.map(|text| text.fields) {
14004        None => (false, true),
14005        Some(TextFields::Title) => (true, !query.metadata.is_empty()),
14006        Some(TextFields::Content) => (false, true),
14007        Some(TextFields::TitleOrContent) => (true, true),
14008    };
14009    let fields = match (title, body) {
14010        (true, true) => "in:title,body",
14011        (true, false) => "in:title",
14012        _ => "in:body",
14013    };
14014    let phrases = text
14015        .map(|text| text.terms.clone())
14016        .into_iter()
14017        .chain(
14018            query
14019                .metadata
14020                .iter()
14021                .map(|wanted| as_stored(wanted.value())),
14022        )
14023        .map(|phrase| quoted(&phrase))
14024        .collect::<Vec<_>>();
14025    Some(format!("{fields} {}", phrases.join(" ")))
14026}
14027
14028/// Whether every status category `query` keeps reads only off an open issue or a draft: a
14029/// closed issue reads `done`, `cancelled` or — closed for a reason that implies no category —
14030/// `unknown`, so a status filter naming none of those three can ask every issue search it sends
14031/// for open issues alone; each candidate's category is still confirmed from its own item.
14032fn open_only(query: &TaskQuery) -> bool {
14033    !query.statuses.is_empty()
14034        && query.statuses.iter().all(|category| {
14035            !matches!(
14036                category,
14037                StatusCategory::Done | StatusCategory::Cancelled | StatusCategory::Unknown
14038            )
14039        })
14040}
14041
14042/// Whether every status category `query` keeps is one only an open item reads as — `draft`,
14043/// `backlog`, `todo`, `queued`, `in-progress` and `unknown` — so a listing of it can read the
14044/// board's open items alone.
14045///
14046/// `unknown` is among them here though [`open_only`] leaves it out: a closed issue reads
14047/// `unknown` only for a closure reason GitHub never records on a closed issue (see
14048/// [`closed_category`]), so an open-only read of the board loses nothing a whole one keeps,
14049/// while an issue search, which [`open_only`] narrows, keeps its own rule.
14050fn open_items_only(query: &TaskQuery) -> bool {
14051    !query.statuses.is_empty()
14052        && query
14053            .statuses
14054            .iter()
14055            .all(|category| !matches!(category, StatusCategory::Done | StatusCategory::Cancelled))
14056}
14057
14058/// What a task query is narrowed by beside a board-scoped issue search's scope — its comment
14059/// activity and its text and metadata, with `is:open` when [`open_only`] — or `None` for a query
14060/// carrying none of those, which no narrowed search answers.
14061///
14062/// A narrowed search never answers a draft, which is no issue, so narrowing it to open issues
14063/// too leaves out nothing such a search could have answered.
14064fn search_qualifiers(query: &TaskQuery) -> Option<String> {
14065    let mut qualifiers: Vec<String> = [
14066        query.commented_since.map(updated_qualifier),
14067        narrowing_qualifiers(query),
14068    ]
14069    .into_iter()
14070    .flatten()
14071    .collect();
14072    if qualifiers.is_empty() {
14073        return None;
14074    }
14075    if open_only(query) {
14076        qualifiers.push(OPEN_QUALIFIER.to_owned());
14077    }
14078    Some(qualifiers.join(" "))
14079}
14080
14081/// The search terms that narrow a board-scoped issue search to a project or document query's
14082/// text, or `None` when it has none or a blank one: the phrase, in the fields, a task query
14083/// carrying that text alone is sent as by [`narrowing_qualifiers`].
14084fn text_qualifiers(text: Option<&TextQuery>) -> Option<String> {
14085    narrowing_qualifiers(&TaskQuery {
14086        text: text.cloned(),
14087        ..TaskQuery::default()
14088    })
14089}
14090
14091/// Refuses a project or document query's text GitHub's issue search cannot find, before
14092/// anything is asked of GitHub, on exactly the terms [`refuse_unsearchable`] refuses a task
14093/// query's.
14094fn refuse_unsearchable_text(text: Option<&TextQuery>) -> Result<(), SourceError> {
14095    refuse_unsearchable(&TaskQuery {
14096        text: text.cloned(),
14097        ..TaskQuery::default()
14098    })
14099}
14100
14101/// Refuses a task query naming a text or a metadata value GitHub's issue search cannot find,
14102/// before anything is asked of GitHub.
14103///
14104/// GitHub's index holds words, so a phrase with no letter or digit names none to find, and no
14105/// bounded query answers it: sent, GitHub's answer to it is nothing this source may rely on;
14106/// left out, the search is every issue of the board. So this source says it cannot answer
14107/// rather than reading the board or answering nothing. A blank text is not refused: it narrows
14108/// nothing GitHub could search for, and keeps the board read it always had.
14109fn refuse_unsearchable(query: &TaskQuery) -> Result<(), SourceError> {
14110    const WHY: &str = "GitHub's issue search indexes words, so it cannot answer a value with no \
14111                       letter or digit with a bounded query";
14112    if let Some(text) = &query.text
14113        && !text.terms.trim().is_empty()
14114        && !has_words(&text.terms)
14115    {
14116        return Err(SourceError::Refused {
14117            message: format!(
14118                "cannot search for the text {:?}: {WHY}; search for a text holding a letter or a digit",
14119                text.terms
14120            ),
14121        });
14122    }
14123    if let Some(wanted) = query
14124        .metadata
14125        .iter()
14126        .find(|wanted| !has_words(wanted.value()))
14127    {
14128        return Err(SourceError::Refused {
14129            message: format!(
14130                "cannot filter by the metadata value {:?} at {:?}: {WHY}; filter by a value holding a letter or a digit",
14131                wanted.value(),
14132                std::iter::once(wanted.key())
14133                    .chain(wanted.path().iter().map(String::as_str))
14134                    .collect::<Vec<_>>()
14135                    .join("/"),
14136            ),
14137        });
14138    }
14139    Ok(())
14140}
14141
14142/// Whether GitHub's index could hold a word of `phrase`: whether it has a letter or a digit.
14143fn has_words(phrase: &str) -> bool {
14144    phrase.chars().any(char::is_alphanumeric)
14145}
14146
14147/// `value` spelled the way the metadata slot stores it: as the inside of its JSON string.
14148///
14149/// What GitHub indexes is the slot's JSON text, so a value holding a character JSON escapes —
14150/// a newline, a tab, a quote — is found by the escape the body holds and not by the character,
14151/// which GitHub's word match would read as different words.
14152fn as_stored(value: &str) -> String {
14153    let encoded = Value::String(value.to_owned()).to_string();
14154    encoded[1..encoded.len() - 1].to_owned()
14155}
14156
14157/// The one narrower question a task query carrying a text, metadata or origin predicate is
14158/// sent as.
14159enum Narrowing {
14160    /// Every carrier of this origin: [`graphql::ORIGIN_LOOKUP`].
14161    Origin(String),
14162    /// The board-scoped issue search narrowed by these qualifiers.
14163    Search(String),
14164}
14165
14166impl Narrowing {
14167    /// What this question is remembered under for the length of one command.
14168    fn key(&self) -> String {
14169        match self {
14170            Self::Origin(origin) => format!("origin {origin}"),
14171            Self::Search(also) => format!("search {also}"),
14172        }
14173    }
14174}
14175
14176/// Where one connection of [`graphql::ORIGIN_LOOKUP`] resumes.
14177enum Resumed {
14178    /// It reported another page, which starts after this cursor.
14179    More(String),
14180    /// It has ended. Sending this cursor again — the page's own end when it had one, and
14181    /// otherwise the cursor it was reached from — answers an empty page, so the one document
14182    /// can go on walking the other connection.
14183    Ended(Option<String>),
14184}
14185
14186impl Resumed {
14187    /// Whether the connection has another page.
14188    const fn has_more(&self) -> bool {
14189        matches!(self, Self::More(_))
14190    }
14191
14192    /// The cursor to send this connection next.
14193    fn cursor(self) -> Option<String> {
14194        match self {
14195            Self::More(next) => Some(next),
14196            Self::Ended(last) => last,
14197        }
14198    }
14199}
14200
14201/// Where `connection`, reached from `after`, resumes — refused when it reports another page
14202/// with no cursor to it, or from a cursor that does not advance.
14203fn resumed(connection: &Value, after: Option<&str>) -> Result<Resumed, SourceError> {
14204    let info = connection
14205        .get("pageInfo")
14206        .ok_or_else(|| SourceError::Malformed {
14207            message: "GitHub connection has no pageInfo".into(),
14208        })?;
14209    let end = optional_str(info, "endCursor")?;
14210    if required_bool(info, "hasNextPage")? {
14211        let next = end.ok_or_else(|| SourceError::Malformed {
14212            message: "GitHub connection reports another page and no endCursor".into(),
14213        })?;
14214        validate_cursor_progress(after, next)?;
14215        return Ok(Resumed::More(next.to_owned()));
14216    }
14217    Ok(Resumed::Ended(
14218        end.map(str::to_owned).or_else(|| after.map(str::to_owned)),
14219    ))
14220}
14221
14222/// The board, and every item on it this source reports.
14223#[derive(Clone)]
14224struct Board {
14225    id: String,
14226    fields: Value,
14227    items: Vec<Resolved>,
14228}
14229
14230/// What a write needs of the board and nothing more: its node id and its field
14231/// definitions, in the shape a read of the board's own `fields` gives them.
14232///
14233/// Deliberately no items. A write decides which item it writes, which parent it files
14234/// under and which far ends it names by reading each of them by its own id; this is the
14235/// half of the board those reads cannot carry, and holding no item is what keeps it from
14236/// ever being asked whether an item is there.
14237#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
14238struct BoardFields {
14239    id: BoardId,
14240    fields: Value,
14241}
14242
14243/// A board's node id: what a field write and `addProjectV2ItemById` address.
14244///
14245/// Never blank, because a blank one addresses no board — so an id GitHub answers blank is
14246/// refused where it is read, and one an item names blank is read as not named at all.
14247#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
14248#[serde(try_from = "String")]
14249struct BoardId(String);
14250
14251impl TryFrom<String> for BoardId {
14252    type Error = String;
14253
14254    /// The same refusal [`BoardId::parse`] makes, for an id read back from a kept context.
14255    fn try_from(id: String) -> Result<Self, Self::Error> {
14256        Self::parse(&id).map_err(|error| error.to_string())
14257    }
14258}
14259
14260/// Where one write left its item, for the record the rest of the command reads it out of.
14261///
14262/// A named record rather than a tuple because the update arm and the create arm each fill
14263/// all four, and two `Option`s of different meaning side by side in a tuple are two
14264/// positions a reader has to count.
14265struct Landed {
14266    /// The issue's own node id, which is the [`NativeId`] this source reports.
14267    content_id: NativeId,
14268    /// The board item's id, which is what a field write addresses — `None` for an issue its
14269    /// create filed on the board itself, whose board item GitHub adds after answering and
14270    /// [`TaskSource::finish_writes`] reads.
14271    // 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.
14272    item_id: Option<String>,
14273    /// The web address GitHub gave the issue, when it gave one.
14274    // 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.
14275    url: Option<String>,
14276    /// The issue's number on its repository, when GitHub reported one.
14277    number: Option<u64>,
14278}
14279
14280impl BoardId {
14281    fn parse(id: &str) -> Result<Self, SourceError> {
14282        if id.trim().is_empty() {
14283            return Err(SourceError::Malformed {
14284                message: "GitHub named a board with a blank node id".into(),
14285            });
14286        }
14287        Ok(Self(id.to_owned()))
14288    }
14289
14290    fn as_str(&self) -> &str {
14291        &self.0
14292    }
14293}
14294
14295impl Board {
14296    fn field<'a>(fields: &'a Value, name: &str) -> Result<Option<&'a Value>, SourceError> {
14297        complete_connection(fields, "project fields", NESTED_PAGE_SIZE)?;
14298        let nodes = fields
14299            .get("nodes")
14300            .and_then(Value::as_array)
14301            .ok_or_else(|| SourceError::Malformed {
14302                message: "GitHub project fields.nodes is not an array".into(),
14303            })?;
14304        Ok(nodes
14305            .iter()
14306            .find(|field| field.get("name").and_then(Value::as_str) == Some(name)))
14307    }
14308}
14309
14310/// Each held page of a narrowed search's own read, by its key, row for row: see
14311/// `GitHubProjectsSource::search_rows`.
14312type SearchRows = BTreeMap<String, Vec<Option<Resolved>>>;
14313
14314/// One board item, resolved into everything this source reports about it.
14315///
14316/// Serializable because it is what [`TaskSource::write_context`] hands the store's cache and
14317/// [`TaskSource::prime_write`] takes back — see [`expected`].
14318#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
14319struct Resolved {
14320    item_id: String,
14321    id: NativeId,
14322    content_kind: ContentKind,
14323    kind: BoardKind,
14324    title: String,
14325    body: Option<String>,
14326    /// The body exactly as GitHub holds it, metadata slot and all, which is what a write
14327    /// that changes the slot alone has to keep byte for byte outside it.
14328    raw_body: Option<String>,
14329    status: Status,
14330    /// The name of the board `Status` option this item sits in, as the board spells it.
14331    option: Option<String>,
14332    /// What its `Priority` field says, read through this instance's mapping.
14333    priority: HeldPriority,
14334    /// Whether this item's issue is closed. A draft has no such state and is never closed.
14335    closed: bool,
14336    /// GitHub's reason for a closed issue's closure, as it spells it — `None` for an open
14337    /// issue, a draft, and an issue closed before GitHub recorded reasons.
14338    #[serde(default)]
14339    reason: Option<String>,
14340    /// The tasks this one delivers, read out of its slot. Empty for anything not a task.
14341    delivers: Vec<TaskRef>,
14342    /// Every task that delivers this one, read out of its slot. Empty for anything not a
14343    /// task.
14344    delivered_by: Vec<TaskRef>,
14345    labels: Vec<Label>,
14346    parent: Option<NativeId>,
14347    /// The issue's GitHub parent on a source reading sub-issues as children (`sub_issues:
14348    /// parent`), where [`Self::parent`] — the project it is filed under — is always `None`.
14349    #[serde(default)]
14350    issue_parent: Option<NativeId>,
14351    // 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.
14352    origin: Option<String>,
14353    /// What each board text field this instance projects metadata onto holds for this item,
14354    /// by field name — only the fields holding a value, an empty text included. What a write compares the
14355    /// item's metadata against, so a field already holding its value is not written again;
14356    /// never read back as metadata, which the slot alone reports.
14357    projected: BTreeMap<String, String>,
14358    /// The issue's own number on its repository, as GitHub reports it.
14359    ///
14360    /// `None` in exactly two cases: a draft, which has no number at all — `DraftIssue`
14361    /// declares none, and a draft is not filed in a repository to be numbered by one — and
14362    /// an issue this run created whose creating mutation answered without one, which is a
14363    /// response GitHub's own schema says cannot happen and which a landed write is not
14364    /// worth failing over. An `Issue` read off the board always has one.
14365    number: Option<u64>,
14366    url: Option<String>,
14367    created_at: Option<DateTime<Utc>>,
14368    updated_at: Option<DateTime<Utc>>,
14369    /// When the board item itself last changed — what a board field write moves — when the
14370    /// read that reached it said.
14371    item_updated_at: Option<DateTime<Utc>>,
14372    /// How many comments the issue holds, when the read that reached it said.
14373    comment_count: Option<u64>,
14374    /// How many relationship events the issue's timeline holds — every dependency, as
14375    /// `blockedBy` or `blocking`, and every project membership, as its parent, added or
14376    /// removed — when the read that reached it said.
14377    relationship_events: Option<u64>,
14378    /// The server's clock on the response that read it — its `Date` header — when the
14379    /// response carried one.
14380    served_at: Option<DateTime<Utc>>,
14381    /// The digest of its [`change_token::Facets`] — its own kind, its board field values and
14382    /// its labels — when the read that reached it carried all three whole.
14383    #[serde(default)]
14384    facets: Option<change_token::FacetsDigest>,
14385    own_repository: Option<Repository>,
14386    repositories: Vec<Repository>,
14387    classification: Classification,
14388    slot: BTreeMap<String, Value>,
14389    /// The node id of the board this item sits on, when the read that reached it said.
14390    board_id: Option<String>,
14391    /// The definition of every board field this item holds a value of, in the shape a read
14392    /// of the board's own `fields` gives one.
14393    ///
14394    /// Only the fields this item has a value in: a field it holds nothing of is not here,
14395    /// which says nothing about whether the board has it.
14396    fields: Vec<Value>,
14397    /// Every field the board this item sits on defines, as its own read of the board's
14398    /// `fields` gives them — when the read that reached the item carried them, which a read
14399    /// of it by its own id does. What a write of it needs of the board, then, needs no read
14400    /// of the board.
14401    board_fields: Option<Value>,
14402    /// The far ends of this issue's whole `blockedBy` connection, each as a dependency read
14403    /// selects one — when the read that reached it carried the connection to its end, which a
14404    /// read of it by its own id does for any issue blocked by no more than a page. What a
14405    /// write reconciles that relationship against, and what a read of its forward edges in
14406    /// the same command answers with.
14407    blocked_by: Option<Vec<Value>>,
14408    /// Every person the item is assigned to, by login in the order GitHub answered them — read
14409    /// only by a source opted in to assignees, and `None` for any other, and for a record no
14410    /// read or write of this process showed them on.
14411    #[serde(default)]
14412    assignees: Option<Vec<String>>,
14413}
14414
14415impl Resolved {
14416    /// The board this item's own read names it on, when that read named one this source can
14417    /// address.
14418    fn named_board(&self) -> Option<BoardId> {
14419        self.board_id
14420            .as_deref()
14421            .and_then(|id| BoardId::parse(id).ok())
14422    }
14423
14424    /// The board's id and every field it defines, when the read that reached this item
14425    /// carried both — which a read of it by its own id does.
14426    fn carried_board(&self) -> Option<BoardFields> {
14427        Some(BoardFields {
14428            id: self.named_board()?,
14429            fields: self.board_fields.clone()?,
14430        })
14431    }
14432
14433    /// Whether this item holds a value of the board field called `name`, and so carries
14434    /// that field's definition. `false` says nothing about whether the board has the field.
14435    fn defines(&self, name: &str) -> bool {
14436        self.fields
14437            .iter()
14438            .any(|field| field.get("name").and_then(Value::as_str) == Some(name))
14439    }
14440
14441    /// The metadata a caller sees: their own keys, plus the copy origin this source keeps
14442    /// in a field of its own, and none of the five keys that are only an encoding.
14443    ///
14444    /// The two delivery keys are left out for every kind, not only for a task: they are
14445    /// the encoding of [`Task::delivers`] and [`Task::delivered_by`], and a project or a
14446    /// document carrying one holds nothing a caller's own metadata could mean by it.
14447    fn metadata(&self) -> BTreeMap<String, Value> {
14448        let mut metadata = self.slot.clone();
14449        metadata.remove(Repository::METADATA_KEY);
14450        metadata.remove(DependencyEdge::RECORDED_KEY);
14451        metadata.remove(ItemKind::METADATA_KEY);
14452        metadata.remove(TaskRef::DELIVERS_KEY);
14453        metadata.remove(TaskRef::DELIVERED_BY_KEY);
14454        metadata.remove(Classification::METADATA_KEY);
14455        // The board field is the origin, and the body's copy of it is only a mirror for the
14456        // issue search to find: an item whose field holds none has none, whatever its body
14457        // says, so no reader ever sees two answers.
14458        metadata.remove(ORIGIN_KEY);
14459        if let Some(origin) = &self.origin {
14460            metadata.insert(ORIGIN_KEY.to_owned(), Value::String(origin.clone()));
14461        }
14462        metadata
14463    }
14464
14465    /// Where this item is, as a link a reader can open.
14466    ///
14467    /// A board is a hosted place and every issue on it has a web address, so that address
14468    /// is what "where is this?" means here — and [`Location::Url`] is what says which kind
14469    /// of place it is, so a reader knows to open it rather than to read a file out. It
14470    /// does not replace or derive from `url`: the field goes on reporting exactly what it
14471    /// reported before, and this says what that address *is*.
14472    ///
14473    /// An item GitHub gave no `url` for — a draft has none — reports no location at all
14474    /// rather than a third variant, which is the contract's "the source did not say". An
14475    /// issue this run created is not one of those: its address comes back from the
14476    /// creating mutation, so it is somewhere a reader can open from the moment it exists
14477    /// rather than from whenever the board read catches up.
14478    fn location(&self) -> Option<Location> {
14479        self.url.clone().map(Location::Url)
14480    }
14481
14482    /// The short handle this board's backend shows people for a task: the issue's number
14483    /// alone, as a decimal string.
14484    ///
14485    /// The number alone rather than `owner/repo#1043`, because that is the contract's
14486    /// value for this backend. A draft has no number and so no handle, which is the
14487    /// contract's *absent* rather than a handle of some other shape — and the native
14488    /// [`Task::id`] here is the issue's GraphQL node id, which this neither replaces nor
14489    /// derives from.
14490    fn key(&self) -> Option<String> {
14491        self.number.map(|number| number.to_string())
14492    }
14493
14494    /// This item's change token — see [`change_token`] — or `None` when the read that
14495    /// reached it did not carry all six of its parts, which a draft never does, did not say
14496    /// when GitHub served it, or found it changed too recently to have settled.
14497    fn version(&self) -> Option<String> {
14498        let parts = self.token_parts()?;
14499        change_token::settled(parts.issue, parts.item, self.served_at?)
14500            .then(|| change_token::spell(&parts))
14501    }
14502
14503    /// The change token this item, read just after a write of it, holds now — whether or not it
14504    /// has settled: what a written task's `version` answers (see
14505    /// [`GitHubProjectsSource::written_tokens`]), spelled from the parts a later read spells its
14506    /// token from.
14507    fn written_version(&self) -> Option<String> {
14508        self.token_parts().map(|parts| change_token::spell(&parts))
14509    }
14510
14511    /// Every part of this item's change token, or `None` when the read that reached it did not
14512    /// carry them all — a draft never does.
14513    fn token_parts(&self) -> Option<change_token::Parts> {
14514        match self.content_kind {
14515            ContentKind::Issue => Some(change_token::Parts {
14516                issue: self.updated_at?,
14517                item: self.item_updated_at?,
14518                comments: self.comment_count?,
14519                relationships: self.relationship_events?,
14520                facets: self.facets.clone()?,
14521                repository: self.own_repository.clone()?,
14522            }),
14523            ContentKind::DraftIssue => None,
14524        }
14525    }
14526
14527    /// Whether its `Priority` field holds a value at all, mapped or not.
14528    fn holds_priority(&self) -> bool {
14529        self.priority != HeldPriority::Read(Priority::None)
14530    }
14531
14532    /// The task this item is.
14533    ///
14534    /// Fails for an item whose `Priority` field holds an option the mapping does not name:
14535    /// reading that as a level would be a guess, and reading it as `none` would let the next
14536    /// copy clear a priority a person set.
14537    fn task(&self) -> Result<Task, SourceError> {
14538        let priority = match &self.priority {
14539            HeldPriority::Read(priority) => *priority,
14540            HeldPriority::Unmapped(option) => {
14541                return Err(SourceError::Malformed {
14542                    message: format!(
14543                        "task {}{} sits in the board {PRIORITY_FIELD} option {option:?}, which \
14544                         this source's priority_mapping does not name, so its priority cannot be \
14545                         read; next: name {option:?} under priority_mapping, or move the item to \
14546                         a mapped option",
14547                        self.id,
14548                        self.number
14549                            .map(|number| format!(" (#{number})"))
14550                            .unwrap_or_default()
14551                    ),
14552                });
14553            }
14554        };
14555        let metadata = self.metadata();
14556        Ok(Task {
14557            version: self.version(),
14558            id: self.id.clone(),
14559            key: self.key(),
14560            title: self.title.clone(),
14561            // The `## Links` section the engine rendered is stripped, so content round-trips.
14562            content: onetaskgraph_plugin_api::read_content(self.body.clone(), &metadata),
14563            status: self.status.clone(),
14564            priority,
14565            labels: self.labels.clone(),
14566            project: self.parent.clone(),
14567            url: self.url.clone(),
14568            location: self.location(),
14569            created_at: self.created_at,
14570            updated_at: self.updated_at,
14571            metadata,
14572            repositories: self.repositories.clone(),
14573            delivers: self.delivers.clone(),
14574            delivered_by: self.delivered_by.clone(),
14575            classification: self.classification,
14576            assignees: self.assignees.clone(),
14577        })
14578    }
14579
14580    fn project(&self) -> Project {
14581        Project {
14582            version: self.version(),
14583            id: self.id.clone(),
14584            title: self.title.clone(),
14585            content: self.body.clone(),
14586            status: self.status.clone(),
14587            labels: self.labels.clone(),
14588            url: self.url.clone(),
14589            location: self.location(),
14590            created_at: self.created_at,
14591            updated_at: self.updated_at,
14592            metadata: self.metadata(),
14593            repositories: self.repositories.clone(),
14594            classification: self.classification,
14595        }
14596    }
14597
14598    /// The same issue as a document: the project it is filed under, and no status and no
14599    /// dependencies, because a document is not work.
14600    fn document(&self) -> Document {
14601        Document {
14602            version: self.version(),
14603            id: self.id.clone(),
14604            title: self.title.clone(),
14605            content: self.body.clone(),
14606            project: self.parent.clone(),
14607            labels: self.labels.clone(),
14608            url: self.url.clone(),
14609            location: self.location(),
14610            created_at: self.created_at,
14611            updated_at: self.updated_at,
14612            metadata: self.metadata(),
14613            repositories: self.repositories.clone(),
14614            classification: self.classification,
14615        }
14616    }
14617}
14618
14619/// Where one targeted update moves an item's status, and which of its two halves move.
14620struct StatusMove {
14621    /// The board the item's `Status` field is on.
14622    board: BoardId,
14623    /// The `Status` field's id.
14624    field: String,
14625    /// The option's id.
14626    option: String,
14627    /// The option's name, as the board spells it.
14628    name: String,
14629    /// What the status asks of the issue's state.
14630    target: StatusTarget,
14631    /// The status the item reads as once it is there.
14632    landed: Status,
14633    /// Which of the status's two halves differ from what the item holds.
14634    moves: Moves,
14635}
14636
14637/// Which halves of an item's status one targeted update moves: its `Status` option, the open or
14638/// closed state of its issue, or both. A status neither half of which differs is no move at all,
14639/// and is not a value of this type.
14640#[derive(Clone, Copy, PartialEq, Eq)]
14641enum Moves {
14642    /// The option alone.
14643    Option,
14644    /// The issue's state alone: open, closed, or closed with another reason.
14645    State,
14646    /// Both.
14647    Both,
14648}
14649
14650impl Moves {
14651    /// What differs, or `None` when nothing does.
14652    const fn of(option: bool, state: bool) -> Option<Self> {
14653        match (option, state) {
14654            (true, true) => Some(Self::Both),
14655            (true, false) => Some(Self::Option),
14656            (false, true) => Some(Self::State),
14657            (false, false) => None,
14658        }
14659    }
14660
14661    /// Whether the option moves.
14662    const fn option(self) -> bool {
14663        matches!(self, Self::Option | Self::Both)
14664    }
14665
14666    /// Whether the issue's state moves.
14667    const fn state(self) -> bool {
14668        matches!(self, Self::State | Self::Both)
14669    }
14670}
14671
14672/// What one write is, and the status that comes with being it.
14673///
14674/// One value rather than a [`BoardKind`] beside an `Option<Status>`: a document has no
14675/// status and a task or a project always has one, so "a document carrying a status" and
14676/// "a task carrying none" are states a write cannot be in rather than states every use
14677/// site below has to defend against.
14678enum Written<'a> {
14679    /// A document, which is not work and so has no status at all.
14680    Document,
14681    /// A task or a project, and the status it is being written with.
14682    Work(ItemKind, &'a Status),
14683}
14684
14685impl Written<'_> {
14686    /// Which of the board's three kinds this write is.
14687    const fn kind(&self) -> BoardKind {
14688        match self {
14689            Self::Document => BoardKind::Document,
14690            Self::Work(kind, _) => BoardKind::Work(*kind),
14691        }
14692    }
14693
14694    /// The status this write carries. A document carries none, so a write of one says
14695    /// nothing about the issue's open or closed state and selects no board `Status`
14696    /// option.
14697    const fn status(&self) -> Option<&Status> {
14698        match self {
14699            Self::Document => None,
14700            Self::Work(_, status) => Some(status),
14701        }
14702    }
14703
14704    /// The status this write carries with the kind whose half of `status_mapping` it is
14705    /// written through.
14706    const fn work_status(&self) -> Option<(ItemKind, &Status)> {
14707        match self {
14708            Self::Document => None,
14709            Self::Work(kind, status) => Some((*kind, status)),
14710        }
14711    }
14712}
14713
14714/// The item being written, in the one shape all three write methods reach.
14715struct Incoming<'a> {
14716    written: Written<'a>,
14717    /// The title a person wrote. A document's goes onto the issue with
14718    /// [`DESIGN_TITLE_PREFIX`] put back, so a round trip returns the title that went in.
14719    title: &'a str,
14720    content: Option<&'a str>,
14721    assets: Option<&'a onetaskgraph_plugin_api::AssetWrite>,
14722    labels: &'a [Label],
14723    metadata: &'a BTreeMap<String, Value>,
14724    repositories: &'a [Repository],
14725    /// Recorded in the slot while private, and nowhere while public.
14726    classification: Classification,
14727    parent: Option<&'a NativeId>,
14728    /// [`Task::delivers`], already checked. Empty for a project or a document, which is
14729    /// what keeps either key out of their slot.
14730    delivers: &'a [TaskRef],
14731    /// [`Task::delivered_by`], already checked. Empty for a project or a document.
14732    delivered_by: &'a [TaskRef],
14733    /// [`Task::priority`], for a task written to an instance that holds one; `None` for a
14734    /// project, a document, and every write to an instance with no `priority_mapping` —
14735    /// which is what keeps such a write's requests exactly what they were before.
14736    priority: Option<Priority>,
14737    /// [`Task::assignees`] of a task written to a source opted in to them — the people it is
14738    /// to be assigned to, replacing whoever it holds — and `None` for everything else, which
14739    /// leaves an existing item's as they are and creates one unassigned.
14740    assignees: Option<&'a [String]>,
14741}
14742
14743/// What one write does to one projected metadata text field, by the field's id.
14744#[derive(Debug, Clone)]
14745enum ProjectionWrite {
14746    /// Write this text.
14747    Set {
14748        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.
14749        text: String,
14750    },
14751    /// Clear the field's value.
14752    Clear { field: String }, // llmlint: ignore[invalid_states_unrepresentable] As above.
14753}
14754
14755impl ProjectionWrite {
14756    /// Add this write to a field write's list of values and list of clears.
14757    fn join<'a>(&'a self, values: &mut Vec<(String, Value)>, clears: &mut Vec<&'a str>) {
14758        match self {
14759            Self::Set { field, text } => values.push((field.clone(), json!({"text": text}))),
14760            Self::Clear { field } => clears.push(field),
14761        }
14762    }
14763}
14764
14765/// What one write does to an item's `Priority` field.
14766enum PriorityWrite {
14767    /// Select this option of this field.
14768    Select {
14769        /// The `Priority` field's id.
14770        field: String,
14771        /// The mapped option's id.
14772        option: String,
14773    },
14774    /// Clear the field's value, which is what `none` is.
14775    Clear {
14776        /// The `Priority` field's id.
14777        field: String,
14778    },
14779}
14780
14781impl Incoming<'_> {
14782    /// The title this write puts on the issue.
14783    fn written_title(&self) -> String {
14784        match self.written {
14785            Written::Document => format!("{DESIGN_TITLE_PREFIX}{}", self.title),
14786            Written::Work(..) => self.title.to_owned(),
14787        }
14788    }
14789}
14790
14791#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
14792enum ContentKind {
14793    DraftIssue,
14794    Issue,
14795}
14796
14797/// What one board issue is: a document, or the work an [`ItemKind`] names.
14798///
14799/// A type of this source's own rather than an `ItemKind` with a third variant, because
14800/// `ItemKind` names what a dependency endpoint points at and nothing may point at a
14801/// document — the contract keeps a document out of that enum deliberately. Holding the
14802/// board's three answers in one value is what makes every place that asks "which is this?"
14803/// answer all three, rather than a `document: bool` beside a `kind` that means nothing for
14804/// two thirds of the board.
14805#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
14806enum BoardKind {
14807    /// An issue whose title begins [`DESIGN_TITLE_PREFIX`].
14808    Document,
14809    /// Every other issue, and every draft.
14810    Work(ItemKind),
14811}
14812
14813impl BoardKind {
14814    /// The kind of an item titled `title`, filed under a project or not, holding `sub_issues`
14815    /// sub-issues and carrying the kind marker `marked` in its slot.
14816    ///
14817    /// The design prefix is read *first*, before either of the two rules that separate a
14818    /// project from a task. A document is not work whatever sub-issues it has and whatever
14819    /// marker it carries, and reading the prefix later would make a design issue with none of
14820    /// either an empty project. Being a sub-issue wins outright over the rest, and no marker
14821    /// overrides it: an issue filed under a project is that project's task even when it has
14822    /// sub-issues of its own.
14823    fn of(title: &str, filed: bool, sub_issues: u64, marked: Option<ItemKind>) -> Self {
14824        if title.starts_with(DESIGN_TITLE_PREFIX) {
14825            Self::Document
14826        } else if filed {
14827            Self::Work(ItemKind::Task)
14828        } else if sub_issues > 0 || marked == Some(ItemKind::Project) {
14829            Self::Work(ItemKind::Project)
14830        } else {
14831            Self::Work(ItemKind::Task)
14832        }
14833    }
14834
14835    /// What the change token's facets call this kind.
14836    const fn facet(self) -> change_token::FacetKind {
14837        match self {
14838            Self::Document => change_token::FacetKind::Document,
14839            Self::Work(ItemKind::Project) => change_token::FacetKind::Project,
14840            Self::Work(ItemKind::Task) => change_token::FacetKind::Task,
14841        }
14842    }
14843
14844    /// Whose half of `status_mapping` an item of this kind reads its status through. A
14845    /// document has no status of its own, so the task half stands in for whatever the issue
14846    /// holds; nothing reports it.
14847    const fn status_kind(self) -> ItemKind {
14848        match self {
14849            Self::Document => ItemKind::Task,
14850            Self::Work(kind) => kind,
14851        }
14852    }
14853
14854    /// How a refusal names this kind to the person reading it.
14855    const fn describes(self) -> &'static str {
14856        match self {
14857            Self::Document => "document",
14858            Self::Work(kind) => kind.marker(),
14859        }
14860    }
14861}
14862
14863/// Whether `labels` satisfies `filter`, matching by name, case-insensitively.
14864///
14865/// This is the local Markdown source's `labels_match`, spelled the same way on purpose:
14866/// the shared cross-source journeys assert one answer to one question, so two sources
14867/// that disagree about what "carries the label bug" means fail them.
14868fn labels_match(labels: &[Label], filter: &LabelFilter) -> bool {
14869    let holds = |name: &String| {
14870        labels
14871            .iter()
14872            .any(|label| label.name.eq_ignore_ascii_case(name))
14873    };
14874    (filter.any_of.is_empty() || filter.any_of.iter().any(holds))
14875        && filter.all_of.iter().all(holds)
14876        && !filter.none_of.iter().any(holds)
14877}
14878
14879/// Whether `category` is one of `statuses`. An empty list is unfiltered rather than
14880/// "keeps nothing", which is what lets a `Vec<StatusCategory>` spell no filter at all.
14881fn status_matches(category: StatusCategory, statuses: &[StatusCategory]) -> bool {
14882    statuses.is_empty() || statuses.contains(&category)
14883}
14884
14885/// Whether `title`/`content` satisfies `query`, matching case-insensitively.
14886///
14887/// `content` is the item's own prose — the body with this source's trailing metadata
14888/// comment already taken off — so a search never matches an encoding the author of the
14889/// issue never wrote.
14890fn text_matches(title: &str, content: Option<&str>, query: &TextQuery) -> bool {
14891    let terms = query.terms.to_lowercase();
14892    let in_title = title.to_lowercase().contains(&terms);
14893    let in_content = content.is_some_and(|body| body.to_lowercase().contains(&terms));
14894    match query.fields {
14895        TextFields::Title => in_title,
14896        TextFields::Content => in_content,
14897        TextFields::TitleOrContent => in_title || in_content,
14898    }
14899}
14900
14901/// Whether `task` satisfies `query`, with `project` deciding the project predicate.
14902///
14903/// The project predicate is passed separately because a read narrowed to one project has
14904/// already answered it by asking *that project* for its own items — and re-applying it
14905/// there would compare the caller's selector, which may be a project's **name**, against
14906/// the id of the project that name resolved to, and keep nothing. Every other read passes
14907/// `query.project` and applies it here, which is what keeps `projects` a predicate this
14908/// source really does apply.
14909fn task_matches(task: &Task, query: &TaskQuery, project: &ProjectFilter) -> bool {
14910    labels_match(&task.labels, &query.labels)
14911        && status_matches(task.status.category, &query.statuses)
14912        && (query.priorities.is_empty() || query.priorities.contains(&task.priority))
14913        && match project {
14914            ProjectFilter::Any => true,
14915            ProjectFilter::Orphans => task.project.is_none(),
14916            ProjectFilter::Is(id) => task.project.as_ref() == Some(id),
14917        }
14918        && query
14919            .text
14920            .as_ref()
14921            .is_none_or(|text| text_matches(&task.title, task.content.as_deref(), text))
14922        // Against the parsed metadata slot, and against the origin field, which is where
14923        // `Resolved::metadata` reads each of them from.
14924        && query.metadata_matches(&task.metadata)
14925        && query.origin_matches(&task.metadata)
14926}
14927
14928fn project_matches(project: &Project, query: &ProjectQuery) -> bool {
14929    labels_match(&project.labels, &query.labels)
14930        && status_matches(project.status.category, &query.statuses)
14931        && query
14932            .text
14933            .as_ref()
14934            .is_none_or(|text| text_matches(&project.title, project.content.as_deref(), text))
14935}
14936
14937/// The same three predicates a task query carries, minus the status filter.
14938///
14939/// A document is not work, so it has no status for one to compare against and the query
14940/// type carries none. The project predicate is the same one — a design issue filed under a
14941/// project issue is in that project, and one filed under nothing is in none — so it is
14942/// spelled the same way here rather than answered differently.
14943fn document_matches(document: &Document, query: &DocumentQuery, project: &ProjectFilter) -> bool {
14944    labels_match(&document.labels, &query.labels)
14945        && match project {
14946            ProjectFilter::Any => true,
14947            ProjectFilter::Orphans => document.project.is_none(),
14948            ProjectFilter::Is(id) => document.project.as_ref() == Some(id),
14949        }
14950        && query
14951            .text
14952            .as_ref()
14953            .is_none_or(|text| text_matches(&document.title, document.content.as_deref(), text))
14954}
14955
14956/// Why a GitHub item's change token does not vouch for its forward edges.
14957///
14958/// A forward edge names its far end and that far end's kind, and the near item's token moves
14959/// with the edges it holds but says nothing of the far ends themselves: a far end turning from a
14960/// task into a project when it gains a sub-issue, retitled into a document, or deleted moves
14961/// nothing the near token reads, so an edge kept at the near version could name a far end that
14962/// is no longer what it said.
14963const FAR_ENDS_UNCOVERED: &str = "a github item's change token does not attest a far end's kind, \
14964     whether it became a document, or its deletion, so its forward edges are always read from \
14965     github";
14966
14967/// The issue-search qualifier that keeps open issues alone, which a status filter naming only
14968/// categories an open issue reads as narrows a board-scoped search with.
14969const OPEN_QUALIFIER: &str = "is:open";
14970
14971/// What the board's open items are held under among the narrowed answers of one command — a
14972/// key no [`Narrowing`], each `origin …` or `search …`, can spell.
14973const OPEN_ITEMS_KEY: &str = "items is:open";
14974
14975/// The board filter `task status reconcile` reads the board through: closed items alone.
14976const CLOSED_FILTER: &str = "is:closed";
14977
14978/// The variables of one [`graphql::ISSUES_BY_REFERENCE`] request for `batch`: each slot names
14979/// one reference, and a slot the batch has none for names its last one again.
14980fn reference_batch(batch: &[IssueRef]) -> Value {
14981    let mut variables = serde_json::Map::new();
14982    for slot in 0..REFERENCE_BATCH {
14983        let issue = batch.get(slot).or(batch.last());
14984        variables.insert(format!("owner{slot}"), json!(issue.map(|i| &i.owner)));
14985        variables.insert(format!("name{slot}"), json!(issue.map(|i| &i.name)));
14986        variables.insert(format!("number{slot}"), json!(issue.map(|i| i.number)));
14987    }
14988    variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
14989    variables.insert("statusField".to_owned(), json!(STATUS_FIELD));
14990    variables.insert("duplicates".to_owned(), json!(true));
14991    Value::Object(variables)
14992}
14993
14994/// One issue an issue read by reference answered, in the shape every other read of an issue
14995/// hands its resolver: each board membership's `Status` value, read by name, as the one field
14996/// value that membership carries.
14997///
14998/// A membership's `status` is `null` when its card sits at no option — or on a board with no
14999/// field of that name — and otherwise an option value naming its option; anything else is not
15000/// an answer to this read, and is refused rather than read as a card at no option.
15001fn held_issue(issue: &Value) -> Result<Value, SourceError> {
15002    let malformed = |what: &str| SourceError::Malformed {
15003        message: format!("GitHub answered an issue read by reference with {what}"),
15004    };
15005    let mut issue = issue.clone();
15006    let nodes = issue
15007        .pointer_mut("/projectItems/nodes")
15008        .and_then(Value::as_array_mut)
15009        .ok_or_else(|| malformed("no list of board memberships"))?;
15010    for node in nodes {
15011        let node = node
15012            .as_object_mut()
15013            .ok_or_else(|| malformed("a board membership that is not an object"))?;
15014        let status = match node.get("status") {
15015            None => return Err(malformed("a board membership with no status member")),
15016            Some(Value::Null) => None,
15017            Some(status) if status.get("name").is_some_and(Value::is_string) => {
15018                Some(status.clone())
15019            }
15020            // A single-select value of another field type answers `{}`; only an option value
15021            // carries a name.
15022            Some(status) if status.as_object().is_some_and(serde_json::Map::is_empty) => None,
15023            Some(_) => return Err(malformed("a membership status that names no option")),
15024        };
15025        node.insert(
15026            "fieldValues".to_owned(),
15027            json!({"nodes": status.into_iter().collect::<Vec<_>>(),
15028                   "pageInfo": {"hasNextPage": false}}),
15029        );
15030    }
15031    Ok(issue)
15032}
15033
15034/// The issue one slot of a read by reference answered, `None` when GitHub answered that
15035/// slot's repository or issue `null` — which [`GitHubProjectsSource::answer_unresolved`]
15036/// admitted only beside a `NOT_FOUND` naming that very slot — and a refusal when the answer
15037/// leaves the slot, or its `issue` member, out: an answer missing a member is malformed rather
15038/// than a reference nothing holds.
15039fn referenced_issue(data: &Value, slot: usize) -> Result<Option<&Value>, SourceError> {
15040    let alias = format!("r{slot}");
15041    let repository = data.get(&alias).ok_or_else(|| SourceError::Malformed {
15042        message: format!("GitHub answered a read by reference with no {alias}"),
15043    })?;
15044    if repository.is_null() {
15045        return Ok(None);
15046    }
15047    let issue = repository
15048        .get("issue")
15049        .ok_or_else(|| SourceError::Malformed {
15050            message: format!("GitHub answered {alias} of a read by reference with no issue"),
15051        })?;
15052    if issue.is_null() {
15053        return Ok(None);
15054    }
15055    // `Repository.issue` is typed `Issue`, so anything else is not an answer to this read.
15056    if optional_str(issue, "__typename")? != Some("Issue") {
15057        return Err(SourceError::Malformed {
15058            message: format!(
15059                "GitHub answered {alias} of a read by reference with an issue whose __typename \
15060                 is not Issue"
15061            ),
15062        });
15063    }
15064    Ok(Some(issue))
15065}
15066
15067/// A closure reason as a person reads it: `NOT_PLANNED` as `not planned`.
15068fn spoken_reason(reason: &str) -> String {
15069    reason.to_ascii_lowercase().replace('_', " ")
15070}
15071
15072impl GitHubProjectsSource {
15073    /// Every task and project of this board whose card contradicts its issue's closure, each
15074    /// judged against its own kind's half of `status_mapping`, read through the board's own
15075    /// `is:closed` filter, page by page — never the board's unfiltered `items`.
15076    ///
15077    /// Each item the filter answers is confirmed from its own node: an open one, one whose
15078    /// closure reads `unknown`, and one whose card is already in line are left out whatever
15079    /// the filter let through. The board's fields ride along and are held for the option
15080    /// writes that follow, so those need no read of the board.
15081    async fn contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
15082        let mut after: Option<String> = None;
15083        let mut found = Vec::new();
15084        loop {
15085            let data = self
15086                .graphql(
15087                    graphql::CLOSED_ITEMS,
15088                    json!({"owner":self.owner,"number":self.project_number,
15089                           "first":MAX_PAGE_SIZE,"after":after,"filter":CLOSED_FILTER,
15090                           "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
15091                )
15092                .await?;
15093            let board = data
15094                .pointer("/closedItems/projectV2")
15095                .filter(|value| !value.is_null())
15096                .ok_or_else(|| SourceError::Refused {
15097                    message: format!(
15098                        "GitHub project {}/{} was not found or is not visible to the token",
15099                        self.owner, self.project_number
15100                    ),
15101                })?;
15102            *self.fields_cache()? = Some(BoardFields {
15103                id: BoardId::parse(required_str(board, "id")?)?,
15104                fields: board.get("fields").cloned().unwrap_or(Value::Null),
15105            });
15106            let items = board.get("items").ok_or_else(|| SourceError::Malformed {
15107                message: "GitHub project closed items are missing".into(),
15108            })?;
15109            for item in items
15110                .get("nodes")
15111                .and_then(Value::as_array)
15112                .ok_or_else(|| SourceError::Malformed {
15113                    message: "GitHub project items.nodes is not an array".into(),
15114                })?
15115            {
15116                let Some(resolved) = self.resolve(item)? else {
15117                    continue;
15118                };
15119                let BoardKind::Work(kind) = resolved.kind else {
15120                    continue;
15121                };
15122                let Some((closed_as, name)) = self.statuses.contradicted(
15123                    kind,
15124                    resolved.option.as_deref(),
15125                    resolved.closed,
15126                    resolved.reason.as_deref(),
15127                ) else {
15128                    continue;
15129                };
15130                found.push(StatusContradiction {
15131                    closed_as,
15132                    to: name.to_owned(),
15133                    option: resolved.option.clone(),
15134                    item: match kind {
15135                        ItemKind::Task => ContradictedItem::Task(resolved.task()?),
15136                        ItemKind::Project => ContradictedItem::Project(resolved.project()),
15137                    },
15138                });
15139            }
15140            let info = items
15141                .get("pageInfo")
15142                .ok_or_else(|| SourceError::Malformed {
15143                    message: "GitHub project items have no pageInfo".into(),
15144                })?;
15145            if !required_bool(info, "hasNextPage")? {
15146                return Ok(found);
15147            }
15148            let next = required_str(info, "endCursor")?;
15149            validate_cursor_progress(after.as_deref(), next)?;
15150            after = Some(next.to_owned());
15151        }
15152    }
15153
15154    /// What this board holds for each issue in `issues`, once each in the order given, read
15155    /// [`REFERENCE_BATCH`] references at a time — and nothing else of the board.
15156    ///
15157    /// An issue GitHub cannot find for this source's credential, and one with no item on this
15158    /// board, are both absent. A closure that already says the work will not be done here —
15159    /// not planned, duplicate — is skipped: a landing does not overrule it. An item closed as
15160    /// completed whose card sits at its kind's `done` option is unchanged, and every other item
15161    /// is due a `done` write. A project item — a plan's home card, its issue holding the plan's
15162    /// tasks as sub-issues — is held under exactly these rules, judged against the project
15163    /// kind's half of `status_mapping`.
15164    async fn holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
15165        let mut distinct: Vec<IssueRef> = Vec::with_capacity(issues.len());
15166        for issue in issues {
15167            if !distinct.contains(issue) {
15168                distinct.push(issue.clone());
15169            }
15170        }
15171        let done = |kind: ItemKind| {
15172            self.statuses
15173                .target(kind, StatusCategory::Done)
15174                .option()
15175                .unwrap_or("Done")
15176                .to_owned()
15177        };
15178        // GitHub numbers an issue with a GraphQL `Int`, a signed 32-bit value, so a reference past
15179        // its range names no issue any repository can hold: it is answered absent and never sent,
15180        // where binding it would have GitHub refuse the whole batch.
15181        let readable: Vec<IssueRef> = distinct
15182            .iter()
15183            .filter(|issue| i32::try_from(issue.number).is_ok())
15184            .cloned()
15185            .collect();
15186        let mut holdings = Vec::with_capacity(readable.len());
15187        for batch in readable.chunks(REFERENCE_BATCH) {
15188            let data = self
15189                .graphql(graphql::ISSUES_BY_REFERENCE, reference_batch(batch))
15190                .await?;
15191            for (slot, issue) in batch.iter().enumerate() {
15192                let node = referenced_issue(&data, slot)?;
15193                let resolved = match node {
15194                    Some(node) => self.resolve_issue_as(&held_issue(node)?, false).await?,
15195                    None => None,
15196                };
15197                // A task and a project are both held; a document is not work, so nothing is.
15198                let Some((item, kind)) = resolved.and_then(|item| match item.kind {
15199                    BoardKind::Work(kind) => Some((item, kind)),
15200                    BoardKind::Document => None,
15201                }) else {
15202                    holdings.push(IssueHolding {
15203                        issue: issue.clone(),
15204                        completion: Completion::Absent,
15205                    });
15206                    continue;
15207                };
15208                let task = match kind {
15209                    ItemKind::Task => {
15210                        let held = item.task()?;
15211                        HeldTask {
15212                            id: held.id,
15213                            kind,
15214                            option: item.option.clone(),
15215                            classification: held.classification,
15216                            repositories: held.repositories,
15217                            delivers: held.delivers,
15218                        }
15219                    }
15220                    // A project delivers no task, so what its write keeps in step is nothing.
15221                    ItemKind::Project => {
15222                        let held = item.project();
15223                        HeldTask {
15224                            id: held.id,
15225                            kind,
15226                            option: item.option.clone(),
15227                            classification: held.classification,
15228                            repositories: held.repositories,
15229                            delivers: Vec::new(),
15230                        }
15231                    }
15232                };
15233                let done = done(kind);
15234                let completion = match (item.closed, item.reason.as_deref()) {
15235                    (true, Some(reason @ ("NOT_PLANNED" | "DUPLICATE"))) => Completion::Skipped {
15236                        task,
15237                        reason: format!("closed as {}", spoken_reason(reason)),
15238                    },
15239                    (true, None | Some("COMPLETED"))
15240                        if item
15241                            .option
15242                            .as_deref()
15243                            .is_some_and(|option| option.eq_ignore_ascii_case(&done)) =>
15244                    {
15245                        Completion::Unchanged { task }
15246                    }
15247                    _ => {
15248                        let kept = item.clone();
15249                        self.held_cache
15250                            .lock()
15251                            .map_err(|_| SourceError::Unavailable {
15252                                message: "items read by issue reference were left \
15253                                          inconsistent; run the command again"
15254                                    .into(),
15255                            })?
15256                            .insert(kept.id.clone(), kept);
15257                        Completion::Due {
15258                            task,
15259                            to: done.clone(),
15260                        }
15261                    }
15262                };
15263                holdings.push(IssueHolding {
15264                    issue: issue.clone(),
15265                    completion,
15266                });
15267            }
15268        }
15269        let mut read = holdings.into_iter();
15270        let mut answered = Vec::with_capacity(distinct.len());
15271        for issue in distinct {
15272            if i32::try_from(issue.number).is_ok() {
15273                answered.push(read.next().ok_or_else(|| SourceError::Malformed {
15274                    message: format!("no holding was read for {issue}"),
15275                })?);
15276            } else {
15277                answered.push(IssueHolding {
15278                    issue,
15279                    completion: Completion::Absent,
15280                });
15281            }
15282        }
15283        Ok(answered)
15284    }
15285}
15286
15287#[async_trait::async_trait]
15288impl TaskSource for GitHubProjectsSource {
15289    fn kind(&self) -> &'static str {
15290        KIND
15291    }
15292    /// GitHub's issue search, which narrows a read of the comments made since an instant, is
15293    /// an index behind the writes it indexes — the credentialed lane has watched it miss a newly
15294    /// commented issue for thirty seconds — so a watermark is set back by
15295    /// [`COMMENT_SEARCH_LAG`], four times that.
15296    fn comment_consistency_window(&self) -> std::time::Duration {
15297        COMMENT_SEARCH_LAG
15298    }
15299    /// The `Date` of the last answer GitHub gave this source.
15300    fn served_at(&self) -> Option<DateTime<Utc>> {
15301        *self
15302            .last_served
15303            .lock()
15304            .unwrap_or_else(std::sync::PoisonError::into_inner)
15305    }
15306    fn attach_body_markup(&self, markup: onetaskgraph_plugin_api::SharedBodyMarkup) {
15307        let _ = self.body_markup.set(markup);
15308    }
15309    fn order_versions(&self, a: &str, b: &str) -> Option<std::cmp::Ordering> {
15310        change_token::order(a, b)
15311    }
15312    /// A task's fields and comments: §4.13d of `docs/plugin-protocol.md` states, member by
15313    /// member, the change each part of the token moves for. Not its forward edges — see
15314    /// [`FAR_ENDS_UNCOVERED`].
15315    fn version_coverage(&self) -> VersionCoverage {
15316        VersionCoverage {
15317            forward_edges: Coverage::Uncovered {
15318                reason: FAR_ENDS_UNCOVERED.to_owned(),
15319            },
15320            ..VersionCoverage::whole()
15321        }
15322    }
15323    /// Every part, for a copy's skip: the relationship count moves for an edge added or removed
15324    /// and for a far end deleted, so the token sees every change to a task's edges but one — a
15325    /// far end's own kind flipping, by gaining a sub-issue or being retitled into a document,
15326    /// which `spike-coverage` measured stale 1 of 1. A skipping recopy does not carry that, and
15327    /// the next copy that reads the task does (`docs/plugin-protocol.md` §4.13d).
15328    // 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.
15329    fn copy_version_coverage(&self) -> VersionCoverage {
15330        VersionCoverage::whole()
15331    }
15332    /// A project's fields, and not its forward edges, for the same reason a task's are not.
15333    fn project_version_coverage(&self) -> ProjectVersionCoverage {
15334        ProjectVersionCoverage {
15335            fields: Coverage::Covered,
15336            forward_edges: Coverage::Uncovered {
15337                reason: FAR_ENDS_UNCOVERED.to_owned(),
15338            },
15339        }
15340    }
15341    /// A document's fields and the manifest of its image assets, which its metadata slot
15342    /// records: both are the issue's body, whose every edit moves the token's issue time.
15343    fn document_version_coverage(&self) -> DocumentVersionCoverage {
15344        DocumentVersionCoverage::whole()
15345    }
15346    fn write_context(&self, id: &NativeId) -> Option<Value> {
15347        self.context_of(id)
15348    }
15349    fn board_context(&self) -> Option<Value> {
15350        self.board_context_held()
15351    }
15352    fn prime_write(&self, id: &NativeId, context: &Value, board: Option<&Value>) -> bool {
15353        self.prime(id, context, board)
15354    }
15355    fn unprime(&self, id: &NativeId) {
15356        self.unprime_held(id);
15357    }
15358    fn placement_context(&self) -> Option<Value> {
15359        self.placement_held()
15360    }
15361    fn prime_placement(&self, context: &Value) -> bool {
15362        self.prime_placement_held(context)
15363    }
15364    fn written_context(&self, id: &NativeId) -> Option<Value> {
15365        self.written_held(id)
15366    }
15367    fn prime_written(&self, id: &NativeId, context: &Value, task: &Task) -> bool {
15368        self.prime_written_held(id, context, task)
15369    }
15370    fn begin_journal(&self) {
15371        self.expected.begin();
15372    }
15373    fn end_journal(&self) -> Option<WriteJournal> {
15374        Some(self.expected.end())
15375    }
15376    fn capabilities(&self) -> Capabilities {
15377        Capabilities {
15378            projects: Support::Native,
15379            documents: Support::Native,
15380            comments: Support::Native,
15381            assets: Support::Native,
15382            priority: if self.priorities.is_some() {
15383                Support::Native
15384            } else {
15385                Support::Unsupported
15386            },
15387            filter_by_priority: Support::Native,
15388            filter_by_comment_activity: Support::Native,
15389            filter_by_metadata: Support::Native,
15390            filter_by_origin: Support::Native,
15391            reconcile_status: Support::Native,
15392            complete_by_issue: Support::Native,
15393            orphan_tasks: Support::Native,
15394            filter_by_label: Support::Native,
15395            filter_by_status: Support::Native,
15396            search_title: Support::Native,
15397            search_content: Support::Native,
15398            task_dependencies: DependencySupport::BothDirections,
15399            project_dependencies: DependencySupport::BothDirections,
15400            max_page_size: MAX_PAGE_SIZE,
15401            assignees: if self.assignees {
15402                Support::Native
15403            } else {
15404                Support::Unsupported
15405            },
15406        }
15407    }
15408    async fn visibility(
15409        &self,
15410        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15411    ) -> Result<onetaskgraph_plugin_api::Visibility, SourceError> {
15412        self.write_visibility(target).await
15413    }
15414    async fn visibility_with_project(
15415        &self,
15416        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15417        project: &onetaskgraph_plugin_api::WriteTarget<'_>,
15418    ) -> Result<onetaskgraph_plugin_api::Visibility, SourceError> {
15419        self.write_visibility_with_project(target, project).await
15420    }
15421    fn declare_visibility(&self, declared: onetaskgraph_plugin_api::Visibility) {
15422        self.declared_private.store(
15423            declared == onetaskgraph_plugin_api::Visibility::Private,
15424            std::sync::atomic::Ordering::SeqCst,
15425        );
15426    }
15427    fn scope_visibility<'a>(
15428        &'a self,
15429        operation: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>>,
15430    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>> {
15431        self.scope_visibility_reads(operation)
15432    }
15433
15434    /// Where a create of `target` would file its issue, by [`Self::creation_rule`] — the rule
15435    /// the create applies — reading the parent project's issue only when `target` names one.
15436    async fn creation_repository(
15437        &self,
15438        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15439    ) -> Result<Option<Repository>, SourceError> {
15440        let onetaskgraph_plugin_api::WriteTarget::New {
15441            repositories,
15442            project,
15443        } = target
15444        else {
15445            return Ok(None);
15446        };
15447        let target = self
15448            .creation_rule(repositories, *project, "a new item")
15449            .await?;
15450        Repository::try_from(target.origin())
15451            .map(Some)
15452            .map_err(|message| SourceError::Malformed { message })
15453    }
15454    /// Every issue of the repository a create of `target` files in whose body carries `key` in
15455    /// its metadata slot, read off that repository's issues newest first back to `since` —
15456    /// never through search, whose index lags a fresh issue by seconds.
15457    async fn created_with_key(
15458        &self,
15459        record: onetaskgraph_plugin_api::MetadataRecord,
15460        key: &str,
15461        since: Option<DateTime<Utc>>,
15462        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15463    ) -> Result<Vec<NativeId>, SourceError> {
15464        let _ = record;
15465        let onetaskgraph_plugin_api::WriteTarget::New {
15466            repositories,
15467            project,
15468        } = target
15469        else {
15470            return Ok(Vec::new());
15471        };
15472        let repository = self
15473            .creation_rule(repositories, *project, "a new item")
15474            .await?;
15475        let wanted = Value::String(key.to_owned());
15476        let mut found = Vec::new();
15477        let mut after: Option<String> = None;
15478        let mut followed = std::collections::HashSet::new();
15479        loop {
15480            let data = self
15481                .graphql(
15482                    graphql::ISSUES_BY_CREATION,
15483                    json!({"owner": repository.owner, "name": repository.name,
15484                           "first": MAX_PAGE_SIZE, "after": after}),
15485                )
15486                .await?;
15487            let issues =
15488                data.pointer("/repository/issues")
15489                    .ok_or_else(|| SourceError::Malformed {
15490                        message: format!(
15491                            "GitHub answered no issues for repository {}",
15492                            repository.slug()
15493                        ),
15494                    })?;
15495            let malformed = |what: &str| SourceError::Malformed {
15496                message: format!(
15497                    "GitHub answered a page of repository {}'s issues {what}",
15498                    repository.slug()
15499                ),
15500            };
15501            let nodes = issues
15502                .get("nodes")
15503                .and_then(Value::as_array)
15504                .ok_or_else(|| malformed("with no list of issues"))?;
15505            let mut older = false;
15506            for node in nodes {
15507                let id = node
15508                    .get("id")
15509                    .and_then(Value::as_str)
15510                    .filter(|id| !id.is_empty())
15511                    .ok_or_else(|| malformed("holding an issue with no id"))?;
15512                let created = optional_time(node, "createdAt")?
15513                    .ok_or_else(|| malformed("holding an issue with no creation time"))?;
15514                if since.is_some_and(|since| created < since) {
15515                    older = true;
15516                    break;
15517                }
15518                let body = match node.get("body") {
15519                    Some(Value::String(body)) => Some(body.clone()),
15520                    Some(Value::Null) => None,
15521                    _ => return Err(malformed("holding an issue with no body member")),
15522                };
15523                let (_, metadata) = metadata_body(body)?;
15524                if metadata.get(MetadataKey::CREATE_KEY) == Some(&wanted) {
15525                    found.push(NativeId(id.to_owned()));
15526                }
15527            }
15528            let next = issues
15529                .pointer("/pageInfo/hasNextPage")
15530                .and_then(Value::as_bool)
15531                .ok_or_else(|| malformed("that does not say whether another follows"))?;
15532            if older || !next {
15533                return Ok(found);
15534            }
15535            // A page that says another follows names where it starts, and never a page already
15536            // read: anything else would ask for the same pages again for ever.
15537            let cursor = issues
15538                .pointer("/pageInfo/endCursor")
15539                .and_then(Value::as_str)
15540                .filter(|cursor| !cursor.is_empty())
15541                .map(str::to_owned);
15542            if cursor
15543                .as_ref()
15544                .is_none_or(|cursor| !followed.insert(cursor.clone()))
15545            {
15546                return Err(SourceError::Malformed {
15547                    message: format!(
15548                        "GitHub answered a page of repository {}'s issues that says another \
15549                         follows without a new cursor to it",
15550                        repository.slug()
15551                    ),
15552                });
15553            }
15554            after = cursor;
15555        }
15556    }
15557
15558    /// `Repository.issues` lists an issue GitHub committed only once its listing catches up.
15559    fn create_key_lags(&self) -> bool {
15560        true
15561    }
15562
15563    /// The task as this process's own latest write of it left it, from the item it recorded
15564    /// that write as — never a request. Its `version` is always `None`: a board's change token
15565    /// is given only once an item has gone unchanged for [`change_token::SETTLED`], which an
15566    /// item this command has just written has not, so no write's own answer can vouch for one.
15567    async fn written_task(&self, id: &NativeId) -> Option<Task> {
15568        let held = self
15569            .created()
15570            .ok()?
15571            .iter()
15572            .find(|held| held.id == *id)
15573            .cloned()
15574            .or_else(|| {
15575                self.updated()
15576                    .ok()?
15577                    .iter()
15578                    .find(|held| held.id == *id)
15579                    .cloned()
15580            })?;
15581        let mut task = held.task().ok()?;
15582        task.version = self.written_token(id);
15583        Some(task)
15584    }
15585
15586    /// Why `creation_owners` refuses a create of `target`, by [`Self::creation_rule`] — read
15587    /// only when the list is not empty, so a source restricting nothing reads nothing.
15588    async fn creation_refusal(
15589        &self,
15590        target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15591    ) -> Result<Option<String>, SourceError> {
15592        let onetaskgraph_plugin_api::WriteTarget::New {
15593            repositories,
15594            project,
15595        } = target
15596        else {
15597            return Ok(None);
15598        };
15599        if self.creation_owners.is_empty() {
15600            return Ok(None);
15601        }
15602        let target = self
15603            .creation_rule(repositories, *project, "a new item")
15604            .await?;
15605        Ok(self.owner_refusal(&target))
15606    }
15607
15608    async fn health(&self) -> Result<Health, SourceError> {
15609        let board = self.board_page(None, 1).await?;
15610        Ok(Health {
15611            reachable: true,
15612            detail: Some(format!(
15613                "reading GitHub project {}/{} ({})",
15614                self.owner,
15615                self.project_number,
15616                required_str(&board, "title")?
15617            )),
15618        })
15619    }
15620    /// The board's own node id, digested: the one request reading its fields, or none when
15621    /// this command has read them already.
15622    async fn designator(&self) -> Result<Option<Designator>, SourceError> {
15623        let board = self.board_fields().await?;
15624        Designator::of_backend(KIND, board.id.as_str())
15625            .map(Some)
15626            .map_err(|message| SourceError::Malformed { message })
15627    }
15628    async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError> {
15629        self.item_by_id(id)
15630            .await?
15631            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
15632            .map(|item| item.task())
15633            .transpose()
15634    }
15635    async fn task_assets(
15636        &self,
15637        id: &NativeId,
15638    ) -> Result<Vec<onetaskgraph_plugin_api::Asset>, SourceError> {
15639        self.held_assets(id, BoardKind::Work(ItemKind::Task)).await
15640    }
15641    async fn task_asset(
15642        &self,
15643        id: &NativeId,
15644        name: &onetaskgraph_plugin_api::AssetName,
15645    ) -> Result<Option<Vec<u8>>, SourceError> {
15646        self.held_asset(id, BoardKind::Work(ItemKind::Task), name)
15647            .await
15648    }
15649    async fn set_task_rendering_with_assets(
15650        &self,
15651        id: &NativeId,
15652        content: &str,
15653        provenance: &Value,
15654        _answers: &BTreeMap<String, Value>,
15655        assets: &onetaskgraph_plugin_api::AssetWrite,
15656    ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
15657        self.replace_rendering(
15658            id,
15659            BoardKind::Work(ItemKind::Task),
15660            content,
15661            provenance,
15662            Some(assets),
15663        )
15664        .await
15665    }
15666    async fn document_assets(
15667        &self,
15668        id: &NativeId,
15669    ) -> Result<Vec<onetaskgraph_plugin_api::Asset>, SourceError> {
15670        self.held_assets(id, BoardKind::Document).await
15671    }
15672    async fn document_asset(
15673        &self,
15674        id: &NativeId,
15675        name: &onetaskgraph_plugin_api::AssetName,
15676    ) -> Result<Option<Vec<u8>>, SourceError> {
15677        self.held_asset(id, BoardKind::Document, name).await
15678    }
15679    async fn set_document_rendering_with_assets(
15680        &self,
15681        id: &NativeId,
15682        content: &str,
15683        provenance: &Value,
15684        _answers: &BTreeMap<String, Value>,
15685        assets: &onetaskgraph_plugin_api::AssetWrite,
15686    ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
15687        self.replace_rendering(id, BoardKind::Document, content, provenance, Some(assets))
15688            .await
15689    }
15690    async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError> {
15691        Ok(self
15692            .item_by_id(id)
15693            .await?
15694            .filter(|item| item.kind == BoardKind::Work(ItemKind::Project))
15695            .map(|item| item.project()))
15696    }
15697    /// Every narrowed search and origin lookup asked, a page at a time, as aliased fields of one
15698    /// [`graphql::SEARCH_BATCH`] request a round — a search's issue search in an `s<n>` field,
15699    /// an origin's board filter in an `o<n>` field beside its issue search — and every other
15700    /// query by [`Self::query_tasks`] on its own: one narrowed by a project or by comment
15701    /// activity, one carrying no narrowing, one resumed from a cursor that read handed out, and
15702    /// every query of a process that has written this board, whose own writes complete a
15703    /// narrowed answer.
15704    ///
15705    /// Each page asks all the rows its search still lacks, up to [`MAX_PAGE_SIZE`], and reads
15706    /// which issues match alone; the distinct issues every search of the call hit are then read
15707    /// whole, [`DETAIL_BATCH`] to a [`graphql::ISSUE_DETAILS`] request, each once. GitHub
15708    /// answers an error about one aliased field at that field's path, beside the others'
15709    /// answers, so a refused page fails that query's answer alone; a request it refuses whole is
15710    /// every query of that request's answer, and a detail read it refuses is the answer of
15711    /// every query that hit one of its issues.
15712    async fn query_tasks_batch(
15713        &self,
15714        asks: &[(TaskQuery, PageRequest)],
15715    ) -> Vec<Result<Page<Task>, SourceError>> {
15716        self.search_batched(asks).await
15717    }
15718    async fn query_tasks(
15719        &self,
15720        query: &TaskQuery,
15721        page: &PageRequest,
15722    ) -> Result<Page<Task>, SourceError> {
15723        validate_page(page)?;
15724        refuse_unsearchable(query)?;
15725        // A closed issue reads `done`, `cancelled` or — closed for a reason that implies no
15726        // category — `unknown`; every other category reads only off an open issue or a draft. So
15727        // a status filter naming none of those three asks every issue search it sends for open
15728        // issues alone; each candidate's category is still confirmed from its own item below.
15729        let open_only = open_only(query);
15730        if query.origin.is_none()
15731            && !matches!(query.project, ProjectFilter::Is(_))
15732            && let Some(also) = search_qualifiers(query)
15733        {
15734            return self.search_tasks(query, page, &also).await;
15735        }
15736
15737        // A read narrowed to one project asks that project for its own tasks, so nothing
15738        // about it costs what the rest of the board holds. A read carrying a text, metadata
15739        // or origin predicate asks GitHub the narrower question those predicates are, and a
15740        // read narrowed to comment activity alone asks the board's own issue search for the
15741        // issues updated since, which is every issue a comment could have been written or
15742        // edited on since. Every other task read is a question about the whole board and is
15743        // answered by reading it.
15744        let (held, membership) = match (&query.project, query.commented_since) {
15745            (ProjectFilter::Is(project), _) => (
15746                match self.held_task_children(project)? {
15747                    // Taken as `project_children` takes the project's own sub-issue read: with
15748                    // every item this process wrote under it since, and none it moved away.
15749                    Some(held) => self.completed_with_written(
15750                        held.into_iter()
15751                            .filter(|child| child.parent.as_ref() == Some(project))
15752                            .collect(),
15753                        |own| own.parent.as_ref() == Some(project),
15754                    )?,
15755                    None => self.project_children(project).await?,
15756                },
15757                // Answered by where these items came from; see `task_matches`.
15758                &ProjectFilter::Any,
15759            ),
15760            (ProjectFilter::Any | ProjectFilter::Orphans, since) => {
15761                match (self.narrowed(query).await?, since) {
15762                    (Some(narrowed), _) => (narrowed, &query.project),
15763                    (None, Some(since)) => (self.updated_since(since).await?, &query.project),
15764                    // The board's own items list every draft; only the search half, which
15765                    // completes them with issues they lag behind on, is narrowed — a closed
15766                    // issue that half leaves out is at no category the filter keeps.
15767                    // Every category it keeps reads only off an open item, so it reads the
15768                    // board's open items alone, through the board's own filter.
15769                    (None, None) if open_items_only(query) => {
15770                        (self.open_items().await?, &query.project)
15771                    }
15772                    (None, None) if open_only => (
15773                        self.board_completed_by(Some(OPEN_QUALIFIER)).await?.items,
15774                        &query.project,
15775                    ),
15776                    (None, None) => (self.board().await?.items, &query.project),
15777                }
15778            }
15779        };
15780        // Every candidate this read confirms by its comments is read together.
15781        let candidates = self.comment_candidates(held.iter(), query, membership)?;
15782        self.hold_comment_pages(&candidates).await?;
15783        // Filtered before paged: a page of a filtered result is a page of the survivors,
15784        // never the survivors of a page.
15785        let mut tasks = Vec::new();
15786        for item in held
15787            .iter()
15788            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
15789        {
15790            let task = item.task()?;
15791            if task_matches(&task, query, membership)
15792                && self.commented_since(item, query.commented_since).await?
15793            {
15794                tasks.push(task);
15795            }
15796        }
15797        Ok(offset_page(
15798            tasks,
15799            numeric_cursor(page.cursor.as_ref())?,
15800            page.limit.min(MAX_PAGE_SIZE) as usize,
15801        ))
15802    }
15803    /// Read board pages directly, at the board connection's consistency. Unlike
15804    /// `query_tasks`, this does not complete a lagging board with issue search: a complete
15805    /// sweep needs one request per listing page, including the first comments.
15806    async fn query_task_details(
15807        &self,
15808        query: &TaskQuery,
15809        page: &PageRequest,
15810        comments: Option<&PageRequest>,
15811    ) -> Result<Page<TaskDetailRead>, SourceError> {
15812        let Some(comments) = comments else {
15813            let tasks = self.query_tasks(query, page).await?;
15814            return Ok(Page {
15815                items: tasks
15816                    .items
15817                    .into_iter()
15818                    .map(|task| TaskDetailRead {
15819                        task,
15820                        comments: None,
15821                    })
15822                    .collect(),
15823                next: tasks.next,
15824            });
15825        };
15826        validate_page(page)?;
15827        validate_page(comments)?;
15828        refuse_unsearchable(query)?;
15829        if comments.cursor.is_some() || query.commented_since.is_some() {
15830            return Err(SourceError::Refused {
15831                message: "a board listing with comments requires a first comment page and cannot filter by comment activity".into(),
15832            });
15833        }
15834        let after = page.cursor.as_ref().map(|cursor| cursor.0.as_str());
15835        let data = self
15836            .graphql(
15837                graphql::BOARD_WITH_COMMENTS,
15838                json!({
15839                    "owner":self.owner,"number":self.project_number,
15840                    "first":page.limit.min(MAX_PAGE_SIZE),"after":after,
15841                    "commentFirst":comments.limit.min(MAX_PAGE_SIZE),
15842                    "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true,
15843                }),
15844            )
15845            .await?;
15846        let connection = data
15847            .pointer("/owner/projectV2/items")
15848            .filter(|value| !value.is_null())
15849            .ok_or_else(|| SourceError::Refused {
15850                message: "GitHub project was not found or is not visible to the token".into(),
15851            })?;
15852        let mut items = Vec::new();
15853        for node in optional_nodes(Some(connection), "board items")?
15854            .into_iter()
15855            .flatten()
15856        {
15857            let Some(item) = self.resolve(node)? else {
15858                continue;
15859            };
15860            if item.kind != BoardKind::Work(ItemKind::Task) {
15861                continue;
15862            }
15863            let task = item.task()?;
15864            if !task_matches(&task, query, &query.project) {
15865                continue;
15866            }
15867            let read = if item.content_kind == ContentKind::DraftIssue {
15868                Err(self.draft_has_no_comments(&task.id))
15869            } else {
15870                self.expected.learn_comments(&task.id, &node["content"]);
15871                comment_page(&node["content"], &task.id.0, None).map(Some)
15872            };
15873            items.push(TaskDetailRead {
15874                task,
15875                comments: Some(read),
15876            });
15877        }
15878        let next = next_cursor(connection)?;
15879        if let Some(next) = &next {
15880            validate_cursor_progress(after, &next.0)?;
15881        }
15882        Ok(Page { items, next })
15883    }
15884
15885    async fn query_projects(
15886        &self,
15887        query: &ProjectQuery,
15888        page: &PageRequest,
15889    ) -> Result<Page<Project>, SourceError> {
15890        validate_page(page)?;
15891        refuse_unsearchable_text(query.text.as_ref())?;
15892        // The projects a board holds are found by an issue search scoped to that board,
15893        // never by walking the board's own item connection: what tells a project from a
15894        // task is the `parent` each issue carries, which costs nothing to read. A query
15895        // carrying a text asks that search for the text too, so it reads the issues that
15896        // hold it rather than every issue of the board.
15897        let held = match self.text_searched(query.text.as_ref()).await? {
15898            Some(searched) => searched,
15899            None => self.board_issues().await?,
15900        };
15901        let projects = held
15902            .iter()
15903            .filter(|item| item.kind == BoardKind::Work(ItemKind::Project))
15904            .map(Resolved::project)
15905            .filter(|project| project_matches(project, query))
15906            .collect();
15907        Ok(offset_page(
15908            projects,
15909            numeric_cursor(page.cursor.as_ref())?,
15910            page.limit.min(MAX_PAGE_SIZE) as usize,
15911        ))
15912    }
15913    async fn query_projects_by_origin(
15914        &self,
15915        origin: &str,
15916        page: &PageRequest,
15917    ) -> Result<Page<Project>, SourceError> {
15918        validate_page(page)?;
15919        let projects = self
15920            .copied_from(origin, BoardKind::Work(ItemKind::Project))
15921            .await?
15922            .iter()
15923            .map(Resolved::project)
15924            .collect();
15925        Ok(offset_page(
15926            projects,
15927            numeric_cursor(page.cursor.as_ref())?,
15928            page.limit.min(MAX_PAGE_SIZE) as usize,
15929        ))
15930    }
15931    async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
15932        let Some(item) = self
15933            .document_by_id(id)
15934            .await?
15935            .filter(|item| item.kind == BoardKind::Document)
15936        else {
15937            return Ok(None);
15938        };
15939        self.expected.read_document(&item);
15940        Ok(Some(item.document()))
15941    }
15942    async fn query_documents_by_origin(
15943        &self,
15944        origin: &str,
15945        page: &PageRequest,
15946    ) -> Result<Page<Document>, SourceError> {
15947        validate_page(page)?;
15948        let documents = self
15949            .copied_from(origin, BoardKind::Document)
15950            .await?
15951            .iter()
15952            .map(Resolved::document)
15953            .collect();
15954        Ok(offset_page(
15955            documents,
15956            numeric_cursor(page.cursor.as_ref())?,
15957            page.limit.min(MAX_PAGE_SIZE) as usize,
15958        ))
15959    }
15960    async fn query_documents(
15961        &self,
15962        query: &DocumentQuery,
15963        page: &PageRequest,
15964    ) -> Result<Page<Document>, SourceError> {
15965        validate_page(page)?;
15966        // Narrowed to one project, this is the same sub-issue read a task list scoped to
15967        // that project makes — a document filed under a project is a sub-issue of it too,
15968        // and which of them come back is the kind this caller asked for. Unscoped, a query
15969        // carrying a text asks the board-scoped issue search for it, as a task query does,
15970        // and only one carrying none reads the board.
15971        let (held, membership) = match &query.project {
15972            ProjectFilter::Is(project) => (
15973                self.project_children(project).await?,
15974                // Answered by where these items came from; see `task_matches`.
15975                &ProjectFilter::Any,
15976            ),
15977            ProjectFilter::Any | ProjectFilter::Orphans => {
15978                refuse_unsearchable_text(query.text.as_ref())?;
15979                match self.text_searched(query.text.as_ref()).await? {
15980                    Some(searched) => (searched, &query.project),
15981                    None => (self.board().await?.items, &query.project),
15982                }
15983            }
15984        };
15985        // Filtered before paged, exactly as a task read is: a page of a filtered result is
15986        // a page of the survivors, never the survivors of a page.
15987        let documents = held
15988            .iter()
15989            .filter(|item| item.kind == BoardKind::Document)
15990            .map(Resolved::document)
15991            .filter(|document| document_matches(document, query, membership))
15992            .collect();
15993        Ok(offset_page(
15994            documents,
15995            numeric_cursor(page.cursor.as_ref())?,
15996            page.limit.min(MAX_PAGE_SIZE) as usize,
15997        ))
15998    }
15999    async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError> {
16000        validate_page(page)?;
16001        let offset = numeric_cursor(page.cursor.as_ref())?;
16002        let mut labels = self
16003            .board()
16004            .await?
16005            .items
16006            .into_iter()
16007            .flat_map(|item| item.labels)
16008            .fold(Vec::new(), |mut all, label| {
16009                if !all.iter().any(|x: &Label| x.id == label.id) {
16010                    all.push(label);
16011                }
16012                all
16013            });
16014        labels.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.0.cmp(&b.id.0)));
16015        Ok(offset_page(
16016            labels,
16017            offset,
16018            page.limit.min(MAX_PAGE_SIZE) as usize,
16019        ))
16020    }
16021    async fn task_dependencies(
16022        &self,
16023        id: &NativeId,
16024        direction: Direction,
16025        page: &PageRequest,
16026    ) -> Result<Page<DependencyEdge>, SourceError> {
16027        self.dependencies(id, ItemKind::Task, direction, page).await
16028    }
16029    async fn project_dependencies(
16030        &self,
16031        id: &NativeId,
16032        direction: Direction,
16033        page: &PageRequest,
16034    ) -> Result<Page<DependencyEdge>, SourceError> {
16035        self.dependencies(id, ItemKind::Project, direction, page)
16036            .await
16037    }
16038
16039    fn writes(&self) -> WriteSupport {
16040        WriteSupport::Supported
16041    }
16042
16043    /// Create or update one task.
16044    ///
16045    /// Its `delivers` and `delivered_by` are checked before anything is read or written —
16046    /// neither may name the task itself or name one task twice — and land in the body's
16047    /// metadata slot under their reserved keys, in place of any caller metadata of those
16048    /// names.
16049    async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
16050        if write.item.project.is_some() {
16051            self.projectless()?;
16052        }
16053        self.write_task_assets(write, None)
16054            .await
16055            .map(|written| written.id)
16056    }
16057
16058    async fn read_ahead_origins_for_copy(&self, origins: &[String]) -> Result<(), SourceError> {
16059        self.origins_ahead(origins).await
16060    }
16061
16062    async fn member_classifications(
16063        &self,
16064        project: &NativeId,
16065    ) -> Result<Option<Vec<(Classification, Vec<Repository>)>>, SourceError> {
16066        Ok(self
16067            .member_classes
16068            .lock()
16069            .map_err(|_| SourceError::Unavailable {
16070                message: "a project's members held for its classification were left \
16071                          inconsistent; run the command again"
16072                    .into(),
16073            })?
16074            .remove(project))
16075    }
16076
16077    /// The issue's own web address, as the `createIssue` that made it in this command answered
16078    /// it: a task, a project and a document are each an issue here.
16079    fn written_location(
16080        &self,
16081        _record: onetaskgraph_plugin_api::MetadataRecord,
16082        id: &NativeId,
16083    ) -> Option<Location> {
16084        self.written
16085            .lock()
16086            .unwrap_or_else(std::sync::PoisonError::into_inner)
16087            .get(id)
16088            .cloned()
16089            .map(Location::Url)
16090    }
16091
16092    /// [`MUTATION_BATCH`], while writes are held back: [`graphql::CREATE_ISSUES`] creates that many
16093    /// in one request, and a copy's tasks are created together only then, since their fields
16094    /// and edges are what is held back.
16095    fn create_batch_limit(&self) -> usize {
16096        if self.deferring().unwrap_or(false) {
16097            MUTATION_BATCH
16098        } else {
16099            1
16100        }
16101    }
16102
16103    // 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.
16104    async fn write_tasks(&self, writes: &[ItemWrite<Task>]) -> Result<Vec<NativeId>, SourceError> {
16105        if writes.iter().any(|write| write.item.project.is_some()) {
16106            self.projectless()?;
16107        }
16108        if let Some(write) = writes.iter().find(|write| write.target.is_some()) {
16109            return Err(SourceError::Refused {
16110                message: format!(
16111                    "write_tasks creates tasks, and the write of {} names the existing task {}; \
16112                     next: update it with write_task",
16113                    write.item.id,
16114                    write.target.as_ref().map_or("", |target| target.0.as_str())
16115                ),
16116            });
16117        }
16118        if !self.deferring()? {
16119            let mut created = Vec::with_capacity(writes.len());
16120            for write in writes {
16121                match self.write_task(write).await {
16122                    Ok(id) => created.push(id),
16123                    Err(error) => {
16124                        let mut left: Vec<&str> = Vec::new();
16125                        for id in &created {
16126                            if self.delete_issue(id).await.is_err() {
16127                                left.push(id.0.as_str());
16128                            }
16129                        }
16130                        return Err(left_behind(error, &left));
16131                    }
16132                }
16133            }
16134            return Ok(created);
16135        }
16136        self.create_together(writes).await
16137    }
16138
16139    fn begin_deferred_writes(&self) {
16140        if let Ok(mut deferred) = self.deferred.lock() {
16141            deferred.get_or_insert_with(Deferred::default);
16142        }
16143    }
16144
16145    async fn finish_writes(&self) -> Result<(), SourceError> {
16146        self.send_held_updates().await?;
16147        self.send_held_back().await
16148    }
16149
16150    async fn write_task_with_assets(
16151        &self,
16152        write: &ItemWrite<Task>,
16153        _answers: Option<&BTreeMap<String, Value>>,
16154        assets: &onetaskgraph_plugin_api::AssetWrite,
16155    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
16156        self.write_task_assets(write, Some(assets)).await
16157    }
16158
16159    async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
16160        self.projectless()?;
16161        self.write_item(
16162            &Incoming {
16163                written: Written::Work(ItemKind::Project, &write.item.status),
16164                title: &write.item.title,
16165                content: write.item.content.as_deref(),
16166                assets: None,
16167                labels: &write.item.labels,
16168                metadata: &write.item.metadata,
16169                repositories: &write.item.repositories,
16170                classification: write.item.classification,
16171                parent: None,
16172                delivers: &[],
16173                delivered_by: &[],
16174                priority: None,
16175                assignees: None,
16176            },
16177            write.target.as_ref(),
16178            &write.depends_on,
16179        )
16180        .await
16181        .map(|written| written.id)
16182    }
16183
16184    fn task_body_size(
16185        &self,
16186        write: &ItemWrite<Task>,
16187        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
16188    ) -> Option<onetaskgraph_plugin_api::BodySize> {
16189        Some(self.body_size(&self.task_incoming(write, assets).ok()?))
16190    }
16191
16192    fn project_body_size(
16193        &self,
16194        write: &ItemWrite<Project>,
16195    ) -> Option<onetaskgraph_plugin_api::BodySize> {
16196        Some(self.body_size(&Incoming {
16197            written: Written::Work(ItemKind::Project, &write.item.status),
16198            title: &write.item.title,
16199            content: write.item.content.as_deref(),
16200            assets: None,
16201            labels: &write.item.labels,
16202            metadata: &write.item.metadata,
16203            repositories: &write.item.repositories,
16204            classification: write.item.classification,
16205            parent: None,
16206            delivers: &[],
16207            delivered_by: &[],
16208            priority: None,
16209            assignees: None,
16210        }))
16211    }
16212
16213    fn document_body_size(
16214        &self,
16215        write: &ItemWrite<Document>,
16216        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
16217    ) -> Option<onetaskgraph_plugin_api::BodySize> {
16218        Some(self.body_size(&Incoming {
16219            written: Written::Document,
16220            title: &write.item.title,
16221            content: write.item.content.as_deref(),
16222            assets,
16223            labels: &write.item.labels,
16224            metadata: &write.item.metadata,
16225            repositories: &write.item.repositories,
16226            classification: write.item.classification,
16227            parent: write.item.project.as_ref(),
16228            delivers: &[],
16229            delivered_by: &[],
16230            priority: None,
16231            assignees: None,
16232        }))
16233    }
16234
16235    /// Create or update one document, which is one issue titled the way this board spells
16236    /// a document.
16237    ///
16238    /// Everything else is exactly a task write: caller metadata goes to the same canonical
16239    /// JSON slot at the end of the body and comes back with its JSON types intact, a key
16240    /// or a field this board cannot carry is refused by name rather than dropped, a target
16241    /// naming an issue this board does not hold is refused rather than created, and an
16242    /// issue this call created is taken back when the rest of the write fails.
16243    async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
16244        self.write_document_assets(write, None)
16245            .await
16246            .map(|written| written.id)
16247    }
16248
16249    async fn write_document_with_assets(
16250        &self,
16251        write: &ItemWrite<Document>,
16252        _answers: Option<&BTreeMap<String, Value>>,
16253        assets: &onetaskgraph_plugin_api::AssetWrite,
16254    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
16255        self.write_document_assets(write, Some(assets)).await
16256    }
16257
16258    /// Refused exactly as the write refuses it, from what the write reads: the mapping first,
16259    /// which reads nothing; then the board's `Status` option. Over an existing item that is
16260    /// read off the item, as the write reads it, and the item is held among this command's
16261    /// resolved records so the write that follows reuses that read rather than repeating it;
16262    /// an item that does not carry the field takes the board's fields, which are held once
16263    /// read. A create is checked against the board's fields only when this command already
16264    /// holds them, because a create reads them together with its repository, in one request,
16265    /// and refuses a missing option before it writes anything.
16266    async fn check_status_write(
16267        &self,
16268        kind: ItemKind,
16269        category: StatusCategory,
16270        target: Option<&NativeId>,
16271    ) -> Result<(), SourceError> {
16272        let status = self.resolved_target(kind, category)?;
16273        if status.option().is_none() {
16274            return Ok(());
16275        }
16276        let fields = match target {
16277            Some(target) => {
16278                // A target this board does not hold is the write's own refusal to make.
16279                let Some(item) = self.bound_item(target).await? else {
16280                    return Ok(());
16281                };
16282                self.resolved_cache()?.insert(target.clone(), item.clone());
16283                // Only the `Status` field decides whether the write can land.
16284                self.fields_for(Some(&item), false, true, false)
16285                    .await?
16286                    .fields
16287            }
16288            None => {
16289                let held = self
16290                    .board_cache()?
16291                    .as_ref()
16292                    .map(|board| board.fields.clone());
16293                match held.or_else(|| {
16294                    self.fields_cache()
16295                        .ok()
16296                        .and_then(|cache| cache.as_ref().map(|board| board.fields.clone()))
16297                }) {
16298                    Some(fields) => fields,
16299                    None => return Ok(()),
16300                }
16301            }
16302        };
16303        self.column_for(&fields, kind, category, &status)
16304            .map(|_| ())
16305    }
16306
16307    /// Whether this instance's resolved mapping — its `status_mapping` over the shipped
16308    /// defaults — gives `category` an option for `kind`. The board's `Status` field is not
16309    /// read: an option the field lacks is the write's own refusal.
16310    fn maps_status(&self, kind: ItemKind, category: StatusCategory) -> bool {
16311        !matches!(
16312            self.statuses.target(kind, category),
16313            StatusTarget::Disabled(_)
16314        )
16315    }
16316
16317    /// What a write of `status` reads back as: the `Status` option its category maps to for
16318    /// `kind`, and for a closing category the closure that option and its fixed reason read
16319    /// as — exactly what [`BoardStatuses::status`] reports of the item once written. A category
16320    /// this instance has no option for is answered as given, since writing it is refused.
16321    fn status_as_written(&self, kind: ItemKind, status: &Status) -> Status {
16322        match self.statuses.target(kind, status.category) {
16323            StatusTarget::Column(name) => {
16324                self.statuses.status(kind, Some(name.as_str()), false, None)
16325            }
16326            StatusTarget::Terminal(name, reason) => {
16327                self.statuses
16328                    .status(kind, Some(name.as_str()), true, Some(reason.reason()))
16329            }
16330            StatusTarget::Disabled(_) => status.clone(),
16331        }
16332    }
16333
16334    /// Set one task's status alone.
16335    ///
16336    /// An open target reopens a closed issue with an `updateIssue` carrying only its
16337    /// `stateInput`, then selects the board option with `updateProjectV2ItemFieldValue`; a
16338    /// terminal target selects its mapped option, then closes with its fixed reason. No
16339    /// request carries a title, a body or a label. The status
16340    /// answered is what [`BoardStatuses::status`] reads off the state just written, which is
16341    /// what a re-read reports.
16342    async fn set_task_status(
16343        &self,
16344        id: &NativeId,
16345        category: StatusCategory,
16346    ) -> Result<Option<Status>, SourceError> {
16347        self.set_status(id, ItemKind::Task, category).await
16348    }
16349
16350    /// Set one task's status and answer the task with it, reading the item once: the read the
16351    /// task is answered from is handed to the status write, which would otherwise read the
16352    /// same issue again — two requests on a fresh process, the read and the field write,
16353    /// where the default's `get_task` before `set_task_status` sent three.
16354    async fn set_task_status_reading(
16355        &self,
16356        id: &NativeId,
16357        category: StatusCategory,
16358    ) -> Result<Option<Task>, SourceError> {
16359        // Refused before anything is read, in the words the write itself refuses it.
16360        self.resolved_target(ItemKind::Task, category)?;
16361        let Some(item) = self
16362            .bound_item(id)
16363            .await?
16364            .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
16365        else {
16366            return Ok(None);
16367        };
16368        let mut task = item.task()?;
16369        self.held_cache
16370            .lock()
16371            .map_err(|_| SourceError::Unavailable {
16372                message: "items read by issue reference were left inconsistent; run the \
16373                          command again"
16374                    .into(),
16375            })?
16376            .insert(id.clone(), item);
16377        let Some(status) = self.set_status(id, ItemKind::Task, category).await? else {
16378            return Ok(None);
16379        };
16380        task.status = status;
16381        Ok(Some(task))
16382    }
16383
16384    /// Set one project's status alone, by exactly the paired write a task's status takes, for
16385    /// the project kind: a terminal category selects the project kind's mapped option and then
16386    /// closes the issue with the category's fixed reason — an issue already closed with a
16387    /// reason that reads that category is left as it is — and an open category reopens a closed
16388    /// issue and then selects its option. A board draft is refused a terminal category as a
16389    /// task's is.
16390    async fn set_project_status(
16391        &self,
16392        id: &NativeId,
16393        category: StatusCategory,
16394    ) -> Result<Option<Status>, SourceError> {
16395        self.projectless()?;
16396        self.set_status(id, ItemKind::Project, category).await
16397    }
16398
16399    /// Every task and project whose card contradicts its issue's closure, read through the
16400    /// board's own `is:closed` filter; see [`TaskSource::status_contradictions`].
16401    async fn status_contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
16402        self.contradictions().await
16403    }
16404
16405    /// What this board holds for each issue reference, one request per fifty of them; see
16406    /// [`TaskSource::issue_holdings`].
16407    async fn issue_holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
16408        self.holdings(issues).await
16409    }
16410
16411    /// Set one task's priority alone: one `updateProjectV2ItemFieldValue` selecting the
16412    /// mapped option of the board's `Priority` field, or one `clearProjectV2ItemFieldValue`
16413    /// for `none`. Refused by an instance with no `priority_mapping`.
16414    async fn set_task_priority(
16415        &self,
16416        id: &NativeId,
16417        priority: Priority,
16418    ) -> Result<Option<Priority>, SourceError> {
16419        self.set_priority(id, priority).await
16420    }
16421
16422    /// Replace one task's content with a single body update that keeps the metadata slot
16423    /// byte for byte.
16424    async fn set_task_content(
16425        &self,
16426        id: &NativeId,
16427        content: &str,
16428    ) -> Result<Option<()>, SourceError> {
16429        self.replace_content(id, content).await
16430    }
16431
16432    /// Replace one task issue's content and its provenance slot entry with a single body
16433    /// update. The answers are not kept: see `replace_rendering`.
16434    async fn set_task_rendering(
16435        &self,
16436        id: &NativeId,
16437        content: &str,
16438        provenance: &Value,
16439        _answers: &BTreeMap<String, Value>,
16440    ) -> Result<Option<()>, SourceError> {
16441        self.replace_rendering(
16442            id,
16443            BoardKind::Work(ItemKind::Task),
16444            content,
16445            provenance,
16446            None,
16447        )
16448        .await
16449        .map(|written| written.map(|_| ()))
16450    }
16451
16452    /// Replace one design-document issue's content and its provenance slot entry, on exactly
16453    /// the terms of [`set_task_rendering`](TaskSource::set_task_rendering).
16454    async fn set_document_rendering(
16455        &self,
16456        id: &NativeId,
16457        content: &str,
16458        provenance: &Value,
16459        _answers: &BTreeMap<String, Value>,
16460    ) -> Result<Option<()>, SourceError> {
16461        self.replace_rendering(id, BoardKind::Document, content, provenance, None)
16462            .await
16463            .map(|written| written.map(|_| ()))
16464    }
16465
16466    /// Replace one project issue's content and its provenance slot entry, on exactly the
16467    /// terms of [`set_task_rendering`](TaskSource::set_task_rendering).
16468    async fn set_project_rendering(
16469        &self,
16470        id: &NativeId,
16471        content: &str,
16472        provenance: &Value,
16473        _answers: &BTreeMap<String, Value>,
16474    ) -> Result<Option<()>, SourceError> {
16475        self.projectless()?;
16476        self.replace_rendering(
16477            id,
16478            BoardKind::Work(ItemKind::Project),
16479            content,
16480            provenance,
16481            None,
16482        )
16483        .await
16484        .map(|written| written.map(|_| ()))
16485    }
16486
16487    /// Apply a targeted update with one read of the item and a write only for what differs:
16488    /// the `Status` and `Priority` field writes in one request, the `blockedBy` difference,
16489    /// and last one `updateIssue` for title, body and state. See `targeted_update`.
16490    async fn update_task(
16491        &self,
16492        id: &NativeId,
16493        update: &TaskUpdate,
16494    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
16495        self.targeted_update(id, update).await
16496    }
16497
16498    /// Each issue's sub-issue parent and children and its links, read in batches.
16499    async fn read_relations(
16500        &self,
16501        ids: &[NativeId],
16502    ) -> Vec<Result<Option<onetaskgraph_plugin_api::Relations>, SourceError>> {
16503        self.relations_of(ids).await
16504    }
16505
16506    async fn set_parents(
16507        &self,
16508        writes: &[onetaskgraph_plugin_api::ParentWrite],
16509    ) -> Vec<Result<onetaskgraph_plugin_api::ParentAnswer, SourceError>> {
16510        self.parents_set(writes).await
16511    }
16512
16513    fn link_types(&self) -> onetaskgraph_plugin_api::LinkTypes {
16514        self.link_types.clone()
16515    }
16516
16517    async fn add_native_links(
16518        &self,
16519        links: &[onetaskgraph_plugin_api::NativeLink],
16520    ) -> Vec<Result<(), SourceError>> {
16521        self.native_links(links, relations::NativeWrite::Add).await
16522    }
16523
16524    async fn remove_native_links(
16525        &self,
16526        links: &[onetaskgraph_plugin_api::NativeLink],
16527    ) -> Vec<Result<(), SourceError>> {
16528        self.native_links(links, relations::NativeWrite::Remove)
16529            .await
16530    }
16531
16532    /// Every task read together — [`DETAIL_BATCH`] to a [`graphql::ISSUE_DETAILS`] request —
16533    /// and each update's hold and guard decided on that read; then each update the read lets
16534    /// through composed exactly as [`Self::update_task`] composes one, its board field writes
16535    /// and its issue update held back and sent in [`graphql::WRITE_TASKS`] requests: every
16536    /// field write first, then the issue update of every task whose field writes all landed.
16537    ///
16538    /// **Where GitHub would refuse the batch as a whole, each item is read on its own:** a
16539    /// batched node read naming an id that resolves to nothing is refused whole, so each id of
16540    /// that batch is read by itself, the missing one answered missing and the rest as
16541    /// themselves. A batch of one, an update of a board draft, one naming dependencies and one
16542    /// of an item whose body this process has not read are each made on their own, as
16543    /// [`Self::update_task`] makes them, because each sends writes of its own in an order the
16544    /// batch does not hold. A field write GitHub refuses fails that task's update alone and
16545    /// sends nothing of its body.
16546    async fn update_tasks(
16547        &self,
16548        updates: &[onetaskgraph_plugin_api::BatchUpdate],
16549    ) -> Vec<Result<onetaskgraph_plugin_api::BatchAnswer<TaskUpdateOutcome>, SourceError>> {
16550        self.updates_batched(updates).await
16551    }
16552
16553    /// Replace one task's `delivered_by` with a single body update that changes the
16554    /// metadata slot and nothing outside it.
16555    async fn set_delivered_by(
16556        &self,
16557        id: &NativeId,
16558        delivered_by: &[TaskRef],
16559    ) -> Result<Option<()>, SourceError> {
16560        self.replace_delivered_by(id, delivered_by).await
16561    }
16562
16563    /// Set one key of one task issue's metadata with a single body update that changes the
16564    /// metadata slot and nothing outside it — no title, label, state or board field request —
16565    /// and sends nothing when the task already holds that value under the key.
16566    async fn set_task_metadata(
16567        &self,
16568        id: &NativeId,
16569        key: &MetadataKey,
16570        value: &Value,
16571    ) -> Result<Option<Task>, SourceError> {
16572        Ok(self
16573            .set_slot_key(id, BoardKind::Work(ItemKind::Task), key, value)
16574            .await?
16575            .map(|item| item.task())
16576            .transpose()?)
16577    }
16578
16579    /// Set one key of one project issue's metadata, on exactly the terms of
16580    /// [`set_task_metadata`](TaskSource::set_task_metadata).
16581    async fn set_project_metadata(
16582        &self,
16583        id: &NativeId,
16584        key: &MetadataKey,
16585        value: &Value,
16586    ) -> Result<Option<Project>, SourceError> {
16587        self.projectless()?;
16588        Ok(self
16589            .set_slot_key(id, BoardKind::Work(ItemKind::Project), key, value)
16590            .await?
16591            .map(|item| item.project()))
16592    }
16593
16594    /// Set one key of one design-document issue's metadata, on exactly the terms of
16595    /// [`set_task_metadata`](TaskSource::set_task_metadata).
16596    async fn set_document_metadata(
16597        &self,
16598        id: &NativeId,
16599        key: &MetadataKey,
16600        value: &Value,
16601    ) -> Result<Option<Document>, SourceError> {
16602        Ok(self
16603            .set_slot_key(id, BoardKind::Document, key, value)
16604            .await?
16605            .map(|item| item.document()))
16606    }
16607
16608    /// Take one key out of one issue's metadata slot with a single body update that changes the
16609    /// slot and nothing outside it, sending nothing when the slot does not hold the key.
16610    async fn remove_record_metadata(
16611        &self,
16612        record: onetaskgraph_plugin_api::MetadataRecord,
16613        id: &NativeId,
16614        key: &MetadataKey,
16615    ) -> Result<Option<Option<String>>, SourceError> {
16616        let kind = match record {
16617            onetaskgraph_plugin_api::MetadataRecord::Task => BoardKind::Work(ItemKind::Task),
16618            onetaskgraph_plugin_api::MetadataRecord::Project => BoardKind::Work(ItemKind::Project),
16619            onetaskgraph_plugin_api::MetadataRecord::Document => BoardKind::Document,
16620        };
16621        let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
16622            return Ok(None);
16623        };
16624        if item.slot.contains_key(key.as_str()) {
16625            let mut slot = item.slot.clone();
16626            slot.remove(key.as_str());
16627            self.write_slot(&mut item, &slot).await?;
16628            self.remember_written(item.clone(), false)?;
16629        }
16630        Ok(Some(match record {
16631            onetaskgraph_plugin_api::MetadataRecord::Task => item.task()?.version,
16632            onetaskgraph_plugin_api::MetadataRecord::Project => item.project().version,
16633            onetaskgraph_plugin_api::MetadataRecord::Document => item.document().version,
16634        }))
16635    }
16636
16637    async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
16638        self.delete_item(id).await
16639    }
16640
16641    async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
16642        self.projectless()?;
16643        self.delete_item(id).await
16644    }
16645
16646    async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
16647        self.delete_item(id).await
16648    }
16649
16650    /// One page of the task issue's own comments, walked by GitHub's own cursor.
16651    ///
16652    /// Nothing here filters, so nothing has to be read ahead of the page: the caller's limit is
16653    /// the page GitHub is asked for and GitHub's `endCursor` is the cursor handed back.
16654    ///
16655    /// One request, [`graphql::ISSUE_DETAIL`]: the read that says the id names a task of this
16656    /// board is the read of its comments. A draft this process already resolved is refused
16657    /// without one.
16658    async fn task_comments(
16659        &self,
16660        task: &NativeId,
16661        page: &PageRequest,
16662    ) -> Result<Option<Page<Comment>>, SourceError> {
16663        validate_page(page)?;
16664        let cached = self.resolved_cache()?.get(task).cloned();
16665        if let Some(item) = cached {
16666            if item.kind != BoardKind::Work(ItemKind::Task) {
16667                return Ok(None);
16668            }
16669            if item.content_kind == ContentKind::DraftIssue {
16670                return Err(self.draft_has_no_comments(task));
16671            }
16672        }
16673        // The first page a comment-activity read just read of this task, at the size asked, is
16674        // that read's answer: taken, so it answers once.
16675        if page.cursor.is_none()
16676            && page.limit >= MAX_PAGE_SIZE
16677            && let Some(held) = self.held_comments()?.remove(task)
16678        {
16679            return Ok(Some(held));
16680        }
16681        match self.issue_detail(task, page).await? {
16682            Some(TaskDetailRead {
16683                comments: Some(comments),
16684                ..
16685            }) => comments,
16686            _ => Ok(None),
16687        }
16688    }
16689
16690    /// Every id's task, with the first page of its comments when `comments` names it:
16691    /// [`DETAIL_BATCH`] items per [`graphql::ISSUE_DETAILS`] request, and one item with its
16692    /// comments in one [`graphql::ISSUE_DETAIL`] request.
16693    async fn get_task_details(
16694        &self,
16695        ids: &[NativeId],
16696        comments: Option<&PageRequest>,
16697    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
16698        if let Some(page) = comments
16699            && let Err(error) = validate_page(page)
16700        {
16701            return ids.iter().map(|_| Err(error.clone())).collect();
16702        }
16703        match (ids, comments) {
16704            ([id], Some(page)) => vec![self.issue_detail(id, page).await],
16705            ([id], None) => vec![self.task_read(id).await],
16706            _ => self.issue_details(ids, comments).await,
16707        }
16708    }
16709
16710    /// Every id's task with the first page of its comments and its `blockedBy`, as a copy reads
16711    /// the tasks it carries: [`COPY_DETAIL_BATCH`] items per [`graphql::ISSUE_COPY_DETAILS`]
16712    /// request, so the dependency read a copy makes of each next is answered from this one.
16713    async fn get_task_details_for_copy(
16714        &self,
16715        ids: &[NativeId],
16716        comments: &PageRequest,
16717    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
16718        // A page past the first is a page of one task's comments, which the detail read of it
16719        // alone answers.
16720        if comments.cursor.is_some() {
16721            return self.get_task_details(ids, Some(comments)).await;
16722        }
16723        if let Err(error) = validate_page(comments) {
16724            return ids.iter().map(|_| Err(error.clone())).collect();
16725        }
16726        let mut read = Vec::with_capacity(ids.len());
16727        for batch in ids.chunks(COPY_DETAIL_BATCH) {
16728            match self
16729                .graphql(
16730                    graphql::ISSUE_COPY_DETAILS,
16731                    copy_detail_batch(batch, comments, false),
16732                )
16733                .await
16734            {
16735                Ok(data) => {
16736                    for (slot, id) in batch.iter().enumerate() {
16737                        let read_one = match data.get(format!("i{slot}")) {
16738                            Some(node) => self.detail_of(id, node, true, None).await,
16739                            None => Err(SourceError::Malformed {
16740                                message: format!(
16741                                    "GitHub answered a batch read with no item for {}",
16742                                    id.0
16743                                ),
16744                            }),
16745                        };
16746                        read.push(read_one);
16747                    }
16748                }
16749                Err(error) if unresolvable_node(&error) => {
16750                    for id in batch {
16751                        read.push(self.issue_detail(id, comments).await);
16752                    }
16753                }
16754                Err(error) => read.extend(batch.iter().map(|_| Err(error.clone()))),
16755            }
16756        }
16757        read
16758    }
16759
16760    /// Every id's item, whatever kind it is, read [`COPY_DETAIL_BATCH`] at a time with
16761    /// [`graphql::ISSUE_COPY_DETAILS`] — the document a copy reads the tasks it carries with —
16762    /// and held for the next read of each by id; see `read_ahead`.
16763    ///
16764    /// What this run wrote is never read: its own record answers, as it does for a read by id.
16765    /// Nor is an item a listing of its project carried whole earlier in this command — see
16766    /// `carried` — which is held in place of reading it.
16767    /// A batch GitHub refuses because one of its ids resolves to no node at all holds nothing,
16768    /// so each of its ids is read on its own and answered as that read answers; a draft, and an
16769    /// answer naming another issue than the one asked for, are left to their own reads too.
16770    async fn read_ahead_for_copy(&self, ids: &[NativeId]) -> Result<(), SourceError> {
16771        // The origins asked just before go out now, beside the members of the one project this
16772        // names when it names one; a project those origins answered whole is held for its next
16773        // read by id rather than read again here.
16774        let hinted = match ids {
16775            [one] => Some(one),
16776            _ => None,
16777        };
16778        self.send_pending_origins(hinted).await?;
16779        if let Some(project) = hinted {
16780            let answered = self.resolved_cache()?.get(project).cloned();
16781            if let Some(answered) = answered
16782                && answered.kind == BoardKind::Work(ItemKind::Project)
16783            {
16784                self.read_ahead()?.insert(project.clone(), Some(answered));
16785                return Ok(());
16786            }
16787        }
16788        let mut unread: Vec<NativeId> = Vec::new();
16789        // Read whole by a listing of its project in this command, which a mutation naming it
16790        // would have dropped: held as a batch would have held it, once every batch is answered.
16791        let mut listed: Vec<NativeId> = Vec::new();
16792        {
16793            let created = self.created()?;
16794            let held = self.read_ahead()?;
16795            let carried = self.carried()?;
16796            for id in ids {
16797                if unread.contains(id)
16798                    || listed.contains(id)
16799                    || held.contains_key(id)
16800                    || created.iter().any(|own| own.id == *id)
16801                {
16802                    continue;
16803                }
16804                // An issue a listing carried without the whole of what blocks it is read in a
16805                // batch too, which carries that, rather than having its dependency read sent
16806                // on its own once the copy reconciles its edges.
16807                let whole = carried.get(id).is_some_and(|item| {
16808                    item.content_kind != ContentKind::Issue || item.blocked_by.is_some()
16809                });
16810                if whole {
16811                    listed.push(id.clone());
16812                } else {
16813                    unread.push(id.clone());
16814                }
16815            }
16816        }
16817        // Nothing of an item's comments is wanted here: the smallest page keeps the read to
16818        // what the item itself costs.
16819        let comments = PageRequest {
16820            cursor: None,
16821            limit: 1,
16822        };
16823        // Held only once every batch has been answered, so a read-ahead that fails part way
16824        // holds nothing — what a listing carried included, which stays carried — and every
16825        // item is read on its own, as the method promises.
16826        let mut read: Vec<(NativeId, Option<Resolved>)> = Vec::new();
16827        // The issues the first id names as sub-issues, as `ISSUE_COPY_DETAILS`'s `children`
16828        // answered them: what a project copy's orphan check asks, when that first id is its
16829        // project.
16830        let mut children: Option<(NativeId, Vec<(String, String)>)> = None;
16831        for (index, batch) in unread.chunks(COPY_DETAIL_BATCH).enumerate() {
16832            let data = match self
16833                .graphql(
16834                    graphql::ISSUE_COPY_DETAILS,
16835                    copy_detail_batch(batch, &comments, index == 0),
16836                )
16837                .await
16838            {
16839                Ok(data) => data,
16840                Err(error) if unresolvable_node(&error) => continue,
16841                Err(error) => return Err(error),
16842            };
16843            for (slot, id) in batch.iter().enumerate() {
16844                let Some(node) = data.get(format!("i{slot}")) else {
16845                    continue;
16846                };
16847                let held = if node.is_null() {
16848                    None
16849                } else {
16850                    match optional_str(node, "__typename")? {
16851                        Some("DraftIssue") => continue,
16852                        Some("Issue") if required_str(node, "id")? != id.0 => continue,
16853                        _ => {}
16854                    }
16855                    // Remembered below with the rest, so a later batch refused leaves no
16856                    // dependency read answered from this one either.
16857                    self.resolve_issue_as(node, false).await?
16858                };
16859                read.push((id.clone(), held));
16860            }
16861            if index == 0
16862                && let Some(node) = data.get("children").filter(|node| !node.is_null())
16863                && node.get("id").and_then(Value::as_str) == batch.first().map(|id| id.0.as_str())
16864                && node.pointer("/subIssues/pageInfo/hasNextPage") == Some(&Value::Bool(false))
16865            {
16866                // A list GitHub did not answer is not an empty one: it would answer the project's
16867                // task listing with nothing, and the orphan check with no orphans.
16868                let listed = node
16869                    .pointer("/subIssues/nodes")
16870                    .and_then(Value::as_array)
16871                    .ok_or_else(|| SourceError::Malformed {
16872                        message: format!(
16873                            "GitHub answered the sub-issues of project {} with no list of them",
16874                            batch[0].0
16875                        ),
16876                    })?
16877                    .iter()
16878                    .map(|child| {
16879                        Ok((
16880                            required_str(child, "id")?.to_owned(),
16881                            required_str(child, "title")?.to_owned(),
16882                        ))
16883                    })
16884                    .collect::<Result<Vec<_>, SourceError>>()?;
16885                children = Some((batch[0].clone(), listed));
16886            }
16887        }
16888        // The project's tasks are known from this read alone when every child it named is held
16889        // from it, but for a document, which its title says is one and which a task listing
16890        // never answers: then a listing of the project's tasks is answered from them.
16891        if let Some((project, listed)) = children
16892            && read.iter().any(|(id, held)| {
16893                *id == project
16894                    && held
16895                        .as_ref()
16896                        .is_some_and(|held| held.kind == BoardKind::Work(ItemKind::Project))
16897            })
16898        {
16899            let mut tasks = Vec::new();
16900            let mut whole = true;
16901            for (child, title) in &listed {
16902                match read.iter().find(|(id, _)| id.0 == *child) {
16903                    Some((_, Some(held))) if held.parent.as_ref() == Some(&project) => {
16904                        if held.kind == BoardKind::Work(ItemKind::Task) {
16905                            tasks.push(held.clone());
16906                        }
16907                    }
16908                    _ if title.starts_with(DESIGN_TITLE_PREFIX) => {}
16909                    _ => whole = false,
16910                }
16911            }
16912            if whole {
16913                self.task_children()?.insert(project, tasks);
16914            }
16915        }
16916        let mut resolved = self.resolved_cache()?;
16917        let mut ahead = self.read_ahead()?;
16918        let mut carried = self.carried()?;
16919        for item in read.iter().filter_map(|(_, held)| held.as_ref()) {
16920            resolved.insert(item.id.clone(), item.clone());
16921        }
16922        // Taken only if still carried: a mutation naming it while the batches ran dropped it,
16923        // and its next read is then its own.
16924        for id in &listed {
16925            let Some(item) = carried.remove(id) else {
16926                continue;
16927            };
16928            // The whole of what it is blocked by came with it, so the dependency read a copy
16929            // makes next is answered from this one, as a copy's detail read is.
16930            if item.blocked_by.is_some() {
16931                resolved.insert(item.id.clone(), item.clone());
16932            }
16933            read.push((id.clone(), Some(item)));
16934        }
16935        for (id, held) in read {
16936            ahead.insert(id, held);
16937        }
16938        Ok(())
16939    }
16940
16941    /// Add one comment to the task's issue, as the account the token belongs to.
16942    ///
16943    /// The author is refused before anything is sent — not even the task is read — because
16944    /// no answer GitHub could give would make posting under another name than the one asked
16945    /// for the right outcome.
16946    async fn add_comment(
16947        &self,
16948        task: &NativeId,
16949        comment: &NewComment,
16950    ) -> Result<Option<Comment>, SourceError> {
16951        if let Some(author) = &comment.author {
16952            return Err(SourceError::Refused {
16953                message: format!(
16954                    "source {} cannot post a comment as {author:?}: GitHub records the account \
16955                     the token signs in as the author of every comment; next: leave --author \
16956                     out, and the comment is posted as that account",
16957                    self.name
16958                ),
16959            });
16960        }
16961        let Some(issue) = self.commented_issue(task).await? else {
16962            return Ok(None);
16963        };
16964        let data = self
16965            .graphql(
16966                graphql::ADD_COMMENT,
16967                json!({"input":{"subjectId":issue.0,"body":comment.body.as_str()}}),
16968            )
16969            .await?;
16970        let subject = data
16971            .pointer("/addComment/subject")
16972            .filter(|value| !value.is_null())
16973            .ok_or_else(|| SourceError::Malformed {
16974                message: "GitHub comment addition returned no subject".into(),
16975            })?;
16976        if required_str(subject, "id")? != issue.0 {
16977            return Err(SourceError::Malformed {
16978                message: "GitHub comment addition answered about another issue".into(),
16979            });
16980        }
16981        let added = data
16982            .pointer("/addComment/commentEdge/node")
16983            .filter(|value| !value.is_null())
16984            .ok_or_else(|| SourceError::Malformed {
16985                message: "GitHub comment addition returned no comment".into(),
16986            })?;
16987        let added = comment_from(added)?;
16988        self.remember_commented(&issue)?;
16989        Ok(Some(added))
16990    }
16991
16992    /// Every task commented on read together — [`DETAIL_BATCH`] to a
16993    /// [`graphql::ISSUE_DETAILS`] request — and each comment's hold decided on that read; then
16994    /// every comment it lets through added by aliased `addComment`s of one
16995    /// [`graphql::ADD_COMMENTS`] request per [`COMMENT_BATCH`]. GitHub answers a refusal of one
16996    /// alias at that alias's path, so it fails that comment alone.
16997    ///
16998    /// **Where GitHub would refuse the batch as a whole, each item is read on its own:** a
16999    /// batched node read naming an id that resolves to nothing is refused whole, so each id of
17000    /// that batch is read by itself, the missing one answered missing. A batch of one is the
17001    /// comment alone, as [`Self::add_comment`] adds it.
17002    async fn add_comments(
17003        &self,
17004        comments: &[onetaskgraph_plugin_api::BatchComment],
17005    ) -> Vec<Result<onetaskgraph_plugin_api::BatchAnswer<Comment>, SourceError>> {
17006        self.comments_batched(comments).await
17007    }
17008
17009    async fn edit_comment(
17010        &self,
17011        task: &NativeId,
17012        comment: &NativeId,
17013        body: &CommentBody,
17014    ) -> Result<Option<Comment>, SourceError> {
17015        let Some(issue) = self.commented_issue(task).await? else {
17016            return Ok(None);
17017        };
17018        let Some(held) = self.comment_on(&issue, comment).await? else {
17019            return Ok(None);
17020        };
17021        // A comment a copy wrote keeps its origin through an edit: its marker is carried over.
17022        let body = CommentOrigin::kept(&held, body)?;
17023        let data = self
17024            .graphql(
17025                graphql::UPDATE_COMMENT,
17026                json!({"input":{"id":comment.0,"body":body.as_str()}}),
17027            )
17028            .await?;
17029        let edited = data
17030            .pointer("/updateIssueComment/issueComment")
17031            .filter(|value| !value.is_null())
17032            .ok_or_else(|| SourceError::Malformed {
17033                message: "GitHub comment update returned no comment".into(),
17034            })?;
17035        let edited = comment_from(edited)?;
17036        if edited.id != *comment {
17037            return Err(SourceError::Malformed {
17038                message: "GitHub comment update returned the wrong comment".into(),
17039            });
17040        }
17041        self.remember_commented(&issue)?;
17042        Ok(Some(edited))
17043    }
17044
17045    async fn delete_comment(
17046        &self,
17047        task: &NativeId,
17048        comment: &NativeId,
17049    ) -> Result<Option<NativeId>, SourceError> {
17050        let Some(issue) = self.commented_issue(task).await? else {
17051            return Ok(None);
17052        };
17053        if !self.comment_is_on(&issue, comment).await? {
17054            return Ok(None);
17055        }
17056        self.held_comments()?.remove(&issue);
17057        let data = self
17058            .graphql(graphql::DELETE_COMMENT, json!({"input":{"id":comment.0}}))
17059            .await?;
17060        // The payload says nothing about the comment it removed, so what is checked is that
17061        // GitHub answered the mutation at all rather than leaving it unanswered.
17062        data.get("deleteIssueComment")
17063            .filter(|value| !value.is_null())
17064            .ok_or_else(|| SourceError::Malformed {
17065                message: "GitHub comment deletion returned no payload".into(),
17066            })?;
17067        Ok(Some(comment.clone()))
17068    }
17069
17070    /// Every request this source has recorded, and what each of GitHub's two budgets was
17071    /// attributed — read off the same accounting the session report is rendered from, so
17072    /// the two cannot count one request two ways.
17073    async fn metering(&self) -> Result<Option<Metering>, SourceError> {
17074        Ok(Some(self.ledger.snapshot().metering()))
17075    }
17076
17077    /// One `GET /rate_limit` at this source's endpoint, every resource it reports, asked
17078    /// afresh each time and counted in nothing [`metering`](TaskSource::metering) reports:
17079    /// GitHub documents the endpoint as free. See [`quota`].
17080    async fn quota(&self) -> Result<Vec<onetaskgraph_plugin_api::QuotaReading>, SourceError> {
17081        self.rate_limits().await
17082    }
17083
17084    /// Drop every item, search answer and board read this source holds, so the next command
17085    /// reads the board as a person has since left it.
17086    ///
17087    /// Every one of those is held on the assumption that nothing but this source writes the
17088    /// board while a command runs, which stops being true the moment the command is over: a
17089    /// body a person edited would be overwritten from the record held here, and a card they
17090    /// moved would be read as still where this source left it. The board's own field
17091    /// definitions go too, because a person can add or delete a `Status` option and a write
17092    /// resolved against the held list would not re-read on a miss. What stays is what stays
17093    /// valid in normal use: each repository's node id, which a miss re-reads, the pacing of
17094    /// mutations, which is about GitHub's limiter rather than anybody's work, and the running
17095    /// accounting [`metering`](TaskSource::metering) answers from.
17096    ///
17097    /// Infallible in practice: a lock an earlier failure poisoned is cleared rather than
17098    /// refused, because clearing it is what puts it right.
17099    async fn end_command(&self) -> Result<(), SourceError> {
17100        fn clear<T: Default>(held: &Mutex<T>) {
17101            *held
17102                .lock()
17103                .unwrap_or_else(std::sync::PoisonError::into_inner) = T::default();
17104            held.clear_poison();
17105        }
17106        clear(&self.created);
17107        clear(&self.updated);
17108        clear(&self.commented);
17109        clear(&self.board_cache);
17110        clear(&self.search_cache);
17111        clear(&self.narrowed_cache);
17112        clear(&self.search_rows);
17113        clear(&self.search_next);
17114        clear(&self.resolved_cache);
17115        clear(&self.read_ahead);
17116        clear(&self.pending_origins);
17117        clear(&self.member_classes);
17118        clear(&self.carried);
17119        clear(&self.held_cache);
17120        clear(&self.children_cache);
17121        clear(&self.task_children);
17122        clear(&self.written);
17123        clear(&self.fields_cache);
17124        clear(&self.held_comments);
17125        clear(&self.task_writes);
17126        clear(&self.written_tokens);
17127        self.forget_at_end_of_call();
17128        self.expected.end_command();
17129        Ok(())
17130    }
17131}
17132
17133/// One member of a project as a classification-only read answers it: its classification and
17134/// the repositories its work changes.
17135type MemberClass = (Classification, Vec<Repository>);
17136
17137/// Each project's sub-issues as one command read them, keyed by the selector they were asked
17138/// for under, beside the project that selector named; see `children_cache`.
17139type ProjectChildren = BTreeMap<NativeId, (NativeId, Vec<Resolved>)>;
17140
17141/// One issue comment as the contract carries it.
17142///
17143/// `author` is absent both when GitHub answers `null` for an account that no longer exists
17144/// and when it answers an actor with no login, because either way the source did not say who
17145/// wrote it — which is what an absent author means, rather than an author called nothing.
17146///
17147/// A comment a copy wrote here carries its origin as the hidden marker at the end of its body
17148/// — GitHub sets every comment's author and times itself, so there is nowhere else to keep it —
17149/// and is read back with the marker taken out and reported as its origin.
17150fn comment_from(value: &Value) -> Result<Comment, SourceError> {
17151    let actor = value.get("author").unwrap_or(&Value::Null);
17152    // A bot's login is spelled as GitHub's own pages spell it, `<login>[bot]`, so a reader —
17153    // and every copy of the comment — can tell it from a person's.
17154    let bot = actor.get("__typename").and_then(Value::as_str) == Some("Bot");
17155    Ok(Comment {
17156        origin: None,
17157        id: NativeId(required_str(value, "id")?.to_owned()),
17158        author: optional_str(actor, "login")?.map(|login| {
17159            if bot && !login.ends_with("[bot]") {
17160                format!("{login}[bot]")
17161            } else {
17162                login.to_owned()
17163            }
17164        }),
17165        created_at: optional_time(value, "createdAt")?,
17166        updated_at: optional_time(value, "updatedAt")?,
17167        body: required_str(value, "body")?.to_owned(),
17168        url: optional_str(value, "url")?.map(str::to_owned),
17169    }
17170    .unmarked())
17171}
17172
17173/// The page of comments one issue node carries, resumed from `after`.
17174fn comment_page(
17175    node: &Value,
17176    issue: &str,
17177    after: Option<&str>,
17178) -> Result<Page<Comment>, SourceError> {
17179    let connection = node
17180        .get("comments")
17181        .filter(|value| !value.is_null())
17182        .ok_or_else(|| SourceError::Malformed {
17183            message: format!("GitHub issue {issue} answered with no comments connection"),
17184        })?;
17185    let items = optional_nodes(Some(connection), "issue comments")?
17186        .into_iter()
17187        .flatten()
17188        .map(comment_from)
17189        .collect::<Result<Vec<_>, _>>()?;
17190    let next = next_cursor(connection)?;
17191    if let Some(next) = &next {
17192        validate_cursor_progress(after, &next.0)?;
17193    }
17194    Ok(Page { items, next })
17195}
17196
17197/// The far ends of an issue's whole `blockedBy` connection, when the read carried it to its
17198/// end — `None` when it carried none, or a page with more past it.
17199fn carried_blocked_by(content: &Value) -> Result<Option<Vec<Value>>, SourceError> {
17200    let Some(connection) = content.get("blockedBy").filter(|value| !value.is_null()) else {
17201        return Ok(None);
17202    };
17203    if next_cursor(connection)?.is_some() {
17204        return Ok(None);
17205    }
17206    Ok(Some(
17207        optional_nodes(Some(connection), "blocked-by issues")?
17208            .into_iter()
17209            .flatten()
17210            .cloned()
17211            .collect(),
17212    ))
17213}
17214
17215/// Where the recorded tail of a dependency walk resumes; see
17216/// [`GitHubProjectsSource::recorded_edges`].
17217const RECORDED_CURSOR: &str = "onetaskgraph.depends_on:";
17218
17219/// The board text field this source keeps a copy's origin in.
17220///
17221/// Named after the key it holds, and held to that name by the guard below rather than by
17222/// a reader noticing.
17223const ORIGIN_FIELD: &str = "onetaskgraph.origin";
17224
17225/// The metadata key that field holds.
17226///
17227/// The engine owns this key and spells it once as `GlobalId::ORIGIN_KEY`; a plugin never
17228/// constructs or interprets the qualified id it carries. This source names it only to
17229/// route it — a short, typed value belongs in a typed field rather than in the body slot
17230/// a caller's own prose shares.
17231///
17232/// Restated rather than imported, because no plugin crate may depend on the engine. What
17233/// keeps the two spellings one contract is `scripts/check-origin-key-spelling.sh`, a
17234/// target in `check`: it reads the engine's own literal and fails naming the file and the
17235/// line when a plugin's parts from it either way. Drift here has one symptom — a copy
17236/// that creates a second item every run instead of finding the one it wrote — and that is
17237/// too late to learn it.
17238const ORIGIN_KEY: &str = "onetaskgraph.origin";
17239
17240/// Where a recorded tail resumes, refusing a cursor no walk in `direction` reported.
17241///
17242/// The reserved key holds forward edges and nothing else — the reverse of a recorded edge
17243/// is derived from the far end, never written down on the near item — so only a forward
17244/// walk ever reports one of these cursors. A reverse read carrying one is resuming a walk
17245/// it did not come from, and it is told so rather than answered with an empty page that
17246/// reads as a walk which ended.
17247fn recorded_offset(
17248    cursor: Option<&str>,
17249    direction: Direction,
17250) -> Result<Option<usize>, SourceError> {
17251    cursor
17252        .and_then(|cursor| cursor.strip_prefix(RECORDED_CURSOR))
17253        .map(|offset| {
17254            if direction != Direction::DependsOn {
17255                return Err(SourceError::Config {
17256                    message: format!(
17257                        "{RECORDED_CURSOR}{offset} resumes recorded forward edges, which a \
17258                         reverse dependency read never issues; resume it in the direction \
17259                         that reported it"
17260                    ),
17261                });
17262            }
17263            offset.parse().map_err(|_| SourceError::Config {
17264                message: format!("{RECORDED_CURSOR}{offset} is not a recorded-edge cursor"),
17265            })
17266        })
17267        .transpose()
17268}
17269
17270/// What a dependency read's own answer says of a board draft: `None` when the item is not a
17271/// draft, or the answer did not carry its board item; `Some(None)` for a draft whose one board
17272/// item is not on this board, which this source does not hold; and `Some(Some(slot))`, the
17273/// draft's metadata, for one it does — its board item naming this board by its number and by
17274/// the id the same answer read of the board, as [`GitHubProjectsSource::draft_by_id`] decides.
17275fn draft_slot(
17276    data: &Value,
17277    id: &NativeId,
17278    project_number: u32,
17279) -> Result<Option<Option<BTreeMap<String, Value>>>, SourceError> {
17280    let Some(draft) = data
17281        .get("node")
17282        .filter(|node| node.get("__typename").and_then(Value::as_str) == Some("DraftIssue"))
17283    else {
17284        return Ok(None);
17285    };
17286    let Some(items) = data.pointer("/draft/projectV2Items") else {
17287        return Ok(None);
17288    };
17289    if required_str(draft, "id")? != id.0 {
17290        return Err(SourceError::Malformed {
17291            message: format!("GitHub answered a different draft for {}", id.0),
17292        });
17293    }
17294    let nodes = items
17295        .get("nodes")
17296        .and_then(Value::as_array)
17297        .ok_or_else(|| SourceError::Malformed {
17298            message: format!("GitHub draft {} projectV2Items.nodes is not an array", id.0),
17299        })?;
17300    let info = items
17301        .get("pageInfo")
17302        .ok_or_else(|| SourceError::Malformed {
17303            message: format!("GitHub draft {} projectV2Items has no pageInfo", id.0),
17304        })?;
17305    if required_bool(info, "hasNextPage")? || nodes.len() > 1 {
17306        return Err(SourceError::Malformed {
17307            message: format!(
17308                "GitHub draft {} reports more board items than the one GitHub links a draft to",
17309                id.0
17310            ),
17311        });
17312    }
17313    let board = data
17314        .pointer("/board/projectV2/id")
17315        .and_then(Value::as_str)
17316        .ok_or_else(|| SourceError::Malformed {
17317            message: format!(
17318                "GitHub answered draft {} without this board's own id beside it",
17319                id.0
17320            ),
17321        })?;
17322    let mut held = false;
17323    for node in nodes {
17324        let project = node.get("project").ok_or_else(|| SourceError::Malformed {
17325            message: format!("GitHub draft {} board item has no project", id.0),
17326        })?;
17327        let number = project
17328            .get("number")
17329            .and_then(Value::as_u64)
17330            .ok_or_else(|| SourceError::Malformed {
17331                message: format!(
17332                    "GitHub draft {} board item has no numeric project number",
17333                    id.0
17334                ),
17335            })?;
17336        let project_id = required_str(project, "id")?;
17337        held |= number == u64::from(project_number) && project_id == board;
17338    }
17339    if !held {
17340        return Ok(Some(None));
17341    }
17342    Ok(Some(Some(
17343        metadata_body(optional_str(draft, "body")?.map(str::to_owned))?.1,
17344    )))
17345}
17346
17347fn recorded_page(edges: Vec<DependencyEdge>, offset: usize, limit: usize) -> Page<DependencyEdge> {
17348    let mut page = offset_page(edges, offset, limit.max(1));
17349    page.next = page
17350        .next
17351        .map(|cursor| Cursor(format!("{RECORDED_CURSOR}{}", cursor.0)));
17352    page
17353}
17354
17355/// The kind of one issue reached through a dependency connection.
17356///
17357/// The same questions the board scan asks, over the fields the dependency document
17358/// selects, and in the same order: the design prefix first, then a sub-issue is a task,
17359/// then anything with sub-issues or the marker is a project.
17360///
17361/// # Errors
17362///
17363/// A far end this board holds as a document is refused rather than reported. The two
17364/// answers that are not refusals would both be wrong: reporting it as a task names an id
17365/// no task read of this source can find, and reporting it as a project names one no
17366/// project read can. There is no third value to return — `ItemKind` has no document
17367/// variant, because nothing may point at a document — so the relationship itself is what
17368/// the person is told about.
17369fn related_kind(value: &Value, meaning: SubIssues) -> Result<ItemKind, SourceError> {
17370    let id = required_str(value, "id")?;
17371    if required_str(value, "title")?.starts_with(DESIGN_TITLE_PREFIX) {
17372        return Err(SourceError::Refused {
17373            message: format!(
17374                "GitHub issue {id} is a document of this board — its title begins \
17375                 {DESIGN_TITLE_PREFIX:?} — and nothing may depend on a document or be depended \
17376                 on by one; next: remove that issue's blocking relationship on this board"
17377            ),
17378        });
17379    }
17380    let parent = optional_str(value.get("parent").unwrap_or(&Value::Null), "id")?;
17381    if parent.is_some() || meaning == SubIssues::Parent {
17382        return Ok(ItemKind::Task);
17383    }
17384    let (_, slot) = metadata_body(optional_str(value, "body")?.map(str::to_owned))?;
17385    let marked = ItemKind::from_metadata(&slot).map_err(|message| SourceError::Malformed {
17386        message: format!("GitHub issue {id}: {message}"),
17387    })?;
17388    let sub_issues = sub_issue_total(value)?;
17389    Ok(if sub_issues > 0 || marked == Some(ItemKind::Project) {
17390        ItemKind::Project
17391    } else {
17392        ItemKind::Task
17393    })
17394}
17395
17396/// The reason GitHub records an issue closed as a duplicate of another under.
17397const DUPLICATE_REASON: &str = "DUPLICATE";
17398
17399/// The `stateInput` that closes an issue for `reason`.
17400fn closed_input(reason: ClosedState) -> Value {
17401    json!({"value":"CLOSED","stateReason":reason.reason()})
17402}
17403
17404/// The `IssueStateUpdateInput` one status target asks for.
17405///
17406/// `stateInput` and `state` are mutually exclusive on `UpdateIssueInput`, and only this
17407/// one is ever sent. A non-terminal status always asks for `OPEN`, which is what reopens
17408/// a currently-closed issue: without that the item would read back `Unknown` and a copy
17409/// would report a change forever. A document has no status at all, and asks for neither.
17410fn state_input(target: Option<&StatusTarget>) -> Value {
17411    match target {
17412        Some(StatusTarget::Terminal(_, reason)) => closed_input(*reason),
17413        Some(StatusTarget::Column(_) | StatusTarget::Disabled(_)) => json!({"value":"OPEN"}),
17414        // A document has no status, so a write of one says nothing about the issue's open
17415        // or closed state rather than forcing it open: `stateInput` is what carries that
17416        // instruction, and an explicit null asks for no change to it.
17417        None => Value::Null,
17418    }
17419}
17420
17421/// The metadata one write stores in the item's body slot.
17422///
17423/// The typed fields travel as themselves, so the three reserved keys are rebuilt here
17424/// rather than carried: the kind marker so an empty project stays readable, the
17425/// repository list only when it is not exactly the issue's own repository, and the far
17426/// ends no relationship here can name.
17427///
17428/// The copy origin is the one typed field that is also mirrored here, and only as a
17429/// mirror: it lands in the board's origin field as well, which stays the one every reader
17430/// takes it from, and it is here so that GitHub's issue search — which indexes this comment
17431/// and catches up with a write in seconds rather than minutes — can find the item by it.
17432/// A reader of the release before this one drops the slot's copy and reads the field, so an
17433/// item written here still reads with exactly one origin there.
17434fn slot_metadata(
17435    incoming: &Incoming<'_>,
17436    own_repository: Option<&Repository>,
17437    fallback: &[DependencyEdge],
17438) -> BTreeMap<String, Value> {
17439    let mut metadata = incoming.metadata.clone();
17440    match metadata.remove(ORIGIN_KEY) {
17441        Some(Value::String(origin)) if !origin.is_empty() => {
17442            metadata.insert(ORIGIN_KEY.to_owned(), Value::String(origin));
17443        }
17444        _ => {}
17445    }
17446    match incoming.written.kind() {
17447        BoardKind::Work(kind) => metadata.insert(
17448            ItemKind::METADATA_KEY.to_owned(),
17449            Value::String(kind.marker().to_owned()),
17450        ),
17451        // A document is told by its title, so it carries no kind marker: that key names
17452        // what a dependency endpoint points at, and nothing may point at a document.
17453        BoardKind::Document => metadata.remove(ItemKind::METADATA_KEY),
17454    };
17455    incoming.classification.record(&mut metadata);
17456    let derivable = own_repository
17457        .map(|own| incoming.repositories == [own.clone()])
17458        .unwrap_or(incoming.repositories.is_empty());
17459    if derivable {
17460        metadata.remove(Repository::METADATA_KEY);
17461    } else {
17462        metadata.insert(
17463            Repository::METADATA_KEY.to_owned(),
17464            Value::Array(
17465                incoming
17466                    .repositories
17467                    .iter()
17468                    .map(|repository| Value::String(repository.as_str().to_owned()))
17469                    .collect(),
17470            ),
17471        );
17472    }
17473    // The typed lists are what land, whatever the caller's own metadata held under their
17474    // keys: a key of either name travelling beside the field would otherwise be a second
17475    // answer to the same question, and the field is the one the contract names.
17476    for (key, entries) in [
17477        (TaskRef::DELIVERS_KEY, incoming.delivers),
17478        (TaskRef::DELIVERED_BY_KEY, incoming.delivered_by),
17479    ] {
17480        set_task_list(&mut metadata, key, entries);
17481    }
17482    record_edges(&mut metadata, fallback);
17483    metadata
17484}
17485
17486/// Hold the far ends no relationship here can name under [`DependencyEdge::RECORDED_KEY`] in
17487/// one slot's metadata, or no such key when there are none.
17488fn record_edges(metadata: &mut BTreeMap<String, Value>, fallback: &[DependencyEdge]) {
17489    if fallback.is_empty() {
17490        metadata.remove(DependencyEdge::RECORDED_KEY);
17491    } else {
17492        metadata.insert(
17493            DependencyEdge::RECORDED_KEY.to_owned(),
17494            Value::Array(
17495                fallback
17496                    .iter()
17497                    .map(|edge| {
17498                        serde_json::to_value(&edge.to).expect("an endpoint renders as JSON")
17499                    })
17500                    .collect(),
17501            ),
17502        );
17503    }
17504}
17505
17506/// Every label one item carries, from its content's own connection and nowhere else.
17507///
17508/// There is no second place to read one from: no document this source sends selects the
17509/// board's built-in `Labels` field, because GitHub derives it from the content and a draft
17510/// cannot carry one at all. The module documentation records the three schema facts that
17511/// settle it.
17512fn labels(content: &Value) -> Result<Vec<Label>, SourceError> {
17513    optional_nodes(content.get("labels"), "content labels")?
17514        .into_iter()
17515        .flatten()
17516        .map(|v| {
17517            Ok(Label {
17518                id: NativeId(required_str(v, "id")?.to_owned()),
17519                name: required_str(v, "name")?.to_owned(),
17520                color: optional_str(v, "color")?.map(str::to_owned),
17521            })
17522        })
17523        .collect()
17524}
17525
17526/// Each board field value one item holds, as the change token's facets name it: the field's
17527/// name, with the single-select option's name or the text. A value of a type no read here
17528/// selects, and one naming no field, says nothing a person can rename and is left out.
17529fn facet_fields(field_values: &[Value]) -> Vec<(String, String)> {
17530    field_values
17531        .iter()
17532        .filter_map(|value| {
17533            let field = value.pointer("/field/name")?.as_str()?;
17534            let held = value.get("name").or_else(|| value.get("text"))?.as_str()?;
17535            Some((field.to_owned(), held.to_owned()))
17536        })
17537        .collect()
17538}
17539
17540/// The digest of the facets of the issue `content`, whose board item's values are
17541/// `field_values` — or `None` when the response did not carry, whole, every member they are read
17542/// from: the title, the parent, the sub-issue summary and the body its kind is read from, every
17543/// label, and every field value.
17544///
17545/// What a write's own response spells its token from, by exactly the rules a read takes them by.
17546fn facets_of(content: &Value, field_values: &Value) -> Option<change_token::FacetsDigest> {
17547    let ended = |connection: &Value| {
17548        connection.pointer("/pageInfo/hasNextPage") == Some(&Value::Bool(false))
17549    };
17550    let labels = content.get("labels").filter(|labels| ended(labels))?;
17551    if !ended(field_values) {
17552        return None;
17553    }
17554    let parent = content.get("parent")?;
17555    let (_, slot) = metadata_body(content.get("body")?.as_str().map(str::to_owned)).ok()?;
17556    let kind = BoardKind::of(
17557        content.get("title")?.as_str()?,
17558        !parent.is_null(),
17559        sub_issue_total(content).ok()?,
17560        ItemKind::from_metadata(&slot).ok()?,
17561    );
17562    let labels = self::labels(&json!({"labels": labels})).ok()?;
17563    let nodes = field_values.get("nodes")?.as_array()?;
17564    Some(change_token::Facets::new(kind.facet(), facet_fields(nodes), &labels).digest())
17565}
17566
17567/// The definition of each board field one item's values are values of, in the shape a read
17568/// of the board's own `fields` gives one.
17569///
17570/// A value names its field through a fragment on that field's own type, so the type is
17571/// known from which kind of value it is: a single-select value's field is a
17572/// `ProjectV2SingleSelectField`, options and all, and a text value's is a `ProjectV2Field`.
17573/// A value whose field carried no id, or an empty one, says nothing usable and is left out.
17574fn field_definitions(field_values: &[Value]) -> Vec<Value> {
17575    field_values
17576        .iter()
17577        .filter_map(|value| {
17578            let field = value.get("field")?.as_object()?;
17579            field.get("id")?.as_str().filter(|id| !id.is_empty())?;
17580            let typename = if value.get("text").is_some() {
17581                "ProjectV2Field"
17582            } else if value.get("name").is_some() {
17583                "ProjectV2SingleSelectField"
17584            } else {
17585                return None;
17586            };
17587            let mut defined = field.clone();
17588            defined.insert("__typename".to_owned(), json!(typename));
17589            // Only a text field holds a text value, so the value says the field's type too.
17590            if typename == "ProjectV2Field" {
17591                defined.insert("dataType".to_owned(), json!("TEXT"));
17592            }
17593            Some(Value::Object(defined))
17594        })
17595        .collect()
17596}
17597
17598fn text_field(field_values: &[Value], name: &str) -> Result<Option<String>, SourceError> {
17599    let Some(node) = field_values
17600        .iter()
17601        .find(|node| node.pointer("/field/name").and_then(Value::as_str) == Some(name))
17602    else {
17603        return Ok(None);
17604    };
17605    Ok(optional_str(node, "text")?.map(str::to_owned))
17606}
17607
17608fn valid_github_owner(owner: &str) -> bool {
17609    !owner.is_empty()
17610        && owner.len() <= 39
17611        && !owner.starts_with('-')
17612        && !owner.ends_with('-')
17613        && !owner.contains("--")
17614        && owner
17615            .bytes()
17616            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
17617}
17618
17619/// GitHub's repository-name grammar: 1-100 ASCII letters, digits, `-`, `_` or `.`, and
17620/// neither of the two names a path segment already means.
17621fn valid_github_repository_name(name: &str) -> bool {
17622    !name.is_empty()
17623        && name.len() <= 100
17624        && name != "."
17625        && name != ".."
17626        && name
17627            .bytes()
17628            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
17629}
17630
17631fn valid_environment_name(name: &str) -> bool {
17632    let mut bytes = name.bytes();
17633    bytes
17634        .next()
17635        .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
17636        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
17637}
17638
17639/// How many sub-issues one issue has.
17640///
17641/// `Issue.subIssuesSummary` is `SubIssuesSummary!` and its `total` is `Int!`, so an
17642/// absent or non-integer one is a response this source cannot read — and reading it as
17643/// zero would classify a project as a task, which is exactly the mistake the marker
17644/// exists to keep from happening quietly.
17645fn sub_issue_total(issue: &Value) -> Result<u64, SourceError> {
17646    let summary = issue
17647        .get("subIssuesSummary")
17648        .ok_or_else(|| SourceError::Malformed {
17649            message: "GitHub issue is missing subIssuesSummary".into(),
17650        })?;
17651    summary
17652        .get("total")
17653        .and_then(Value::as_u64)
17654        .ok_or_else(|| SourceError::Malformed {
17655            message: "GitHub issue subIssuesSummary.total is not an unsigned integer".into(),
17656        })
17657}
17658
17659/// One issue's own `number`.
17660///
17661/// An issue always has one: GitHub declares `Issue.number` as `Int!` and every selection of
17662/// an issue in this module asks for it. So a read of one that comes back without it, or
17663/// with something that is not an unsigned integer, is a response this source cannot read —
17664/// absence here is **not** "this issue has no number". A draft is the content that has
17665/// none, and a draft never reaches this: the caller decides on `__typename` first, the way
17666/// it does for `subIssuesSummary`, which `DraftIssue` equally declares nothing for.
17667fn issue_number(issue: &Value) -> Result<u64, SourceError> {
17668    issue
17669        .get("number")
17670        .and_then(Value::as_u64)
17671        .ok_or_else(|| SourceError::Malformed {
17672            message: "GitHub issue number is missing or is not an unsigned integer".into(),
17673        })
17674}
17675
17676/// The `number` a creating mutation answered with, and `None` when it answered without one;
17677/// why a missing one is tolerated is at the call in `create_and_file_issue`.
17678fn created_issue_number(created: &Value) -> Result<Option<u64>, SourceError> {
17679    match created.get("number") {
17680        None | Some(Value::Null) => Ok(None),
17681        Some(value) => value
17682            .as_u64()
17683            .map(Some)
17684            .ok_or_else(|| SourceError::Malformed {
17685                message: "GitHub created issue number is not an unsigned integer".into(),
17686            }),
17687    }
17688}
17689
17690fn required_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
17691    value
17692        .get(field)
17693        .and_then(Value::as_str)
17694        .ok_or_else(|| SourceError::Malformed {
17695            message: format!("GitHub response is missing string field {field}"),
17696        })
17697}
17698
17699fn required_nonblank_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
17700    let found = required_str(value, field)?;
17701    if found.trim().is_empty() {
17702        return Err(SourceError::Malformed {
17703            message: format!("GitHub response has blank string field {field}"),
17704        });
17705    }
17706    Ok(found)
17707}
17708
17709/// The slot's delimiters, which `docs/metadata.md` settles once for every source that
17710/// needs one — Linear spells them too, in its own description field.
17711///
17712/// Restated rather than shared, because a plugin crate depends on the contract crate and
17713/// nothing else of this workspace. `scripts/check-metadata-slot-encoding.sh`, a target in
17714/// `check`, is what keeps the two one encoding: drift is otherwise quiet, since each
17715/// source round-trips its own writes perfectly well under its own spelling.
17716const METADATA_OPEN: &str = "<!-- onetaskgraph.metadata\n";
17717const METADATA_CLOSE: &str = "\n-->";
17718
17719/// What the composer puts between a non-empty visible body and the slot, and the one thing
17720/// the parser takes off the visible body when it takes the slot off — exactly once, so every
17721/// other trailing byte of the body comes back as it was written.
17722// 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.
17723const METADATA_SEPARATOR: &str = "\n\n";
17724
17725/// The visible body and the metadata slot at the end of it.
17726///
17727/// The encoding is the one `docs/metadata.md` settles for Linear, which is where its
17728/// reasons are. Only a comment at the very end is a slot; one in the middle is a person's
17729/// own content and is left alone. The visible body is everything before the slot less the
17730/// one [`METADATA_SEPARATOR`] the composer put there, byte for byte.
17731fn metadata_body(
17732    body: Option<String>,
17733) -> Result<(Option<String>, BTreeMap<String, Value>), SourceError> {
17734    let Some(body) = body else {
17735        return Ok((None, BTreeMap::new()));
17736    };
17737    let Some(slot) = slot_span(&body)? else {
17738        return Ok((Some(body), BTreeMap::new()));
17739    };
17740    let metadata =
17741        serde_json::from_str(&body[slot.encoded_start..slot.encoded_end]).map_err(|error| {
17742            SourceError::Malformed {
17743                message: format!(
17744                    "invalid canonical JSON in GitHub issue onetaskgraph metadata slot: {error}"
17745                ),
17746            }
17747        })?;
17748    let before = &body[..slot.start];
17749    let visible = before.strip_suffix(METADATA_SEPARATOR).unwrap_or(before);
17750    Ok(((!visible.is_empty()).then(|| visible.to_owned()), metadata))
17751}
17752
17753/// Where the metadata slot sits in one body, as byte offsets into it.
17754struct SlotSpan {
17755    /// Where [`METADATA_OPEN`] begins.
17756    start: usize,
17757    /// Where the encoded JSON begins, just past [`METADATA_OPEN`].
17758    encoded_start: usize,
17759    /// Where the encoded JSON ends, at the start of [`METADATA_CLOSE`].
17760    encoded_end: usize,
17761    /// Just past [`METADATA_CLOSE`].
17762    end: usize,
17763}
17764
17765/// The slot at the very end of `body`, or `None` when it has none.
17766///
17767/// The one reading of *where the slot is*, shared by [`metadata_body`], which reads it, and
17768/// [`with_slot`], which rewrites it — so the two cannot disagree about which comment is the
17769/// slot.
17770fn slot_span(body: &str) -> Result<Option<SlotSpan>, SourceError> {
17771    let Some(start) = body.rfind(METADATA_OPEN) else {
17772        return Ok(None);
17773    };
17774    let encoded_start = start + METADATA_OPEN.len();
17775    let Some(relative_end) = body[encoded_start..].find(METADATA_CLOSE) else {
17776        return Err(SourceError::Malformed {
17777            message: "unterminated onetaskgraph metadata slot in GitHub issue body".into(),
17778        });
17779    };
17780    let encoded_end = encoded_start + relative_end;
17781    let end = encoded_end + METADATA_CLOSE.len();
17782    if !body[end..].trim().is_empty() {
17783        return Ok(None);
17784    }
17785    Ok(Some(SlotSpan {
17786        start,
17787        encoded_start,
17788        encoded_end,
17789        end,
17790    }))
17791}
17792
17793/// `body` with its metadata slot holding exactly `metadata`, and every byte outside the
17794/// slot as it was.
17795///
17796/// A slot that is there has its JSON replaced in place; one that becomes empty is removed
17797/// together with the one [`METADATA_SEPARATOR`] separating it from the prose before it. A
17798/// body with no slot gains one the way [`compose_body`] writes it — after that separator,
17799/// or alone in an empty body — and a body with no slot that is given no metadata is
17800/// returned as it is.
17801fn with_slot(body: &str, metadata: &BTreeMap<String, Value>) -> Result<String, SourceError> {
17802    let encoded = if metadata.is_empty() {
17803        None
17804    } else {
17805        Some(
17806            serde_json::to_string(metadata).map_err(|error| SourceError::Malformed {
17807                message: error.to_string(),
17808            })?,
17809        )
17810    };
17811    Ok(match (slot_span(body)?, encoded) {
17812        (Some(slot), Some(encoded)) => format!(
17813            "{}{encoded}{}",
17814            &body[..slot.encoded_start],
17815            &body[slot.encoded_end..]
17816        ),
17817        (Some(slot), None) => {
17818            let before = &body[..slot.start];
17819            format!(
17820                "{}{}",
17821                before.strip_suffix(METADATA_SEPARATOR).unwrap_or(before),
17822                &body[slot.end..]
17823            )
17824        }
17825        (None, None) => body.to_owned(),
17826        (None, Some(encoded)) if body.is_empty() => {
17827            format!("{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17828        }
17829        (None, Some(encoded)) => {
17830            format!("{body}{METADATA_SEPARATOR}{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17831        }
17832    })
17833}
17834
17835/// `body` with everything before its metadata slot replaced by `content`, and the slot
17836/// itself kept byte for byte.
17837///
17838/// The inverse of how [`metadata_body`] splits a body: the slot, when there is one, follows
17839/// `content` after the one [`METADATA_SEPARATOR`] the composer puts there — or alone, when
17840/// `content` is empty — so a read of the result reports `content` as the visible body and
17841/// the slot's metadata exactly as it was.
17842fn with_content(body: &str, content: &str) -> Result<String, SourceError> {
17843    let Some(slot) = slot_span(body)? else {
17844        return Ok(content.to_owned());
17845    };
17846    let kept = &body[slot.start..];
17847    Ok(if content.is_empty() {
17848        kept.to_owned()
17849    } else {
17850        format!("{content}{METADATA_SEPARATOR}{kept}")
17851    })
17852}
17853
17854/// Hold `entries` under `key` in one slot's metadata, or no such key when there are none.
17855fn set_task_list(metadata: &mut BTreeMap<String, Value>, key: &str, entries: &[TaskRef]) {
17856    if entries.is_empty() {
17857        metadata.remove(key);
17858    } else {
17859        metadata.insert(
17860            key.to_owned(),
17861            Value::Array(
17862                entries
17863                    .iter()
17864                    .map(|entry| Value::String(entry.as_str().to_owned()))
17865                    .collect(),
17866            ),
17867        );
17868    }
17869}
17870
17871fn compose_body(
17872    content: Option<&str>,
17873    metadata: &BTreeMap<String, Value>,
17874) -> Result<Option<String>, SourceError> {
17875    let visible = content.unwrap_or_default();
17876    if metadata.is_empty() {
17877        return Ok((!visible.is_empty()).then(|| visible.to_owned()));
17878    }
17879    let encoded = serde_json::to_string(metadata).map_err(|error| SourceError::Malformed {
17880        message: error.to_string(),
17881    })?;
17882    Ok(Some(if visible.is_empty() {
17883        format!("{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17884    } else {
17885        format!("{visible}{METADATA_SEPARATOR}{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17886    }))
17887}
17888
17889fn required_bool(value: &Value, field: &str) -> Result<bool, SourceError> {
17890    value
17891        .get(field)
17892        .and_then(Value::as_bool)
17893        .ok_or_else(|| SourceError::Malformed {
17894            message: format!("GitHub response is missing boolean field {field}"),
17895        })
17896}
17897fn optional_str<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>, SourceError> {
17898    match value.get(field) {
17899        None | Some(Value::Null) => Ok(None),
17900        Some(value) => value
17901            .as_str()
17902            .map(Some)
17903            .ok_or_else(|| SourceError::Malformed {
17904                message: format!("GitHub response field {field} is not a string or null"),
17905            }),
17906    }
17907}
17908fn optional_nodes<'a>(
17909    connection: Option<&'a Value>,
17910    name: &str,
17911) -> Result<Option<&'a Vec<Value>>, SourceError> {
17912    match connection {
17913        None | Some(Value::Null) => Ok(None),
17914        Some(value) => value
17915            .get("nodes")
17916            .and_then(Value::as_array)
17917            .map(Some)
17918            .ok_or_else(|| SourceError::Malformed {
17919                message: format!("GitHub {name}.nodes is not an array"),
17920            }),
17921    }
17922}
17923fn complete_connection(connection: &Value, name: &str, size: u32) -> Result<(), SourceError> {
17924    let page_info = connection
17925        .get("pageInfo")
17926        .ok_or_else(|| SourceError::Malformed {
17927            message: format!("GitHub {name} has no pageInfo"),
17928        })?;
17929    if required_bool(page_info, "hasNextPage")? {
17930        return Err(SourceError::Malformed {
17931            message: format!(
17932                "GitHub {name} exceeds the supported nested connection size of {size}"
17933            ),
17934        });
17935    }
17936    Ok(())
17937}
17938fn optional_time(value: &Value, field: &str) -> Result<Option<DateTime<Utc>>, SourceError> {
17939    optional_str(value, field)?
17940        .map(|timestamp| {
17941            timestamp.parse().map_err(|error| SourceError::Malformed {
17942                message: format!("GitHub response field {field} is not a timestamp: {error}"),
17943            })
17944        })
17945        .transpose()
17946}
17947fn validate_page(page: &PageRequest) -> Result<(), SourceError> {
17948    if page.limit == 0 {
17949        Err(SourceError::Config {
17950            message: "page limit must be at least 1".into(),
17951        })
17952    } else {
17953        Ok(())
17954    }
17955}
17956fn next_cursor(connection: &Value) -> Result<Option<Cursor>, SourceError> {
17957    let page = connection
17958        .get("pageInfo")
17959        .filter(|value| value.is_object())
17960        .ok_or_else(|| SourceError::Malformed {
17961            message: "GitHub connection is missing pageInfo".into(),
17962        })?;
17963    if required_bool(page, "hasNextPage")? {
17964        let cursor = required_str(page, "endCursor")?;
17965        validate_cursor_progress(None, cursor)?;
17966        Ok(Some(Cursor(cursor.into())))
17967    } else {
17968        Ok(None)
17969    }
17970}
17971fn validate_cursor_progress(previous: Option<&str>, next: &str) -> Result<(), SourceError> {
17972    if next.is_empty() || previous == Some(next) {
17973        Err(SourceError::Malformed {
17974            message: "GitHub pagination cursor is empty or did not advance".into(),
17975        })
17976    } else {
17977        Ok(())
17978    }
17979}
17980/// The version of this plugin's opaque narrowing-search cursor.
17981pub const SEARCH_CURSOR_VERSION: u32 = 4;
17982
17983#[derive(Serialize, Deserialize)]
17984#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
17985enum SearchConnection {
17986    Initial {},
17987    Continuing { after: Cursor },
17988    Exhausted {},
17989}
17990impl SearchConnection {
17991    fn after(&self) -> Option<&str> {
17992        match self {
17993            Self::Continuing { after } => Some(&after.0),
17994            _ => None,
17995        }
17996    }
17997    fn exhausted(&self) -> bool {
17998        matches!(self, Self::Exhausted { .. })
17999    }
18000    /// Whether a cursor naming this position, `offset` rows into its page, is one this
18001    /// plugin could have handed out: a page is resumed only part of the way through it — an
18002    /// offset of GitHub's whole page maximum or more would skip rows nobody was given; a batched
18003    /// search sharing a page with a larger one of its text stops anywhere inside it — an
18004    /// initial page only once some of it was handed out, and an exhausted connection has no
18005    /// page to be part of the way through.
18006    fn valid_resume(&self, offset: usize) -> bool {
18007        let within = offset < MAX_PAGE_SIZE as usize;
18008        match self {
18009            Self::Initial { .. } => offset > 0 && within,
18010            Self::Continuing { after } => !after.0.is_empty() && within,
18011            Self::Exhausted { .. } => offset == 0,
18012        }
18013    }
18014}
18015
18016/// Versioned source cursor. A zero offset and empty own-write ids are omitted.
18017#[derive(Serialize, Deserialize)]
18018#[serde(deny_unknown_fields)]
18019struct SearchPosition {
18020    version: u32,
18021    connection: SearchConnection,
18022    /// How many rows of the page `connection` starts were already handed out.
18023    #[serde(default, skip_serializing_if = "is_zero")]
18024    offset: usize,
18025    #[serde(default, skip_serializing_if = "Vec::is_empty")]
18026    seen: Vec<NativeId>,
18027    #[serde(default, skip_serializing_if = "Vec::is_empty")]
18028    own: Vec<NativeId>,
18029}
18030impl Default for SearchPosition {
18031    fn default() -> Self {
18032        Self {
18033            version: SEARCH_CURSOR_VERSION,
18034            connection: SearchConnection::Initial {},
18035            offset: 0,
18036            seen: Vec::new(),
18037            own: Vec::new(),
18038        }
18039    }
18040}
18041
18042fn is_zero(offset: &usize) -> bool {
18043    *offset == 0
18044}
18045
18046fn numeric_cursor(cursor: Option<&Cursor>) -> Result<usize, SourceError> {
18047    cursor.map_or(Ok(0), |c| {
18048        c.0.parse().map_err(|_| SourceError::Config {
18049            message: "page cursor is invalid".into(),
18050        })
18051    })
18052}
18053fn offset_page<T>(mut items: Vec<T>, offset: usize, limit: usize) -> Page<T> {
18054    if offset > items.len() {
18055        return Page::last(vec![]);
18056    }
18057    let tail = items.split_off(offset);
18058    let mut selected = tail;
18059    let next = (selected.len() > limit).then(|| Cursor((offset + limit).to_string()));
18060    selected.truncate(limit);
18061    Page {
18062        items: selected,
18063        next,
18064    }
18065}
18066
18067impl GitHubProjectsSource {
18068    /// The body [`Self::write_item`] would compose for `incoming`, sized in the characters
18069    /// [`BODY_LIMIT`] counts, without a request: its slot as `slot_metadata` writes it, every
18070    /// asset reference rewritten to its recorded URL or — for one not uploaded yet — to an
18071    /// address as long as GitHub's, and the heading markup this board's bodies carry.
18072    ///
18073    /// What the write reads rather than knows is taken as it most often lands: the issue in
18074    /// the one repository the item names, else the configured one, and every edge on the
18075    /// board's own relationships rather than in the slot.
18076    fn body_size(&self, incoming: &Incoming<'_>) -> onetaskgraph_plugin_api::BodySize {
18077        let own = match incoming.repositories {
18078            [named] => Some(named.clone()),
18079            _ => self
18080                .repository
18081                .as_ref()
18082                .and_then(|target| Repository::try_from(target.origin()).ok()),
18083        };
18084        let mut slot = slot_metadata(incoming, own.as_ref(), &[]);
18085        let content = match incoming.assets {
18086            Some(assets) => {
18087                let mut uploads = onetaskgraph_plugin_api::AssetUploads::default();
18088                for asset in &assets.assets {
18089                    let url = assets
18090                        .recorded_assets
18091                        .as_ref()
18092                        .and_then(|recorded| recorded.reusable(&asset.name, &asset.sha256))
18093                        .unwrap_or(PREDICTED_ATTACHMENT_URL)
18094                        .to_owned();
18095                    uploads.0.insert(
18096                        asset.name.clone(),
18097                        onetaskgraph_plugin_api::AssetUpload {
18098                            sha256: asset.sha256.clone(),
18099                            url,
18100                        },
18101                    );
18102                }
18103                incoming.content.map(|content| {
18104                    onetaskgraph_plugin_api::serve_asset_references(content, &mut slot, &uploads)
18105                })
18106            }
18107            None => incoming.content.map(str::to_owned),
18108        };
18109        let marked = content.as_deref().map(|content| self.marked(content));
18110        let size = compose_body(marked.as_deref(), &slot)
18111            .ok()
18112            .flatten()
18113            .map_or(0, |body| body.chars().count());
18114        onetaskgraph_plugin_api::BodySize {
18115            size: u64::try_from(size).unwrap_or(u64::MAX),
18116            limit: Some(BODY_LIMIT),
18117        }
18118    }
18119
18120    async fn write_task_assets(
18121        &self,
18122        write: &ItemWrite<Task>,
18123        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
18124    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
18125        self.write_item(
18126            &self.task_incoming(write, assets)?,
18127            write.target.as_ref(),
18128            &write.depends_on,
18129        )
18130        .await
18131    }
18132
18133    /// One task write as [`Self::write_item`] takes it, once what it delivers and its priority
18134    /// are known to be ones this source can write.
18135    fn task_incoming<'a>(
18136        &self,
18137        write: &'a ItemWrite<Task>,
18138        assets: Option<&'a onetaskgraph_plugin_api::AssetWrite>,
18139    ) -> Result<Incoming<'a>, SourceError> {
18140        let near = write.target.as_ref().unwrap_or(&write.item.id);
18141        for (key, entries) in [
18142            (TaskRef::DELIVERS_KEY, &write.item.delivers),
18143            (TaskRef::DELIVERED_BY_KEY, &write.item.delivered_by),
18144        ] {
18145            TaskRef::listed(key, near, Some(&self.name), entries.clone())
18146                .map_err(|message| SourceError::Refused { message })?;
18147        }
18148        if self.priorities.is_none() && write.item.priority != Priority::None {
18149            return Err(self.holds_no_priority());
18150        }
18151        if write.item.assignees.is_some() && !self.assignees {
18152            return Err(onetaskgraph_plugin_api::unwritable_field(KIND, "assignees"));
18153        }
18154        Ok(Incoming {
18155            written: Written::Work(ItemKind::Task, &write.item.status),
18156            title: &write.item.title,
18157            content: write.item.content.as_deref(),
18158            assets,
18159            labels: &write.item.labels,
18160            metadata: &write.item.metadata,
18161            repositories: &write.item.repositories,
18162            classification: write.item.classification,
18163            parent: write.item.project.as_ref(),
18164            delivers: &write.item.delivers,
18165            delivered_by: &write.item.delivered_by,
18166            priority: self.priorities.as_ref().map(|_| write.item.priority),
18167            assignees: write.item.assignees.as_deref(),
18168        })
18169    }
18170    async fn write_document_assets(
18171        &self,
18172        write: &ItemWrite<Document>,
18173        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
18174    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
18175        // A document takes part in no dependency graph, so there is no far end to write
18176        // natively and none to record: a caller naming one is told so rather than having it
18177        // stored under the reserved key, where a later read would report an edge the
18178        // contract says cannot exist.
18179        if !write.depends_on.is_empty() {
18180            return Err(SourceError::Refused {
18181                message: format!(
18182                    "this write names {} dependencies for a document, and a document takes \
18183                     part in no dependency graph; next: put the dependency on the task or \
18184                     project the document is about",
18185                    write.depends_on.len()
18186                ),
18187            });
18188        }
18189        self.write_item(
18190            &Incoming {
18191                written: Written::Document,
18192                title: &write.item.title,
18193                content: write.item.content.as_deref(),
18194                assets,
18195                labels: &write.item.labels,
18196                metadata: &write.item.metadata,
18197                repositories: &write.item.repositories,
18198                classification: write.item.classification,
18199                parent: write.item.project.as_ref(),
18200                delivers: &[],
18201                delivered_by: &[],
18202                priority: None,
18203                assignees: None,
18204            },
18205            write.target.as_ref(),
18206            &[],
18207        )
18208        .await
18209    }
18210}
18211
18212/// What [`TaskSource::end_command`] leaves of this source's held state, asserted on the state
18213/// itself, for the two things no journey can observe.
18214///
18215/// The journeys in `crates/onetaskgraph-e2e/tests/e2e/end_command.rs` prove through the engine,
18216/// with and without the call, that a settlement, a board listing and a metadata search each
18217/// read afresh after it — the resolved records, the written-item overlay, the board and its
18218/// search, and the narrowed searches. What they cannot reach is the held field definitions,
18219/// because a status write naming an option a person deleted is refused the same whether or
18220/// not the list is held, and a poisoned lock, because nothing outside the source can panic
18221/// while one of its locks is held. So these assert those directly, and every other holder
18222/// beside them so a holder added later without a clear in the call fails here.
18223#[cfg(test)]
18224mod end_command_tests {
18225    use super::*;
18226
18227    struct Token;
18228
18229    impl SecretResolver for Token {
18230        fn get(&self, var: &str) -> Option<SecretString> {
18231            (var == "GH_PROJECTS_TOKEN").then(|| "test-token".into())
18232        }
18233    }
18234
18235    fn source() -> GitHubProjectsSource {
18236        let config = serde_json::from_value(json!({
18237            "owner": "octo-org", "project_number": 7, "repository": "acme/work",
18238            // Nothing here is sent: the source is only built and its state inspected.
18239            "endpoint": "http://127.0.0.1:9/graphql",
18240        }))
18241        .expect("a usable configuration");
18242        GitHubProjectsSource::new(&SourceName::new("work").unwrap(), config, &Token)
18243            .expect("the source builds")
18244    }
18245
18246    /// One issue as a board read answers it.
18247    fn resolved(source: &GitHubProjectsSource) -> Resolved {
18248        source
18249            .resolve(&json!({
18250                "id": "ITEM-1",
18251                "content": {"__typename": "Issue", "id": "I_1", "title": "Held",
18252                            "body": "what a person may since have edited", "state": "OPEN",
18253                            "stateReason": null, "url": null, "number": 1,
18254                            "subIssuesSummary": {"total": 0},
18255                            "labels": {"nodes": [], "pageInfo": {"hasNextPage": false}}},
18256                "fieldValues": {"nodes": [], "pageInfo": {"hasNextPage": false}},
18257            }))
18258            .expect("the item reads")
18259            .expect("an issue")
18260    }
18261
18262    /// Hold something in every holder the call clears, and the repository id it keeps.
18263    fn fill(source: &GitHubProjectsSource) {
18264        let item = resolved(source);
18265        source.created.lock().unwrap().push(item.clone());
18266        source.updated.lock().unwrap().push(item.clone());
18267        *source.board_cache.lock().unwrap() = Some(Board {
18268            id: "PVT-board".into(),
18269            fields: json!({"nodes": []}),
18270            items: vec![item.clone()],
18271        });
18272        *source.search_cache.lock().unwrap() = Some(vec![item.clone()]);
18273        source
18274            .narrowed_cache
18275            .lock()
18276            .unwrap()
18277            .insert("status:todo".into(), vec![item.clone()]);
18278        source.children_cache.lock().unwrap().insert(
18279            NativeId("P-1".into()),
18280            (NativeId("P-1".into()), vec![item.clone()]),
18281        );
18282        source
18283            .search_rows
18284            .lock()
18285            .unwrap()
18286            .insert("status:todo".into(), vec![Some(item.clone()), None]);
18287        source
18288            .search_next
18289            .lock()
18290            .unwrap()
18291            .insert("status:todo".into(), Some("cursor".into()));
18292        source
18293            .resolved_cache
18294            .lock()
18295            .unwrap()
18296            .insert(item.id.clone(), item);
18297        *source.fields_cache.lock().unwrap() = Some(BoardFields {
18298            id: BoardId::parse("PVT-board").unwrap(),
18299            fields: json!({"nodes": []}),
18300        });
18301        source
18302            .repository_cache
18303            .lock()
18304            .unwrap()
18305            .insert(RepositoryTarget::parse("acme/work").unwrap(), "R_1".into());
18306    }
18307
18308    fn assert_dropped(source: &GitHubProjectsSource) {
18309        assert!(source.created().unwrap().is_empty(), "created");
18310        assert!(source.updated().unwrap().is_empty(), "updated");
18311        assert!(source.board_cache().unwrap().is_none(), "board");
18312        assert!(source.search_cache.lock().unwrap().is_none(), "search");
18313        assert!(source.narrowed_cache.lock().unwrap().is_empty(), "narrowed");
18314        assert!(source.search_rows.lock().unwrap().is_empty(), "search rows");
18315        assert!(
18316            source.children_cache.lock().unwrap().is_empty(),
18317            "project children"
18318        );
18319        assert!(
18320            source.search_next.lock().unwrap().is_empty(),
18321            "search paging"
18322        );
18323        assert!(
18324            source.resolved_cache().unwrap().is_empty(),
18325            "resolved records"
18326        );
18327        assert!(source.fields_cache().unwrap().is_none(), "board fields");
18328        assert_eq!(
18329            source.repository_cache().unwrap().len(),
18330            1,
18331            "a repository's node id stays valid and is kept"
18332        );
18333    }
18334
18335    fn end(source: &GitHubProjectsSource) {
18336        tokio::runtime::Builder::new_current_thread()
18337            .build()
18338            .unwrap()
18339            .block_on(source.end_command())
18340            .expect("the command ends");
18341    }
18342
18343    #[test]
18344    fn the_call_drops_every_item_search_and_board_read_and_keeps_repository_ids() {
18345        let source = source();
18346        fill(&source);
18347        end(&source);
18348        assert_dropped(&source);
18349    }
18350
18351    #[test]
18352    fn the_call_clears_a_lock_an_earlier_failure_poisoned() {
18353        fn poison<T: Send>(held: &Mutex<T>) {
18354            std::thread::scope(|scope| {
18355                let _ = scope
18356                    .spawn(|| {
18357                        let _guard = held.lock().unwrap();
18358                        panic!("a failure while the lock is held");
18359                    })
18360                    .join();
18361            });
18362            assert!(held.is_poisoned());
18363        }
18364        let source = source();
18365        fill(&source);
18366        poison(&source.created);
18367        poison(&source.updated);
18368        poison(&source.board_cache);
18369        poison(&source.search_cache);
18370        poison(&source.narrowed_cache);
18371        poison(&source.search_rows);
18372        poison(&source.search_next);
18373        poison(&source.resolved_cache);
18374        poison(&source.fields_cache);
18375        assert!(
18376            source.resolved_cache().is_err(),
18377            "a poisoned lock is refused before the call"
18378        );
18379        end(&source);
18380        assert_dropped(&source);
18381    }
18382}
18383
18384#[cfg(test)]
18385mod unprojectable_fields_tests {
18386    use super::*;
18387
18388    /// The field names `docs/metadata.md` says a `metadata_fields` entry may not name.
18389    fn documented() -> std::collections::BTreeSet<String> {
18390        let document = std::fs::read_to_string(
18391            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/metadata.md"),
18392        )
18393        .expect("docs/metadata.md is readable");
18394        let document = document.split_whitespace().collect::<Vec<_>>().join(" ");
18395        let lead = "a `field` equal, ignoring case, to ";
18396        let start = document.find(lead).expect("the refused-field sentence") + lead.len();
18397        let sentence = &document[start..];
18398        let sentence = &sentence[..sentence
18399            .find("; and two entries naming one field")
18400            .expect("the refused-field sentence ends at the duplicate rule")];
18401        let (own, github) = sentence
18402            .split_once(" or a field GitHub owns on every board (")
18403            .expect("the sentence names GitHub's own fields");
18404        own.split('`')
18405            .skip(1)
18406            .step_by(2)
18407            .chain(
18408                github
18409                    .strip_suffix(')')
18410                    .expect("GitHub's own fields close the sentence")
18411                    .split(", "),
18412            )
18413            .map(str::to_owned)
18414            .collect()
18415    }
18416
18417    /// `docs/metadata.md` states the text field's limit a caller is held to; it is this source's
18418    /// own constant, so the two cannot part.
18419    #[test]
18420    fn the_documented_text_field_limit_is_the_one_the_source_shortens_at() {
18421        let document = std::fs::read_to_string(
18422            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/metadata.md"),
18423        )
18424        .expect("docs/metadata.md is readable");
18425        let lead = "**A text field holds at most ";
18426        let start = document.find(lead).expect("the limit sentence") + lead.len();
18427        let stated = &document[start..start + document[start..].find(',').unwrap() + 4];
18428        assert_eq!(
18429            stated.replace(',', "").parse::<usize>().ok(),
18430            Some(TEXT_FIELD_LIMIT),
18431            "docs/metadata.md states {stated:?}"
18432        );
18433        assert!(document[start..].starts_with(&format!("{stated}, counted here in UTF-8 bytes.")));
18434    }
18435
18436    #[test]
18437    fn the_documented_refused_fields_are_exactly_the_ones_the_configuration_refuses() {
18438        let refused: std::collections::BTreeSet<String> = UNPROJECTABLE_FIELDS
18439            .iter()
18440            .map(|&name| name.to_owned())
18441            .collect();
18442        assert_eq!(documented(), refused, "the fields docs/metadata.md lists");
18443        let instance = SourceName::new("work").unwrap();
18444        for name in UNPROJECTABLE_FIELDS {
18445            for spelled in [name.to_owned(), name.to_uppercase()] {
18446                let entry = MetadataFieldConfig {
18447                    field: spelled.clone(),
18448                    key: "team.machine".to_owned(),
18449                    path: Vec::new(),
18450                };
18451                let refused = MetadataField::resolve(vec![entry], &instance)
18452                    .expect_err("an unprojectable field is refused");
18453                assert!(
18454                    refused.to_string().contains(&format!("{name:?}")),
18455                    "{spelled}: {refused}"
18456                );
18457            }
18458        }
18459    }
18460}