Skip to main content

onetaskgraph_linear/
lib.rs

1//! A read/write source over Linear's published GraphQL API.
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: Linear takes no conditional write, so the engine reads
5//! the issue through this source just before writing it, and a change landing between that read
6//! and the mutation — the time one request takes — is Linear's residual race. The version is
7//! the `lin1` token its `updatedAt` and facets give.
8//!
9//! Linear `Issue` maps to [`Task`], `Project` to [`Project`], `Document` to [`Document`],
10//! `IssueLabel` and `ProjectLabel` to [`Label`], and an issue's `WorkflowState.name` and a
11//! project's `ProjectStatus.name` are preserved as the status's name while the source's
12//! `status_mapping` — the one grammar every source that names its statuses is configured with,
13//! [`StatusMapping`] — decides its category. Issue `relations`/`inverseRelations` and
14//! project relations provide native dependency traversal in both directions.
15//!
16//! Label, workflow-state, project, and orphan filters are sent in the
17//! `issues(filter:)`/`projects(filter:)` variables. Pagination uses Relay `first` and
18//! `after`.
19//!
20//! Every issue, project and document reports its own Linear web address as its
21//! [`Location`], as a link rather than a path — the counterpart of a folder of Markdown
22//! reporting the path of the file behind an item. It does not replace the `url` field
23//! those types already carry; it is the same address said in the shape a reader can act on.
24//!
25//! # What this source declares, field by field
26//!
27//! One verdict per field of [`Capabilities`]. A field is *supported and proven* when this
28//! source applies it and a shared journey drives it against the real binary; the shared
29//! table is `crates/onetaskgraph-e2e-support/src/fixtures.rs`, the journeys are beside it, and
30//! `every_row_declares_exactly_what_its_plugin_reports` is what keeps this list and
31//! [`capabilities`](TaskSource::capabilities) from parting.
32//!
33//! | Field | Verdict |
34//! | --- | --- |
35//! | `projects` | **Supported and proven.** `issues(filter:{project:{id:{eq:…}}})`. |
36//! | `documents` | **Supported and proven.** Linear's own first-class `Document`, read through `documents(first:,after:,filter:)` and `document(id:)`, written through `documentCreate`/`documentUpdate` and taken back by `documentDelete`. See the ruling below on what a Linear document cannot hold. |
37//! | `comments` | **Supported and proven,** as the issue's own comments: read oldest first through `issue(id:){comments(last:,before:)}`, added with `commentCreate`, edited with `commentUpdate` and removed with `commentDelete` — each of the last two only once `comment(id:)` has placed the comment on that very issue. See the ruling below on the order and on the author. |
38//! | `assets` | **Supported and proven.** Native asset support: Images are uploaded through Linear's `fileUpload` flow, verified by an authenticated GET, and their Markdown references rewritten before content is written. Matching recorded SHA-256 values reuse their URLs. Images are visible to authenticated members of the workspace; see [`assets`] for the mechanism and bounded retries. |
39//! | `priority` | **Supported,** as Linear's own `Issue.priority`: read on every issue, written by `issueCreate`/`issueUpdate` through `IssueCreateInput.priority`/`IssueUpdateInput.priority`, and set on its own by an `issueUpdate` carrying nothing else. See the ruling below on the scale. |
40//! | `filter_by_priority` | **Supported and proven.** `issues(filter:{priority:{in:[…]}})` over Linear's own `0`–`4` scale, confirmed against each issue read. |
41//! | `filter_by_comment_activity` | **Supported and proven.** `comments:{some:{or:[{createdAt:{gte:…}},{updatedAt:{gte:…}}]}}` — the issues with a comment created or last edited at or after the instant, over the same two fields a comment read reports. |
42//! | `filter_by_metadata` | **Supported and proven.** `description:{contains:"\"<value>\""}` for each match — the value as every JSON encoder writes it, which a slot holding it contains however it spaces or spells its keys — and every candidate confirmed over the parsed slot, so prose carrying the phrase and a slot holding another value are both kept out. A value with a character an encoder may escape is not sent, and the confirmation decides alone. |
43//! | `filter_by_origin` | **Supported and proven,** on the same terms, for the slot's `onetaskgraph.origin` — and a lookup that lists nothing reads the record its origin's create key names by id; see the ruling below on how a copy finds what it wrote. |
44//! | `reconcile_status` | **Unsupported — unsupportable.** A Linear issue's workflow state *is* its closure: there is no card beside it to contradict it, so nothing could need reconciling and the source is sent nothing. |
45//! | `complete_by_issue` | **Unsupported — unsupportable** here: a Linear issue is not a GitHub issue a landing's `closes` names, and its state is its closure, so a completion lists this source unsupported and sends it nothing. |
46//! | `orphan_tasks` | **Supported and proven.** `issues(filter:{project:{null:true}})`. |
47//! | `filter_by_label` | **Supported and proven.** `labels:{some:{name:{eqIgnoreCase:…}}}` for what an item must carry — one per label, gathered under `or:` where any one of them will do — and `labels:{every:{name:{neqIgnoreCase:…}}}` for what it must not. Linear's `StringComparator` has no case-insensitive list operator; see the note beside `filter`. |
48//! | `filter_by_status` | **Supported and proven,** and spelled twice. An issue narrows by its workflow state's name, `state:{name:{eqIgnoreCase:…}}`; a project by its project status's name, `status:{name:{eqIgnoreCase:…}}` — a different member of a different filter over a different vocabulary — each by the names its kind's half of `status_mapping` gives, and `unknown` by every name that half does not give. See the ruling below. |
49//! | `search_title` | **Supported and proven.** A task query's text is `title:{containsIgnoreCase:…}`, every candidate confirmed by the contract's case-insensitive substring rule; a project or document query's text is applied by that same rule over the page Linear answered. |
50//! | `search_content` | **Supported and proven,** on the same terms, `description:{containsIgnoreCase:…}`, confirmed over the visible content — the trailing metadata slot Linear's comparator also reads is not part of what the rule confirms. A `title-or-content` search sends the two under one `or`. |
51//! | `task_dependencies` | **Supported and proven,** in both directions: `relations` and `inverseRelations`. |
52//! | `project_dependencies` | **Supported and proven,** in both directions, by the project relations of the same shape. Linear types every one of them `dependency`; see the ruling below on the edge that has no spelling here. |
53//! | `max_page_size` | **Supported and proven.** 100; every read pages with Relay `first`/`after`. Linear's connection maximum is 250 and its complexity budget is the tighter bound — see [`MAX_PAGE_SIZE`]. |
54//!
55//! ## Ruling: the follow-up searches are native, and what each rests on
56//!
57//! Six predicates a follow-up search sends — metadata, origin, comment activity, priority,
58//! and the two text searches — are each sent to Linear as a narrowing of `issues(filter:)`
59//! and confirmed in process before a row is returned. Each narrowing is a candidate set that
60//! cannot miss a row the contract's predicate keeps, which is what makes sending it sound;
61//! the confirmation is what makes the answer exact. Every member below is pinned in
62//! `tests/fixtures/schema.graphql`, and each rests on one observation of the real API,
63//! against the scratch team `TES` on 2026-10-02, which `drive_follow_ups` in `tests/live.rs`
64//! asserts again — the comparators by name, and every narrowing through this source with a
65//! decoy whose prose carries the searched phrases:
66//!
67//! - **`IssueFilter.description.contains` reads the whole stored description, the metadata
68//!   slot included, and is case-sensitive.** An issue whose slot held
69//!   `"caller.key":"needle-…"` was returned for `contains` of that exact phrase, and of the
70//!   `"onetaskgraph.origin":"…"` pair beside it; the same description's prose, upper-cased,
71//!   was returned for `containsIgnoreCase` and *not* for `contains`. So a metadata match or an
72//!   origin is sent as its value in quotes, `"<value>"` — the bytes any JSON encoder writes a
73//!   string as, which a slot holding it contains whether it is the code span this source
74//!   writes, the multi-line slot it wrote before, or one a person spaced by hand — and
75//!   confirmed over the parsed slot. A value holding a character an encoder may escape is not
76//!   sent, and the confirmation decides alone.
77//! - **`IssueFilter.title.containsIgnoreCase` and `description.containsIgnoreCase` match
78//!   regardless of case** — the title `… Alpha Title` was returned for `alpha TITLE`, and not
79//!   for `contains` of it. They are the two text searches; the content search is confirmed
80//!   over the visible content, because the comparator also reads the slot.
81//! - **`IssueFilter.priority.in` narrows by Linear's own number** — an issue at `2` was
82//!   returned for `in:[2]` and not for `in:[3]`.
83//! - **`IssueFilter.comments.some` with `createdAt`/`updatedAt` `gte` narrows by a comment's
84//!   own times** — an issue whose comment had been edited a moment earlier was returned for an
85//!   instant before the edit and not for one a day later, and editing the comment moved its
86//!   `updatedAt` while leaving `createdAt`. The comment read reports those same two fields,
87//!   so the filter and the contract's rule read one value.
88//!
89//! ## Ruling: what Linear does to an HTML comment, settled
90//!
91//! A follow-up tool marks what it writes with HTML comments, and this source keeps its own
92//! metadata in one, so what survives is a fact this crate records rather than assumes.
93//! Observed on 2026-10-02 against the scratch team `TES`, each written and read back by id,
94//! and asserted again — the probe text and its stored form exactly — by `drive_follow_ups` in
95//! `tests/live.rs`, a leg of its `real_linear_applies_every_declared_capability_and_leaves_no_residue`:
96//!
97//! - **A comment's `body` keeps every HTML comment byte for byte** — on one line or across
98//!   several, a bare `-->` closing line, domain-like text and JSON included.
99//! - **An issue's `description` and a document's `content` do not.** Linear stores both as
100//!   Markdown and normalizes the text *inside* an HTML comment exactly as it normalizes prose:
101//!   a domain-like token or a URL is autolinked — `example.com` comes back
102//!   `[example.com](<http://example.com>)`, and a key such as `caller.live` likewise — `[` and
103//!   `]` come back `\[` and `\]`, `~` comes back `\~`, `_y_` comes back `*y*`, the backslash
104//!   of `\"` is dropped, a backslash before a letter is doubled, and a line opening `-->` comes
105//!   back `\-->`. Text with none of those in it — `{"k":"v"}`, `caller.key`, `sha256:…`,
106//!   `gh:I_kwDO…` — comes back as written. An autolink can run on past the token, swallowing
107//!   what follows it up to the next delimiter.
108//! - **One thing in those two fields comes back byte for byte: a code span.** An HTML comment
109//!   on one line whose payload is inside backticks — ``<!-- probe `{…}` -->`` — came back
110//!   identical with every one of the payloads above inside it, and re-writing what Linear
111//!   handed back changed nothing more. So this source writes its own slot that way (see
112//!   `METADATA_OPEN_SPAN`), and a marker meant to survive an issue's description or a
113//!   document's content belongs in one too.
114//!
115//! ## Ruling: what Linear stores is read off each write's own answer
116//!
117//! **Document-content contract:** writes send the caller's Markdown plus this source's
118//! code-span metadata slot. Reads return Linear's stored Markdown with that slot and its
119//! separator removed; they do not promise the caller's original bytes. `stored_content`
120//! reports the write answer in that same form. Code-span payloads survive unchanged;
121//! prose and HTML-comment payloads may be normalized. The captured response in
122//! `tests/fixtures/document-content-40721997875.json` records autolinking, bracket escaping
123//! and a comment terminator escape. What that run read after the Markdown probe's update
124//! matches, byte for byte, the stored form of the HTML-comment probe written before it. The
125//! working hypothesis — not yet confirmed against real Linear — is a by-id read lagging the
126//! write rather than a new rewrite rule, so the live journey waits within its replica bound
127//! for the exact recorded content, refusing a different value when that bound expires; the
128//! required live capability journey comparing both exact probes is what confirms or refutes
129//! it. Hosted run
130//! 40734970799 also missed freshly created projects in the unfiltered listing. That listing
131//! is retried within the existing index bound (21 reads, one second apart), still requiring
132//! both created projects; the journey's test timeout is unchanged.
133//!
134//! Linear stores an issue's `description`, a project's `content` and a document's `content` as
135//! Markdown it normalizes on write — `- ` bullets come back `* `, a table's delimiter row `| -- |`,
136//! a blank line is set before a list after a heading or a paragraph line and between two images
137//! on adjacent lines, an ordered item on a lazy-continuation line inside a list item is escaped,
138//! an inline code span wrapped across two lines is joined, `**bold**` spanning a line break is
139//! split into one run per line, an indented code block becomes a fenced one, and more — so the
140//! bytes a read hands back are not the bytes a write sent. That serializer is a whole-document
141//! one, and a table of its rules never converges: spike `spike-linear-stored-content` found
142//! Linear rewrote 11 of 14 probes, both realistic bodies — a rendered plan task and a design
143//! document — among them. So this source predicts nothing. Each of the eight writes that carry
144//! the long form — [`graphql::ISSUE_CREATE`], [`graphql::ISSUE_UPDATE`],
145//! [`graphql::ISSUE_REWRITE`], [`graphql::PROJECT_CREATE`], [`graphql::PROJECT_UPDATE`],
146//! [`graphql::PROJECT_REWRITE`], [`graphql::DOCUMENT_CREATE`] and [`graphql::DOCUMENT_UPDATE`] —
147//! selects what Linear stored in its own answer, with no request of its own, and
148//! [`TaskSource::stored_content`] hands the content in it — the metadata slot and its separator
149//! removed, as a read reports content — to the engine, once. The same spike found every create's
150//! and every update's answer byte-identical to a read of the item by id a few seconds later, for
151//! all 14 probes on issues, documents and a project, two adjacent uploaded images included: the
152//! answer *is* the read, so no read of an item follows a write of it here.
153//!
154//! The engine sends the content as it composed it. Where Linear's answer reports exactly that,
155//! the write is done: one request. Where it reports other content S, the engine recomputes every
156//! fingerprint it records over S — a rendering's `body_digest`, a copy's
157//! `onetaskgraph.copied_destination_version` — and sends one follow-up write, as its own
158//! request, of S verbatim with the metadata slot carrying them. That follow-up's own answer has
159//! to report S again, and an item it does not is refused as `stored-content-diverged`: Linear
160//! not holding its own stored content stable, which the spike measured as never happening. What
161//! moved was only the separator: where S ends in a table row and its line break, `S + "\n\n" +
162//! slot` is stored as `S + "\n" + slot`, which is no change to S — so the follow-up is judged by
163//! the content its answer reports, never by whether its whole long form is what was sent, and
164//! [`metadata_description`] recovers S exactly without cutting into it. A copy's follow-up that
165//! finishes a link also holds text of the store's own Linear has not seen, so an answer differing
166//! only as Linear autolinks or escapes that text is written back once more rather than refused:
167//! the engine's `stored::normalized` tells it from a change a person made.
168//! Both halves hold whichever way the store loads this source: served over the stdio plugin
169//! protocol, the stored content crosses as a write result's `stored_content`
170//! (`docs/plugin-protocol.md` §3.16, §4.9).
171//!
172//! **What this means for a caller:** Linear may normalize the spelling of a content write while
173//! keeping its rendered meaning, and `task content set` reports the content Linear stored, read
174//! off that write's own answer. The local check [`TaskSource::set_task_content`] still makes —
175//! that the content cannot be mistaken for the metadata slot — is the one thing checked before
176//! a content write.
177//!
178//! ## Ruling: the requests a copy into Linear sends, each justified
179//!
180//! A first copy of a realistic plan — one project, five tasks and one design document with two
181//! new images — sends 20 requests where an earlier release sent 22, and an unchanged re-copy
182//! writes nothing. `linear-requests-per-plan-copy` in `crates/onetaskgraph-linear-e2e/budgets.yaml`
183//! holds the figure. Each request that stays:
184//!
185//! - **One origin lookup for the whole project copy.** [`TaskSource::read_ahead_origins_for_copy`]
186//!   asks, in one request per 50 origins, for every Linear item an earlier copy made of the
187//!   project and of each task, and for the workspace's `organization{id}`
188//!   [`TaskSource::designator`] answers from; see the ruling on that read below.
189//! - **A document copy's own `documents` origin lookup**, because a first copy of a document
190//!   whose local record names no Linear item has to find one an earlier copy made rather than
191//!   make a second, and it is a command of its own. Its destination project is not read: a
192//!   document is filed under the project its project's copy link names, on that link alone.
193//! - **One content write per item**, and **one follow-up write per item Linear rewrites** —
194//!   every item of a first copy of a real plan, since Linear rewrote both realistic bodies, and
195//!   none of an unchanged re-copy, which the copy record recognises without a write.
196//! - **Per new image, one `fileUpload` and one PUT** of its bytes ([`assets`]); an unchanged
197//!   image costs nothing.
198//!
199//! The reads a metadata, content or rendering write makes *before* it writes stay, because they
200//! keep the metadata slot byte for byte; no read of an item follows a write of it.
201
202//! ## Ruling: a Linear document carries no label, and that is Linear's
203//!
204//! Unlike the two searches above, this one *is* a property of the remote service. The
205//! types of Linear's published schema carrying a `labels` field are `Issue`, `Project`,
206//! `Team`, `Initiative` and `Organization`; `Document` is not among them, re-observed
207//! 2026-09-01 and pinned in `tests/fixtures/schema.graphql`. So this source reports a
208//! document's labels as none and **refuses by name** a document write carrying one, rather
209//! than dropping it or standing a slot up beside a first-class type. The shared journey
210//! table's row says so, and the shared document journeys drive that claim.
211//!
212//! Two predicates therefore reach a fetched page rather than the `documents(filter:)`
213//! variables, and both are still *applied* — which is what `Native` means here, and why
214//! the declaration stays honest. Labels, for the reason above. And orphans, because
215//! `DocumentFilter.project` is a `ProjectFilter` where `IssueFilter.project` is a
216//! `NullableProjectFilter`: only the nullable one carries `null:`, so Linear cannot be
217//! asked for the documents belonging to no project. The page-by-page walk asks for only
218//! what is still owed, so neither predicate can make a read return more than the caller
219//! asked for, and neither can drop a document the walk already fetched.
220//!
221//! ## Ruling: a comment is read backwards, and its author is Linear's to record
222//!
223//! **The order.** The contract owes a task's comments oldest first, across pages, and Linear's
224//! `Issue.comments` takes no sort direction — only `orderBy`, whose members are `createdAt`
225//! (the default) and `updatedAt`. Linear's pagination documentation says results are "ordered
226//! by `createdAt`" and that "to get most recently updated resources, you can alternatively
227//! order by `updatedAt`", which reads that ordering as newest first. So this source walks the
228//! connection from its far end: `last` with `before`, each page reversed, the next page's
229//! cursor being `startCursor` while `hasPreviousPage` holds. Reversing within a page and
230//! walking backwards across them is what makes the whole walk oldest first rather than each
231//! page alone. **That direction is inferred from the documentation's wording rather than
232//! observed against the real API,** which is the one reading here a live run has not yet
233//! confirmed; if Linear is found to list oldest first, the correction is this walk's
234//! direction and nothing else.
235//!
236//! **The author.** Linear records the user whose credential made the request as a comment's
237//! author, and this source authenticates with an API key. `CommentCreateInput.createAsUser`
238//! exists but is, in Linear's own words, "only available to OAuth applications creating
239//! comments in `actor=app` mode", which a key is not. So a comment carrying an author is
240//! **refused before any request is sent**, naming why and what to do instead, rather than
241//! posted under a name other than the one it was given. An author read back is the user's
242//! `displayName`, which Linear keeps unique within a workspace, and is absent when Linear
243//! names no user — a comment an integration or a bot wrote.
244//!
245//! **What "no such comment" means.** An edit or a removal first asks `comment(id:)` which
246//! issue the comment is on, and answers "no such comment" — no mutation sent — unless it is
247//! the task's own issue: a comment on another issue, on no issue at all, or trashed, is not a
248//! comment this task has. The body is Linear's `body`, which its schema describes as markdown
249//! derived from a rich-text document, so what an add or an edit answers with is what Linear
250//! now holds rather than an echo of what was sent.
251//!
252//! ## Ruling: a project's filter is not an issue's, and neither is its status
253//!
254//! Linear's `IssueFilter` and `ProjectFilter` read as one filter over two kinds of row.
255//! They are two input types, and this source built one object for both until 2026-09-04,
256//! which put two members into `projects(filter:)` that Linear does not have there. It
257//! refused the first outright — `Field "team" is not defined by type "ProjectFilter". Did
258//! you mean "lead"?` — and would have refused the second next.
259//!
260//! A project has no team; it has the teams it is accessible from, so the configured team
261//! reaches `accessibleTeams:{some:{key:{eqIgnoreCase:…}}}`. And a project's status is not
262//! an issue's state: the counterpart of `IssueFilter.state` is `ProjectFilter.status`,
263//! while `ProjectFilter.state` exists and is a bare `StringComparator` over something else.
264//! The two do not even share a vocabulary — a project's statuses are the workspace's,
265//! `Idea`, `Proposal`, `Planned`, `Completed` among them, where an issue's states are
266//! the team's — which is why `status_mapping` names each kind's statuses separately, and why a
267//! filter spelled in the other level's names matches nothing while being refused by nothing.
268//!
269//! **Neither of those could be caught by reading a document, and that is the general
270//! lesson.** A filter is built at runtime and handed over as `$filter`, so it appears in no
271//! operation this crate declares, and the two pinned-schema checks that parse those
272//! operations could not see it — Linear was the only reader, one refusal per round trip.
273//! `every_variables_object_this_source_sends_conforms_to_the_pinned_schema` closes that:
274//! it drives this source's whole surface, records what really went out, and walks every
275//! variables object against the pinned type of the argument it stands at.
276//!
277//! ## Ruling: a Linear project relation is always an ordering
278//!
279//! This one is Linear's too, and the validator says so in as many words. Asked on
280//! 2026-09-04 for a project relation typed `related` — and separately `blocks` and
281//! `dependsOn` — the real API refused each with `Argument Validation Error` and
282//! `constraints: {"isEnum": "type must be one of the following values: dependency"}`. That
283//! enumeration has one member and it is a timeline dependency, which is why the input
284//! carries an anchor at each end at all.
285//!
286//! So a project edge carrying no ordering has nowhere here to land, and this source
287//! **refuses it by name** before the write rather than sending a value Linear will reject
288//! or quietly promoting it to a dependency it does not mean. `DependencyKind::Related`
289//! keeps its issue-level spelling, `related`, because `IssueRelationCreateInput` really
290//! does take it: the two relations are different relations with different vocabularies,
291//! and each level's read accepts only its own.
292//!
293//! Which end of a project relation waits is carried by the two anchors and not by the two
294//! id slots — measured, not reasoned, from Linear's own `ProjectFilter.hasBlockedByRelations`
295//! against relations written both ways round. `tests/fixtures/README.md` records the whole
296//! probe, and `write_relations` records why the pair this source sends is the oriented one.
297//!
298//! Caller metadata is canonical JSON in a trailing
299//! ``<!-- onetaskgraph.metadata `…` -->`` Markdown comment in the item's long form — an
300//! issue's `description`, a project's or a document's `content` — on one
301//! line with the JSON in a code span — the one spelling Linear keeps byte for byte, see the
302//! ruling above; the multi-line spelling this source wrote before is still read. The visible
303//! description is returned unchanged without that slot. Writes put the same canonical
304//! encoding back beside the visible description, and use Linear issue/project relations for
305//! same-source dependencies. Only cross-source far ends use the reserved
306//! `onetaskgraph.depends_on` metadata key.
307//!
308//! ## Ruling: a status is the name `status_mapping` gives the item's kind, and nothing else
309//!
310//! Linear has no built-in names: a team's workflow states and a workspace's project statuses
311//! are whatever the people who own them called them, and a type says nothing about which of
312//! several states of it a category means — `Todo` and `Queued` are both `unstarted`. So the
313//! source's `status_mapping` ([`StatusMapping`]) is the whole of what a status is written as
314//! and read by: a task's names are the configured team's workflow states, a project's the
315//! workspace's project statuses.
316//!
317//! **A write** of a category is the name the mapping gives the kind of the item being written —
318//! `set_task_status`, the targeted update and `write_task` for a task, so `task create` and every
319//! copy; `write_project` for a project, whose own status name plays no part. A write the mapping
320//! gives that kind no name for — a category it does not mention, one set to `null`, one a
321//! per-kind object leaves out — is refused before any request, naming the source, the kind, the
322//! category and the key to set; one whose name that kind's vocabulary does not hold is refused
323//! naming the name, after the resolution and before any mutation. Nothing falls back by type, or
324//! by the name a status was called where it came from, and a source with no mapping refuses
325//! every status write.
326//!
327//! So what a write leaves an item at is the mapped name, whatever the name it was given, and
328//! [`TaskSource::stored_status`] says so: a copy compares an item already in Linear with the
329//! status at that name, and an item whose category Linear already holds reads as unchanged.
330//!
331//! **A read** of an item at a name its kind's mapping gives is that category, under the name;
332//! every other name reads as `unknown`, under its own name, whatever its type — the review
333//! states only people write, `Triage` among them. `filter_by_status` returns exactly the items
334//! that read as each category asked for: those at the name the kind's mapping gives it, and for
335//! `unknown` every item at a name that mapping does not give at all. Each is confirmed in process
336//! as well, so a row reading as another category is never returned.
337//!
338//! ## Ruling: the resolution is read once per source instance, and a status write reads nothing
339//!
340//! A Linear key is shared by every manager of a host, so what a status write costs is counted at
341//! Linear's endpoint, and `crates/onetaskgraph-linear-e2e/budgets.yaml` holds it. A source resolves
342//! the configured team's id, its workflow states and the workspace's project statuses in one
343//! request — [`graphql::RESOLUTION`] — the first time a write or `sources fields` needs them, and
344//! holds the answer for its own lifetime: per instance, never per process, never shared between
345//! sources. Building a source sends nothing. A mapped name the held answer lacks is looked for
346//! once more in a fresh read, so one added in Linear since is found; nothing a failed call
347//! answered is held, and a write that fails while carrying a held id drops the answer, so the
348//! next reads afresh rather than sending that id again. A name `sources fields --apply` creates is
349//! added to what is held.
350//!
351//! `set_task_status`, and a targeted update naming a status and nothing else, are one
352//! `issueUpdate` and no read: [`graphql::ISSUE_UPDATE_READ`] selects the whole issue, which is
353//! what the answered status — and the engine keeping a delivered task in step — need. So writing
354//! the category an issue already reads as sends the same state again, setting `unknown` on an
355//! issue at a name the mapping does not give moves it to the mapped `unknown` name, and an issue
356//! Linear does not hold is no such task from the mutation's own refusal — `Entity not found` —
357//! rather than from a read. That spelling is the one Linear documents for its own input
358//! validation; a live run has not yet re-observed it here. A source scoped to one project is no
359//! exception: its status write goes to the issue it names wherever that issue is filed — see
360//! the scope's ruling below. A targeted update naming anything else
361//! keeps its one read of the issue: the metadata slot is merged into the description Linear
362//! holds, and writing it without that read would overwrite whatever a person wrote there since.
363//! A whole rewrite of an issue or a project reads its existing relations in its own answer
364//! ([`graphql::ISSUE_REWRITE`], [`graphql::PROJECT_REWRITE`]) rather than in a read of its own.
365//! Matching issue relations are retained, so a body edit or stored-content follow-up does not
366//! delete and recreate an unchanged dependency.
367//!
368//! ## Ruling: `sources fields --apply` creates every name the mapping needs
369//!
370//! For parity with a GitHub Projects board, whose `--apply` adds the `Status` options it lacks:
371//! `--apply` creates each name the mapping gives a task that the team lacks, as a workflow state
372//! (`workflowStateCreate`), and each name it gives a project that the workspace lacks, as a
373//! project status (`projectStatusCreate`) — a bare name in both. The type of what it creates is
374//! its category's, by this fixed table:
375//!
376//! | Category | Workflow state | Project status |
377//! | --- | --- | --- |
378//! | `backlog`, `draft` | `backlog` | `backlog` |
379//! | `todo`, `queued` | `unstarted` | `planned` |
380//! | `in-progress`, `unknown` | `started` | `started` |
381//! | `done` | `completed` | `completed` |
382//! | `cancelled` | `canceled` | `canceled` |
383//!
384//! Both create inputs also require a colour, and a project status a place in the workspace's
385//! flow, and nothing in a mapping says either: every name is created in Linear's neutral grey,
386//! `#95a2b3`, and a project status after the workspace's last. Nothing that exists is renamed, retyped or deleted, and a name present
387//! under another type is reported with its type and left as it is. A create Linear refuses stops
388//! the run, and the report names what it created before it. Whether to run it against a
389//! workspace is the operator's decision.
390//!
391//! ## Ruling: a copy asks for every origin's counterpart in one request
392//!
393//! A copy into Linear looks for the item an earlier copy made of each thing it writes, by the
394//! `onetaskgraph.origin` each item records in its metadata slot: an issue by the task query by
395//! origin, a project by [`TaskSource::query_projects_by_origin`]. Asked one at a time, a project
396//! copy of `n` tasks sent one `projects` listing, `n` `issues` queries and an `organization`
397//! read for the designator its edges are written under — every one priced against the key's
398//! hourly allowance. So [`TaskSource::read_ahead_origins_for_copy`] sends
399//! [`graphql::COUNTERPART_LOOKUPS`] first, one request per [`ORIGIN_BATCH`] origins:
400//!
401//! - **`originIssues`**, the `issues` connection narrowed to the team and project scope exactly
402//!   as one origin's own query is, and to the `or` of every origin's slot phrase — the same
403//!   phrase that query sends, so it is the union of their candidate sets. Its page is one row an
404//!   origin, at most [`MAX_PAGE_SIZE`].
405//! - **`originProjects`**, the `projects` connection narrowed to the scope alone, as the single
406//!   lookup's listing is: `ProjectFilter` has no member a slot phrase could be sent in, so every
407//!   project in scope is a candidate. Its page is the rest of one projects listing page, so the
408//!   request asks for no more rows than that page does — about 7,000 of Linear's 10,000
409//!   complexity points; see [`ORIGIN_BATCH`].
410//! - **`organization{id}`**, which [`TaskSource::designator`] then answers from for the rest of
411//!   the command, with no request of its own, and the team's workflow states and the workspace's
412//!   project statuses — the rest of [`graphql::RESOLUTION`], which the copy's first write would
413//!   read otherwise, since a copy finding nothing creates. It is held as a resolution read on
414//!   its own is, only when it read whole, and costs the projects page [`RESOLUTION_ROWS`] rows.
415//!
416//! Nothing is sent when the copy asks: the origins are held until its first lookup by origin
417//! needs one, so a copy that looks no issue or project up by its origin — a document copy among
418//! them — sends no such request, and one that does sends it as the first request before its
419//! first write. A source with no `team` holds none, as no resolution names one.
420//!
421//! Each origin's next lookup is answered from it once, every row confirmed in process exactly as
422//! that origin's own query confirms it, so the answer is the one that query would have given —
423//! every match, however many items record the origin. **An origin is never taken as having no
424//! counterpart from an incomplete answer:** a connection whose page has a next page holds no
425//! origin's answer at all, found in it or not, and each of them is sent on its own as before,
426//! paging to its end; so is an origin whose phrase cannot be sent, and one this read did not
427//! carry. What is held lives until the next mutation or [`TaskSource::end_command`], and the
428//! organization id until the end of the command. With the store's cache in front of this source
429//! it is [`graphql::COUNTERPART_LOOKUPS_CACHED`], each row carrying the token parts its listing would,
430//! so a row it answers reads exactly as that listing's row does. A document copy keeps its own
431//! `documents` lookup.
432//!
433//! ## Ruling: a copy finds what it wrote by id when no listing shows it
434//!
435//! Linear's filtered and searched reads — the `issues` search of a description a lookup by
436//! origin sends, and the `projects` and `documents` listings — were observed on `TES2` to miss
437//! records written moments before, and records a repeat a minute earlier had found. A copy whose
438//! source records no link found its counterparts only through them, so it created a plan a
439//! second time. So no lookup by origin answers "none" from a listing alone:
440//!
441//! - **A create carrying an origin and no create key is sent under that origin's key's ids**
442//!   ([`LinearSource::create_id`]): the store's own create key for a create replacing no link,
443//!   `<origin>|<this source's name>|` under its published namespace, so a create that recorded
444//!   an intent and one that could not land under the same id.
445//! - **A lookup by origin that lists nothing reads that id** — and each later generation past one
446//!   holding another origin's record — by id, which Linear answers the moment a record is
447//!   written. A task's lookup, a project's and a document's alike, a document copy's reference
448//!   resolution among them.
449//! - **A create refused because a record holds its id reads that record**, and one recording the
450//!   create's origin refuses the create naming it, creating nothing: the counterpart the lookup
451//!   did not reach, behind a trashed record. Any other refusal is the create's answer, as it was.
452//!
453//! The cost is one read by id per record a copy creates, before its create; a lookup that lists
454//! its counterpart sends nothing more. Linear refuses operation batching, an id naming nothing
455//! fails a whole aliased query, and an `id:{in:…}` filter is a filtered read, so none of them
456//! can stand in for it.
457//!
458//! ## Ruling: `project` scopes a source to one project
459//!
460//! With `project` set, every issue read carries `project:{id:{eq:…}}` beside the team, a
461//! project read carries `id:{eq:…}` and a document read the same project, and a read by id
462//! of anything filed elsewhere answers as no such item — so a content, a metadata or a comment
463//! write to it, each of which reads the item first, is answered the same way.
464//!
465//! **A status-only write is the exception, and goes to the item it names wherever that item is
466//! filed.** `task status set`, and a targeted update naming a status and nothing else, are one
467//! `issueUpdate` to the issue named, with no read before it — so a scoped source meets the same
468//! request budgets as an unscoped one — and answer the issue as it now reads, even when it is
469//! filed in another project of the team. Linear has no update conditional on where an issue is
470//! filed, so holding a status write to the scope would cost the read the budget refuses; the
471//! item was named outright, and the scope is what this source reads, lists and creates rather
472//! than where a status it is asked to set may land. Reads, listings and creation stay scoped: a
473//! task or a document written with no project is placed in that one, and one naming another is
474//! refused naming both. A project write other than to that project itself is refused before any
475//! request: a project this source created would be one none of its reads could find.
476//!
477//! ## Ruling: a narrow metadata write moves only the slot, and a task carries delivery
478//!
479//! `set_task_metadata`, `set_project_metadata` and `set_document_metadata` read the item and
480//! send one update of its long-form field — `description`, `description` and `content` —
481//! that differs from what Linear holds only inside the trailing metadata slot: every byte
482//! above it is kept as it was. A key already holding the value sends nothing. The answer is
483//! the item read back. `set_task_rendering` and `set_document_rendering` replace the content
484//! and the slot's `onetaskgraph.template` entry together in one such update, every other slot
485//! entry kept; this source keeps no template answers. So a copy's `onetaskgraph.copies` link
486//! is recorded on a Linear item rather than reported unrecorded.
487//!
488//! A task's `delivers` and `delivered_by` live in that same slot under
489//! `onetaskgraph.delivers` and `onetaskgraph.delivered_by`, each a list of qualified ids,
490//! with the shape and the rules the GitHub Projects plugin keeps: neither may name the task
491//! itself or name one task twice, which is refused by name before anything is sent; a write
492//! lands the typed lists in place of any caller metadata of those names; and
493//! `set_delivered_by` is one update of the slot. A project or a document naming either key is
494//! refused, because only a task delivers or is delivered.
495//!
496//! ## Ruling: a priority is Linear's own, and content shares a field with the slot
497//!
498//! A task's priority is `Issue.priority`, on Linear's scale: `0` none, `1` urgent, `2` high,
499//! `3` normal — this contract's `medium` — and `4` low. Linear declares the field `Float!`
500//! while `IssueCreateInput.priority` and `IssueUpdateInput.priority` are `Int`, so a read
501//! accepts `2` and `2.0` alike and refuses anything that is not one of the five as a
502//! malformed response naming the field. A copy sends it on a create and on an update, `0`
503//! included, so a task moved back to no priority is not left holding its old one.
504//! `set_task_priority` reads the issue first — no such issue, or a trashed one, is `None`
505//! with nothing written — then sends `issueUpdate` with `priority` alone and answers with
506//! the priority the mutation's own payload reports.
507//!
508//! `set_task_content` sends `issueUpdate` with `description` alone, and that description is
509//! the given content followed by the issue's metadata slot exactly as it was stored, so the
510//! slot, and every key in it, is untouched. What a later read reports as the content is the
511//! given bytes, trailing whitespace included: a read of an issue carrying a slot takes off only
512//! the one blank line that sets the slot off, and a write whose content would not read back as
513//! itself is refused before it is sent.
514//!
515//! Fixture provenance is recorded in `tests/fixtures/README.md`. The live journey in
516//! `tests/live.rs` drives every field of the table above against Linear itself: it builds its own fixture
517//! on the scratch team `LINEAR_WRITE_TEAM` names — two projects, one issue filed under
518//! each, one filed under neither, two labels and two workflow states — because that shape
519//! is what tells an honoured predicate from an ignored one, and a workspace where every
520//! issue carries the label answers a filter the same way either way. Everything the lane
521//! creates it deletes whether its assertions passed or failed, and it clears residue named
522//! the way it names its own before it starts. A failed live cleanup is reported as a test
523//! failure and may require manual deletion from that scratch team.
524#![deny(missing_docs)]
525
526/// The image upload mechanism: one `fileUpload` and one storage PUT per new image.
527pub mod assets;
528use chrono::{DateTime, Utc};
529use onetaskgraph_plugin_api::{
530    Capabilities, Classification, Comment, CommentBody, CommentOrigin, Cursor, DependencyEdge,
531    DependencyEndpoint, DependencyKind, DependencySupport, Designator, Direction, Document,
532    DocumentQuery, Health, ItemKind, ItemWrite, Label, LabelFilter, Location, MetadataKey,
533    MetadataRecord, NativeId, NewComment, Page, PageRequest, Priority, Project, ProjectFilter,
534    ProjectQuery, Repository, SecretResolver, SourceError, SourceName, SourcePlugin, Status,
535    StatusCategory, StatusMapping, StatusName, Support, Task, TaskDetailRead, TaskQuery, TaskRef,
536    TaskSource, TaskUpdate, TaskUpdateOutcome, TextFields, TextQuery, UpdatedField, WriteSupport,
537};
538use schemars::{Schema, schema_for};
539use secrecy::{ExposeSecret, SecretString};
540use serde::Deserialize;
541use serde_json::{Value, json};
542
543/// A transport error with every cause beneath it: reqwest's own message stops at "error sending
544/// request", and what the connection actually met — refused, reset, a local port it could not
545/// take — is only in its sources.
546pub(crate) fn with_causes(error: &(dyn std::error::Error + 'static)) -> String {
547    let mut message = error.to_string();
548    let mut cause = error.source();
549    while let Some(next) = cause {
550        let said = next.to_string();
551        if !message.ends_with(&said) {
552            message.push_str(": ");
553            message.push_str(&said);
554        }
555        cause = next.source();
556    }
557    message
558}
559
560pub mod change_token;
561pub mod headings;
562/// Ownership prefix for Linear live-test artifacts and scheduled orphan recovery.
563pub const LIVE_ARTIFACT_TITLE_PREFIX: &str = "onetaskgraph live cleanup ";
564
565/// Exact ownership grammar shared by live lanes and their cleanup.
566pub mod live_artifact;
567
568mod batch;
569mod origins;
570mod relations;
571mod shared;
572
573/// The plugin kind a `linear` source's `plugin:` field names.
574pub const KIND: &str = "linear";
575
576/// The largest page this source will ask Linear for, and the capability it declares.
577///
578/// **Not Linear's connection maximum, which is 250, because a connection maximum is not
579/// the only thing bounding a page.** Linear also scores each document for complexity and
580/// refuses one over 10000 with HTTP 400 and `The query is too complex.` — and the
581/// `projects` document this source sends scores 17475 at `first: 250`, because its nested
582/// `labels` connection, which names no `first` of its own, is charged Linear's default of
583/// 50 per node. Measured against the real API on 2026-09-04: the largest `first` that
584/// document is accepted at is **143**, exactly, and the filter it carries adds nothing.
585/// The `issues` document is accepted at 250, so this is the tighter of the two and a
586/// single declared maximum has to be the tighter one.
587///
588/// 100 rather than 143 because 143 is the cliff. A field added to either selection moves
589/// it, and a page size chosen at the edge of a budget nobody here controls fails in the
590/// live lane rather than in a check. This leaves 30% of the budget spare.
591///
592/// Nothing offline can hold this: complexity is scored by Linear's own runtime and appears
593/// in no schema, so `every_variables_object_this_source_sends_conforms_to_the_pinned_schema`
594/// cannot see it. What guards it is the live journey, which walks a real `projects` page at
595/// exactly this size.
596pub const MAX_PAGE_SIZE: u32 = 100;
597
598/// The rows a projects listing asks for at most while the store's cache stands in front of this
599/// source.
600///
601/// Linear prices `projects` by the rows a request asks for: 70 a row plain, 95 with the relations
602/// page a project's token is read from (`spike-linear-coverage`, about 9,491 at 100 rows), and,
603/// taking the inverse relations page at the relations page's 25, 120 with both. Seventy-four rows
604/// price at 8,880, under the `linear-cache-largest-query-complexity` guard of 9,000; a listing of
605/// more than seventy-four projects takes another request a page, which the hour budgets count.
606pub const PROJECTS_CACHED_PAGE: u32 = 74;
607
608/// The most origins one [`graphql::COUNTERPART_LOOKUPS`] request asks for: a copy naming more sends
609/// one such request per this many.
610///
611/// The issues page that request asks for is one row an origin, and the projects page the rest
612/// of one projects listing page — [`MAX_PAGE_SIZE`], or [`PROJECTS_CACHED_PAGE`] while the
613/// store's cache stands in front of this source — so the request asks for no more rows than one
614/// listing page does, and a projects row is the dearer: about 7,000 of Linear's 10,000
615/// complexity points at the 70 a row a projects listing is priced at, and under 8,880 with the
616/// cache's pages at 120, however many origins it carries.
617pub const ORIGIN_BATCH: usize = 50;
618
619/// The projects rows [`graphql::COUNTERPART_LOOKUPS`] gives up to the vocabulary resolution it carries
620/// beside its listings — [`graphql::RESOLUTION`]'s `teams` and `projectStatuses`, priced at
621/// about 2,053 of Linear's complexity points, or some thirty projects rows at 70 each — so the
622/// request still asks for no more than one listing page does.
623pub const RESOLUTION_ROWS: u32 = 30;
624const DEFAULT_ENDPOINT: &str = "https://api.linear.app/graphql";
625
626/// Exact GraphQL query documents issued by this plugin.
627///
628/// Fixture servers consume these constants so their recognized contract cannot drift
629/// from the production requests.
630pub mod graphql {
631    /// Request Linear's signed upload URL, private asset URL, and required PUT headers.
632    pub const FILE_UPLOAD: &str = "mutation AssetUpload($contentType:String!,$filename:String!,$size:Int!){fileUpload(contentType:$contentType,filename:$filename,size:$size){success uploadFile{uploadUrl assetUrl headers{key value}}}}";
633
634    /// Linear's missing-issue error, reconciled with the service by the live status journey.
635    pub const ISSUE_NOT_FOUND_MESSAGE: &str = "Entity not found: Issue";
636    /// Its user-facing alternative; the loopback fixture shares this contract.
637    pub const ISSUE_NOT_FOUND_PRESENTABLE: &str = "Could not find referenced Issue.";
638    /// The same error for a project a mutation addresses: Linear spells every missing entity
639    /// `Entity not found: <type>`. Reconciled with the service by the live capability journey,
640    /// which sends a project status write to a nonexistent project and requires `None`; the
641    /// loopback fixture shares this contract.
642    pub const PROJECT_NOT_FOUND_MESSAGE: &str = "Entity not found: Project";
643    /// Its user-facing alternative, on the terms of [`ISSUE_NOT_FOUND_PRESENTABLE`].
644    pub const PROJECT_NOT_FOUND_PRESENTABLE: &str = "Could not find referenced Project.";
645    /// The same error for a document a read addresses, on the terms of
646    /// [`PROJECT_NOT_FOUND_MESSAGE`]. Reconciled with the service by the live project-create
647    /// journey of `onetaskgraph-linear-e2e`, which reads a document id Linear does not hold and
648    /// requires it absent; the loopback fixture shares this contract.
649    pub const DOCUMENT_NOT_FOUND_MESSAGE: &str = "Entity not found: Document";
650    /// Its user-facing alternative, on the terms of [`ISSUE_NOT_FOUND_PRESENTABLE`].
651    pub const DOCUMENT_NOT_FOUND_PRESENTABLE: &str = "Could not find referenced Document.";
652    /// Linear's refusal of a page asked for `after` (or `before`) a cursor it cannot find, as the
653    /// live capability journey met it on 2026-11-11 (run 43027479734) — `cursor not found`, whose
654    /// `userPresentableMessage` reads `Could not find cursor '<cursor>'.` — partway through a walk
655    /// in pages of one over issues that run had just created, the cursor being the last of them.
656    /// A cursor is the id of the row it follows, so a replica that does not hold that row yet
657    /// cannot place it. The loopback of `tests/absent_and_refused.rs` answers with these two.
658    pub const CURSOR_NOT_FOUND_MESSAGE: &str = "cursor not found";
659    /// Its user-facing alternative, up to the cursor it names.
660    pub const CURSOR_NOT_FOUND_PRESENTABLE: &str = "Could not find cursor";
661    /// Linear's refusal of a `projectCreate` under an id a record already holds — a deleted
662    /// one's included — answered under HTTP 200, as the live project-create journey of
663    /// `onetaskgraph-linear-e2e` observed it on 2026-11-03 and checks, for each of the three
664    /// kinds, on every credentialed run. The loopback fixtures share this contract; nothing in
665    /// this source reads it, because a keyed create tries its next id on any refusal.
666    pub const PROJECT_ID_CONFLICT_MESSAGE: &str = "conflict on insert of Project";
667    /// [`PROJECT_ID_CONFLICT_MESSAGE`] for an `issueCreate`.
668    pub const ISSUE_ID_CONFLICT_MESSAGE: &str = "conflict on insert of Issue";
669    /// [`PROJECT_ID_CONFLICT_MESSAGE`] for a `documentCreate`.
670    pub const DOCUMENT_ID_CONFLICT_MESSAGE: &str = "conflict on insert of Document";
671
672    /// [`PROJECT_ID_CONFLICT_MESSAGE`] or its counterpart for `record`'s create.
673    #[must_use]
674    pub fn id_conflict_message(record: super::MetadataRecord) -> &'static str {
675        match record {
676            super::MetadataRecord::Task => ISSUE_ID_CONFLICT_MESSAGE,
677            super::MetadataRecord::Project => PROJECT_ID_CONFLICT_MESSAGE,
678            super::MetadataRecord::Document => DOCUMENT_ID_CONFLICT_MESSAGE,
679        }
680    }
681
682    /// The `userPresentableMessage` beside [`id_conflict_message`], for `record`'s create sent
683    /// under `id`.
684    #[must_use]
685    pub fn id_conflict_presentable(record: super::MetadataRecord, id: &str) -> String {
686        let kind = match record {
687            super::MetadataRecord::Task => "Issue",
688            super::MetadataRecord::Project => "Project",
689            super::MetadataRecord::Document => "Document",
690        };
691        format!("Entity {kind} with id {id} already exists.")
692    }
693
694    /// Check the authenticated viewer.
695    pub const VIEWER: &str = "query { viewer { id } }";
696    /// The workspace's own id, which this source's designator digests.
697    pub const ORGANIZATION: &str = "query { organization { id } }";
698    /// What a copy asks before it looks for the items copied from each of up to
699    /// [`super::ORIGIN_BATCH`] origins: [`ISSUES`]'s connection narrowed to every origin's slot
700    /// phrase under one `or`, aliased `originIssues`, [`PROJECTS`]'s connection narrowed to the
701    /// source's scope, aliased `originProjects`, and [`ORGANIZATION`]'s `organization{id}` — in
702    /// one request. See the module documentation's ruling on the requests a copy sends.
703    pub const COUNTERPART_LOOKUPS: &str = "query($issuesFirst:Int!,$issuesFilter:IssueFilter,$projectsFirst:Int!,$projectsFilter:ProjectFilter,$key:String!){ originIssues: issues(first:$issuesFirst,filter:$issuesFilter){ nodes{id identifier title description descriptionState url createdAt updatedAt state{name type} priority labels{nodes{id name color}} project{id}} pageInfo{hasNextPage endCursor} } originProjects: projects(first:$projectsFirst,filter:$projectsFilter){ nodes{id name content url createdAt updatedAt status{name type} labels{nodes{id name color}}} pageInfo{hasNextPage endCursor} } organization{ id } teams(first:2,filter:{key:{eqIgnoreCase:$key}}){nodes{id states(first:250){nodes{id name type} pageInfo{hasNextPage}}}} projectStatuses(first:250){nodes{id name type position} pageInfo{hasNextPage}} }";
704    /// [`COUNTERPART_LOOKUPS`], sent in its place while the store's cache stands in front of this
705    /// source: each connection's rows carry what [`ISSUES_CACHED`]'s and [`PROJECTS_CACHED`]'s
706    /// carry, so a row it answers is pinned to the token a listing of it spells.
707    pub const COUNTERPART_LOOKUPS_CACHED: &str = "query($issuesFirst:Int!,$issuesFilter:IssueFilter,$projectsFirst:Int!,$projectsFilter:ProjectFilter,$key:String!){ originIssues: issues(first:$issuesFirst,filter:$issuesFilter){ nodes{id identifier title description descriptionState url createdAt updatedAt state{name type} priority labels{nodes{id name color}} project{id} comments(first:10){nodes{id updatedAt} pageInfo{hasNextPage}} relations(first:10){nodes{id type relatedIssue{id}} pageInfo{hasNextPage}} inverseRelations(first:10){nodes{id type issue{id}} pageInfo{hasNextPage}}} pageInfo{hasNextPage endCursor} } originProjects: projects(first:$projectsFirst,filter:$projectsFilter){ nodes{id name content url createdAt updatedAt status{name type} labels{nodes{id name color}} relations(first:10){nodes{id type relatedProject{id}} pageInfo{hasNextPage}} inverseRelations(first:10){nodes{id type project{id}} pageInfo{hasNextPage}}} pageInfo{hasNextPage endCursor} } organization{ id } teams(first:2,filter:{key:{eqIgnoreCase:$key}}){nodes{id states(first:250){nodes{id name type} pageInfo{hasNextPage}}}} projectStatuses(first:250){nodes{id name type position} pageInfo{hasNextPage}} }";
708    /// Fetch one issue.
709    pub const ISSUE: &str = "query($id:String!){ issue(id:$id){ id identifier title description descriptionState url createdAt updatedAt archivedAt state{name type} priority labels{nodes{id name color}} project{id} } }";
710    /// Fetch one project.
711    pub const PROJECT: &str = "query($id:String!){ project(id:$id){ id name content contentState url createdAt updatedAt archivedAt status{name type} labels{nodes{id name color}} } }";
712    /// List issues.
713    pub const ISSUES: &str = "query($first:Int!,$after:String,$filter:IssueFilter){ issues(first:$first,after:$after,filter:$filter){ nodes{id identifier title description descriptionState url createdAt updatedAt state{name type} priority labels{nodes{id name color}} project{id}} pageInfo{hasNextPage endCursor} } }";
714    /// List projects.
715    pub const PROJECTS: &str = "query($first:Int!,$after:String,$filter:ProjectFilter){ projects(first:$first,after:$after,filter:$filter){ nodes{id name content url createdAt updatedAt status{name type} labels{nodes{id name color}}} pageInfo{hasNextPage endCursor} } }";
716    /// List issue labels.
717    pub const LABELS: &str = "query($first:Int,$after:String){ issueLabels(first:$first,after:$after){ nodes{id name color} pageInfo{hasNextPage endCursor} } }";
718    /// Fetch issue dependency relations.
719    pub const ISSUE_RELATIONS: &str = "query($id:String!,$first:Int!,$after:String){ issue(id:$id){ description relations(first:$first,after:$after){nodes{id type relatedIssue{id}} pageInfo{hasNextPage endCursor}} inverseRelations(first:$first,after:$after){nodes{id type issue{id}} pageInfo{hasNextPage endCursor}} } }";
720    /// Fetch project dependency relations.
721    pub const PROJECT_RELATIONS: &str = "query($id:String!,$first:Int!,$after:String){ project(id:$id){ content relations(first:$first,after:$after){nodes{id type relatedProject{id}} pageInfo{hasNextPage endCursor}} inverseRelations(first:$first,after:$after){nodes{id type project{id}} pageInfo{hasNextPage endCursor}} } }";
722    /// What one issue depends on: [`ISSUE_RELATIONS`] without its `inverseRelations`, so a
723    /// dependency read asks Linear for the one direction it answers. The `description` rides
724    /// along because its metadata slot is where an edge to another source is recorded, so
725    /// those edges cost no second request.
726    pub const ISSUE_DEPENDS_ON: &str = "query($id:String!,$first:Int!,$after:String){ issue(id:$id){ description relations(first:$first,after:$after){nodes{id type relatedIssue{id}} pageInfo{hasNextPage endCursor}} } }";
727    /// What depends on one issue: [`ISSUE_RELATIONS`] with its `inverseRelations` alone. The
728    /// `description` is read for its links alone — never for a recorded edge, whose reverse is
729    /// derived from the far end — so a `related` relation mirroring a link is told from a
730    /// `related` dependency at no request of its own.
731    pub const ISSUE_DEPENDED_ON_BY: &str = "query($id:String!,$first:Int!,$after:String){ issue(id:$id){ description inverseRelations(first:$first,after:$after){nodes{id type issue{id}} pageInfo{hasNextPage endCursor}} } }";
732    /// What one project depends on, on the terms of [`ISSUE_DEPENDS_ON`].
733    pub const PROJECT_DEPENDS_ON: &str = "query($id:String!,$first:Int!,$after:String){ project(id:$id){ content relations(first:$first,after:$after){nodes{id type relatedProject{id}} pageInfo{hasNextPage endCursor}} } }";
734    /// What depends on one project, on the terms of [`ISSUE_DEPENDED_ON_BY`].
735    pub const PROJECT_DEPENDED_ON_BY: &str = "query($id:String!,$first:Int!,$after:String){ project(id:$id){ inverseRelations(first:$first,after:$after){nodes{id type project{id}} pageInfo{hasNextPage endCursor}} } }";
736    /// Everything a status write resolves, in one request: the configured team's id, that
737    /// team's workflow states, and the workspace's project statuses, each with its type.
738    ///
739    /// One document rather than three lookups, because a status write's cost is counted at
740    /// Linear's endpoint on a key every manager of a workspace shares: a source sends this once
741    /// and holds the answer for its own lifetime (see the ruling on the resolution cache in this
742    /// crate's module documentation). `Team.states` and `Query.projectStatuses` are each read
743    /// as one page of Linear's connection maximum, 250, and refused rather than read short when
744    /// either says it has more — a team holds a few dozen states at most, and a workspace a
745    /// few dozen project statuses, so a resolution that does not fit one page is not one this
746    /// source guesses at — and `projectStatuses` takes no `filter`: Linear refuses one outright with `Unknown argument "filter" on field
747    /// "Query.projectStatuses"`, which is why a project status is matched by name here, locally.
748    /// `position` is read for one reason: a project status `sources fields --apply` creates is
749    /// placed after the workspace's last.
750    ///
751    /// `teams` is read at `first:2` and never at Linear's default page of 50, because Linear
752    /// scores a connection's selection once per node its page may hold: at the default, the 250
753    /// states asked of each of fifty possible teams scored this document 30905 against Linear's
754    /// limit of 10000, and the live journey's first status write was refused `Query too complex`.
755    /// Two rather than one so a key matching more than one team is still seen, and refused, by
756    /// the exactly-one rule that reads this answer. `states` and `projectStatuses` stay at 250,
757    /// whole or refused, as above: a name a page cut off would read as missing.
758    ///
759    /// Under Linear's documented model — a property 0.1, an object 1, and a connection's
760    /// children multiplied by its `first`, or 50 without one — the refused document scores
761    /// 50 × (1 + 0.1 + 250 × (1.3 + 1.1)) + 250 × (1.4 + 1.1) = 30680, and this one
762    /// 2 × 601.1 + 625 = 1827.2. Linear's own figures run 225 above the model on both
763    /// documents it has reported here (30905 for the refused one, 17475 for [`PROJECTS`] at
764    /// 250), and one point more for every node of every connection at every depth — 752 here —
765    /// still leaves this under 2580, about a quarter of the limit. Like [`super::MAX_PAGE_SIZE`],
766    /// nothing offline can hold this — complexity appears in no schema — and the live journey
767    /// is what guards it.
768    ///
769    /// `organization{id}` is the workspace this credential belongs to, read in the same request
770    /// rather than in one of its own: it is what a source declared private is verified
771    /// against, once per instance, and a cold write already sends this. It adds one object
772    /// and one property — 1.1 points by the model above — to the document's score.
773    pub const RESOLUTION: &str = "query($key:String!){ organization{id} teams(first:2,filter:{key:{eqIgnoreCase:$key}}){nodes{id states(first:250){nodes{id name type} pageInfo{hasNextPage}}}} projectStatuses(first:250){nodes{id name type position} pageInfo{hasNextPage}} }";
774    /// [`ISSUE`] and [`RESOLUTION`] in one request: what an update naming a status reads its
775    /// issue with while this instance holds no resolution yet, so a fresh source's settlement
776    /// costs its read and its mutation and no lookup between them.
777    pub const ISSUE_RESOLVED: &str = "query($id:String!,$key:String!){ issue(id:$id){ id identifier title description descriptionState url createdAt updatedAt archivedAt state{name type} priority labels{nodes{id name color}} project{id} } organization{id} teams(first:2,filter:{key:{eqIgnoreCase:$key}}){nodes{id states(first:250){nodes{id name type} pageInfo{hasNextPage}}}} projectStatuses(first:250){nodes{id name type position} pageInfo{hasNextPage}} }";
778    /// Create a workflow state on the configured team, for `sources fields --apply`.
779    pub const WORKFLOW_STATE_CREATE: &str = "mutation($input:WorkflowStateCreateInput!){ workflowStateCreate(input:$input){success workflowState{id name type}} }";
780    /// Create a workspace project status, for `sources fields --apply`.
781    pub const PROJECT_STATUS_CREATE: &str = "mutation($input:ProjectStatusCreateInput!){ projectStatusCreate(input:$input){success status{id name type position}} }";
782    /// Resolve an issue-label display name.
783    pub const ISSUE_LABEL: &str =
784        "query($name:String!){ issueLabels(filter:{name:{eqIgnoreCase:$name}}){nodes{id}} }";
785    /// Resolve a project-label display name.
786    pub const PROJECT_LABEL: &str =
787        "query($name:String!){ projectLabels(filter:{name:{eqIgnoreCase:$name}}){nodes{id}} }";
788    /// Create an issue.
789    pub const ISSUE_CREATE: &str = "mutation($input:IssueCreateInput!){ issueCreate(input:$input){success issue{ id identifier title description descriptionState url createdAt updatedAt archivedAt state{name type} priority labels{nodes{id name color}} project{id} }} }";
790    /// Update an issue and read back, in the same request, everything a task is read as: the
791    /// selection is [`ISSUE`]'s, so what a write of the description alone answers is what a read
792    /// of the issue a moment later answers, and nothing is read after it.
793    pub const ISSUE_UPDATE: &str = "mutation($id:String!,$input:IssueUpdateInput!){ issueUpdate(id:$id,input:$input){success issue{ id identifier title description descriptionState url createdAt updatedAt archivedAt state{name type} priority labels{nodes{id name color}} project{id} }} }";
794    /// [`ISSUE_UPDATE`], by the name a status write and a targeted update send it under.
795    ///
796    /// What they answer with: the selection is [`ISSUE`]'s, so the task they report — its
797    /// status, and the `delivers` the engine keeps in step with it — is what Linear holds after
798    /// the write, with no read before it and none after.
799    pub const ISSUE_UPDATE_READ: &str = ISSUE_UPDATE;
800    /// Set an issue's priority on its own, and read back the issue as Linear now holds it.
801    ///
802    /// The same `issueUpdate` as [`ISSUE_UPDATE`], selecting what a read of the issue selects
803    /// and `priority` once more, as 0.6.0's priority write did, because a narrow priority write answers with what the source reads back rather
804    /// than an echo of what it sent — and with the issue's token, so the write answers what the
805    /// task holds after it without a read. A document of its own, spelled apart from
806    /// [`ISSUE_UPDATE`], so a request log tells a priority write from every other update.
807    pub const ISSUE_PRIORITY_UPDATE: &str = "mutation($id:String!,$input:IssueUpdateInput!){ issueUpdate(id:$id,input:$input){success issue{ id identifier title description descriptionState url createdAt updatedAt archivedAt state{name type} priority labels{nodes{id name color}} project{id} priority}} }";
808    /// Rewrite an issue whole, and read back in the same request the first page of the
809    /// relations it holds — the ones a whole write reconciles.
810    ///
811    /// A whole write of an existing item reconciles its relations with the ones it was
812    /// given, so it has to know which it holds; selected here, that is the update's own answer
813    /// rather than a read of its own, and a re-write with no relations to replace is the one
814    /// request. The relations are read after the update, which moves none of them.
815    pub const ISSUE_REWRITE: &str = "mutation($id:String!,$input:IssueUpdateInput!,$first:Int!){ issueUpdate(id:$id,input:$input){success issue{ id identifier title description descriptionState url createdAt updatedAt archivedAt state{name type} priority labels{nodes{id name color}} project{id} relations(first:$first){nodes{id type relatedIssue{id}} pageInfo{hasNextPage endCursor}}}} }";
816    /// Rewrite a project whole, and read back the first page of its relations, on the terms of
817    /// [`ISSUE_REWRITE`].
818    pub const PROJECT_REWRITE: &str = "mutation($id:String!,$input:ProjectUpdateInput!,$first:Int!){ projectUpdate(id:$id,input:$input){success project{ id name content contentState url createdAt updatedAt archivedAt status{name type} labels{nodes{id name color}} relations(first:$first){nodes{id type relatedProject{id}} pageInfo{hasNextPage endCursor}}}} }";
819    /// Create a project.
820    pub const PROJECT_CREATE: &str = "mutation($input:ProjectCreateInput!){ projectCreate(input:$input){success project{ id name content contentState url createdAt updatedAt archivedAt status{name type} labels{nodes{id name color}} }} }";
821    /// Update a project — its long form alone, by a metadata or rendering write — reading back in
822    /// the same request everything a project is read as, so a metadata write answers the project
823    /// its own answer selected and a follow-up write reads nothing after the write before it.
824    pub const PROJECT_UPDATE: &str = "mutation($id:String!,$input:ProjectUpdateInput!){ projectUpdate(id:$id,input:$input){success project{ id name content contentState url createdAt updatedAt archivedAt status{name type} labels{nodes{id name color}} }} }";
825    /// Set one project's status alone — its input carries `statusId` and nothing else — and
826    /// read back the status it then holds.
827    pub const PROJECT_STATUS_UPDATE: &str = "mutation($id:String!,$input:ProjectUpdateInput!){ projectUpdate(id:$id,input:$input){success project{id status{name type}}} }";
828    /// Create a native issue dependency.
829    pub const ISSUE_RELATION_CREATE: &str = "mutation($input:IssueRelationCreateInput!){ issueRelationCreate(input:$input){success issueRelation{id}} }";
830    /// Create a native project dependency.
831    pub const PROJECT_RELATION_CREATE: &str = "mutation($input:ProjectRelationCreateInput!){ projectRelationCreate(input:$input){success projectRelation{id}} }";
832    /// Delete a native issue dependency before replacing its full edge set.
833    pub const ISSUE_RELATION_DELETE: &str =
834        "mutation($id:String!){ issueRelationDelete(id:$id){success} }";
835    /// Delete a native project dependency before replacing its full edge set.
836    pub const PROJECT_RELATION_DELETE: &str =
837        "mutation($id:String!){ projectRelationDelete(id:$id){success} }";
838    /// Delete an issue, so a copy that could not finish can take back what it created.
839    pub const ISSUE_DELETE: &str = "mutation($id:String!){ issueDelete(id:$id){success} }";
840    /// Delete a project, for the same reason and on the same terms.
841    pub const PROJECT_DELETE: &str = "mutation($id:String!){ projectDelete(id:$id){success} }";
842    /// Fetch one document.
843    pub const DOCUMENT: &str = "query($id:String!){ document(id:$id){ id title content contentState url createdAt updatedAt archivedAt project{id} } }";
844    /// List documents.
845    ///
846    /// `first` is an `Int` rather than an `Int!` because that is what Linear's `documents`
847    /// connection declares, unlike its `issues` one.
848    pub const DOCUMENTS: &str = "query($first:Int,$after:String,$filter:DocumentFilter){ documents(first:$first,after:$after,filter:$filter){ nodes{id title content contentState url createdAt updatedAt project{id}} pageInfo{hasNextPage endCursor} } }";
849    /// Create a document.
850    pub const DOCUMENT_CREATE: &str = "mutation($input:DocumentCreateInput!){ documentCreate(input:$input){success document{ id title content contentState url createdAt updatedAt archivedAt project{id} }} }";
851    /// Update a document, reading back in the same request everything a document is read as, on
852    /// the terms of [`PROJECT_UPDATE`].
853    pub const DOCUMENT_UPDATE: &str = "mutation($id:String!,$input:DocumentUpdateInput!){ documentUpdate(id:$id,input:$input){success document{ id title content contentState url createdAt updatedAt archivedAt project{id} }} }";
854    /// Delete a document, so a copy that could not finish can take back what it created.
855    pub const DOCUMENT_DELETE: &str = "mutation($id:String!){ documentDelete(id:$id){success} }";
856    /// One page of an issue's comments, walked backwards.
857    ///
858    /// `last`/`before` rather than `first`/`after`, and `pageInfo{hasPreviousPage
859    /// startCursor}` rather than its forward pair, because Linear lists a connection newest
860    /// first and the contract owes the oldest first — see the ruling on comments in this
861    /// crate's module documentation. `archivedAt` is selected for the reason every by-id read
862    /// here selects it: a trashed issue is not an issue this source holds.
863    pub const ISSUE_COMMENTS: &str = "query($id:String!,$last:Int,$before:String){ issue(id:$id){ archivedAt comments(last:$last,before:$before){ nodes{id body url createdAt updatedAt user{displayName}} pageInfo{hasPreviousPage startCursor} } } }";
864    /// One issue and one page of its comments, in one request: [`ISSUE`]'s selection and
865    /// [`ISSUE_COMMENTS`]'s connection on one `issue(id:)` field.
866    ///
867    /// What a copy reads a task with when it carries its comments: one request answers both
868    /// where the comments fit one page, and every further page through this same read carries
869    /// the issue beside it, so the copy can tell the issue changed between two of them.
870    pub const ISSUE_DETAIL: &str = "query($id:String!,$last:Int,$before:String){ issue(id:$id){ id identifier title description descriptionState url createdAt updatedAt archivedAt state{name type} priority labels{nodes{id name color}} project{id} comments(last:$last,before:$before){ nodes{id body url createdAt updatedAt user{displayName}} pageInfo{hasPreviousPage startCursor} } } }";
871    /// The first page of an issue's relations a `lin1` token's relations part is spelled from:
872    /// one of what [`ISSUES_CACHED`], [`ISSUE_CACHED`] and [`ISSUE_DETAIL_CACHED`] add to the
873    /// documents they stand in for.
874    pub const RELATIONS_PAGE: &str =
875        "relations(first:10){nodes{id type relatedIssue{id}} pageInfo{hasNextPage}}";
876    /// The first page of an issue's inverse relations — what depends on it — a `lin1` token's
877    /// inverse part is spelled from, added beside [`RELATIONS_PAGE`].
878    pub const INVERSE_RELATIONS_PAGE: &str =
879        "inverseRelations(first:10){nodes{id type issue{id}} pageInfo{hasNextPage}}";
880    /// The first page of an issue's comments, each its id and when it last changed, a `lin1`
881    /// token's comments part is spelled from: what [`ISSUES_CACHED`], [`ISSUE_CACHED`] and
882    /// [`ISSUE_RELATIONS_CACHED`] add for it. [`ISSUE_DETAIL_CACHED`] spells it from the comments
883    /// page it already reads.
884    pub const COMMENTS_PAGE: &str = "comments(first:10){nodes{id updatedAt} pageInfo{hasNextPage}}";
885    /// The first page of a project's relations a project's `lin1` token's relations part is
886    /// spelled from: one of what [`PROJECTS_CACHED`] and [`PROJECT_CACHED`] add.
887    pub const PROJECT_RELATIONS_PAGE: &str =
888        "relations(first:10){nodes{id type relatedProject{id}} pageInfo{hasNextPage}}";
889    /// The first page of a project's inverse relations — what depends on it — a project's
890    /// `lin1` token's inverse part is spelled from, added beside [`PROJECT_RELATIONS_PAGE`].
891    pub const PROJECT_INVERSE_RELATIONS_PAGE: &str =
892        "inverseRelations(first:10){nodes{id type project{id}} pageInfo{hasNextPage}}";
893    /// What [`ISSUE_RELATIONS_CACHED`] adds to [`ISSUE_RELATIONS`]: every part of a task's
894    /// `lin1` token beside the two relations pages that document already reads, and nothing
895    /// else.
896    pub const TOKEN_PARTS: &str = "updatedAt identifier url state{name type} labels{nodes{id name color}} project{id} comments(first:10){nodes{id updatedAt} pageInfo{hasNextPage}}";
897    /// What [`PROJECT_RELATIONS_CACHED`] adds to [`PROJECT_RELATIONS`]: every part of a
898    /// project's `lin1` token beside the relations page that document already reads.
899    pub const PROJECT_TOKEN_PARTS: &str =
900        "updatedAt status{name type} labels{nodes{id name color}}";
901    /// [`ISSUES`], sent in its place while the store's cache stands in front of this source:
902    /// with [`COMMENTS_PAGE`], [`RELATIONS_PAGE`] and [`INVERSE_RELATIONS_PAGE`], so a listing
903    /// pins each task to the token a read of it fills.
904    pub const ISSUES_CACHED: &str = "query($first:Int!,$after:String,$filter:IssueFilter){ issues(first:$first,after:$after,filter:$filter){ nodes{id identifier title description descriptionState url createdAt updatedAt state{name type} priority labels{nodes{id name color}} project{id} comments(first:10){nodes{id updatedAt} pageInfo{hasNextPage}} relations(first:10){nodes{id type relatedIssue{id}} pageInfo{hasNextPage}} inverseRelations(first:10){nodes{id type issue{id}} pageInfo{hasNextPage}}} pageInfo{hasNextPage endCursor} } }";
905    /// [`ISSUE`], sent in its place while the store's cache stands in front of this source.
906    pub const ISSUE_CACHED: &str = "query($id:String!){ issue(id:$id){ id identifier title description descriptionState url createdAt updatedAt archivedAt state{name type} priority labels{nodes{id name color}} project{id} comments(first:10){nodes{id updatedAt} pageInfo{hasNextPage}} relations(first:10){nodes{id type relatedIssue{id}} pageInfo{hasNextPage}} inverseRelations(first:10){nodes{id type issue{id}} pageInfo{hasNextPage}} } }";
907    /// [`ISSUE_DETAIL`], sent in its place while the store's cache stands in front of this
908    /// source: its comments part is spelled from the comments page it already reads.
909    pub const ISSUE_DETAIL_CACHED: &str = "query($id:String!,$last:Int,$before:String){ issue(id:$id){ id identifier title description descriptionState url createdAt updatedAt archivedAt state{name type} priority labels{nodes{id name color}} project{id} relations(first:10){nodes{id type relatedIssue{id}} pageInfo{hasNextPage}} inverseRelations(first:10){nodes{id type issue{id}} pageInfo{hasNextPage}} comments(last:$last,before:$before){ nodes{id body url createdAt updatedAt user{displayName}} pageInfo{hasPreviousPage startCursor} } } }";
910    /// [`ISSUE_RELATIONS`], sent in its place while the store's cache stands in front of this
911    /// source: with [`TOKEN_PARTS`], so a dependency read in either direction spells the token
912    /// its edges are kept at.
913    pub const ISSUE_RELATIONS_CACHED: &str = "query($id:String!,$first:Int!,$after:String){ issue(id:$id){ updatedAt identifier url state{name type} labels{nodes{id name color}} project{id} comments(first:10){nodes{id updatedAt} pageInfo{hasNextPage}} description relations(first:$first,after:$after){nodes{id type relatedIssue{id}} pageInfo{hasNextPage endCursor}} inverseRelations(first:$first,after:$after){nodes{id type issue{id}} pageInfo{hasNextPage endCursor}} } }";
914    /// [`PROJECTS`], sent in its place while the store's cache stands in front of this source:
915    /// with [`PROJECT_RELATIONS_PAGE`] and [`PROJECT_INVERSE_RELATIONS_PAGE`], so a listing pins
916    /// each project to the token its edges are kept at. Sent at most
917    /// [`super::PROJECTS_CACHED_PAGE`] rows a page.
918    pub const PROJECTS_CACHED: &str = "query($first:Int!,$after:String,$filter:ProjectFilter){ projects(first:$first,after:$after,filter:$filter){ nodes{id name content url createdAt updatedAt status{name type} labels{nodes{id name color}} relations(first:10){nodes{id type relatedProject{id}} pageInfo{hasNextPage}} inverseRelations(first:10){nodes{id type project{id}} pageInfo{hasNextPage}}} pageInfo{hasNextPage endCursor} } }";
919    /// [`PROJECT`], sent in its place while the store's cache stands in front of this source.
920    pub const PROJECT_CACHED: &str = "query($id:String!){ project(id:$id){ id name content contentState url createdAt updatedAt archivedAt status{name type} labels{nodes{id name color}} relations(first:10){nodes{id type relatedProject{id}} pageInfo{hasNextPage}} inverseRelations(first:10){nodes{id type project{id}} pageInfo{hasNextPage}} } }";
921    /// [`PROJECT_RELATIONS`], sent in its place while the store's cache stands in front of this
922    /// source: with [`PROJECT_TOKEN_PARTS`], so a dependency read in either direction spells the
923    /// token its edges are kept at.
924    pub const PROJECT_RELATIONS_CACHED: &str = "query($id:String!,$first:Int!,$after:String){ project(id:$id){ updatedAt status{name type} labels{nodes{id name color}} content relations(first:$first,after:$after){nodes{id type relatedProject{id}} pageInfo{hasNextPage endCursor}} inverseRelations(first:$first,after:$after){nodes{id type project{id}} pageInfo{hasNextPage endCursor}} } }";
925    /// Place one comment: which issue it is on, if any.
926    ///
927    /// `$id` is a nullable `String` because that is what `Query.comment` declares — it also
928    /// takes a `hash` instead — and a variable has to be exactly its argument's type.
929    pub const COMMENT: &str =
930        "query($id:String){ comment(id:$id){ id body archivedAt issue{id} } }";
931    /// Add a comment to an issue.
932    pub const COMMENT_CREATE: &str = "mutation($input:CommentCreateInput!){ commentCreate(input:$input){success comment{id body url createdAt updatedAt user{displayName}}} }";
933    /// Replace a comment's body.
934    pub const COMMENT_UPDATE: &str = "mutation($id:String!,$input:CommentUpdateInput!){ commentUpdate(id:$id,input:$input){success comment{id body url createdAt updatedAt user{displayName}}} }";
935    /// Remove a comment.
936    pub const COMMENT_DELETE: &str = "mutation($id:String!){ commentDelete(id:$id){success} }";
937
938    /// [`ISSUE_RELATIONS`] with the issue's own `id`, as a mirrored link's removal reads the
939    /// relations of its `from`: every alias's answer is held to the issue it asked for, so an
940    /// answer about another issue never names a relation to delete.
941    pub const ISSUE_LINK_RELATIONS: &str = "query($id:String!,$first:Int!,$after:String){ issue(id:$id){ id relations(first:$first,after:$after){nodes{id type relatedIssue{id}} pageInfo{hasNextPage endCursor}} inverseRelations(first:$first,after:$after){nodes{id type issue{id}} pageInfo{hasNextPage endCursor}} } }";
942
943    /// One issue as a relation read reads it: the task, its parent and a first page of its
944    /// children — and nothing else, because the selection is what moves a read's complexity.
945    pub const ISSUE_PARENT_READ: &str = "query($id:String!){ issue(id:$id){ id identifier title description url createdAt updatedAt archivedAt state{name type} priority labels{nodes{id name color}} project{id} parent{id} children(first:50){nodes{id} pageInfo{hasNextPage}} } }";
946    /// Set or remove one issue's parent — `parentId: null` removes it — reading the issue back.
947    pub const ISSUE_PARENT_UPDATE: &str = "mutation($id:String!,$input:IssueUpdateInput!){ issueUpdate(id:$id,input:$input){success issue{ id identifier title description descriptionState url createdAt updatedAt archivedAt state{name type} priority labels{nodes{id name color}} project{id} parent{id} }} }";
948
949    /// The documents this source sends batched by [`composed`], each the single-root document it
950    /// batches.
951    pub const BATCHED: [&str; 17] = [
952        ISSUE_CREATE,
953        ISSUE_LABEL,
954        PROJECT_LABEL,
955        ISSUE_RELATION_CREATE,
956        ISSUE,
957        ISSUES,
958        ISSUE_UPDATE_READ,
959        COMMENT_CREATE,
960        ISSUE_DETAIL,
961        ISSUE_DEPENDS_ON,
962        PROJECT,
963        PROJECT_DEPENDS_ON,
964        DOCUMENT,
965        ISSUE_PARENT_READ,
966        ISSUE_PARENT_UPDATE,
967        ISSUE_LINK_RELATIONS,
968        ISSUE_RELATION_DELETE,
969    ];
970
971    /// `single` — a document of one root field, as this source sends it alone — `count` times
972    /// in one document, as [`composed`] composes it.
973    #[must_use]
974    pub fn aliased(single: &str, count: usize) -> String {
975        composed(&vec![single; count])
976    }
977
978    /// The documents `singles` — each of one root field, as this source sends it alone, all
979    /// queries or all mutations — in one document: the `i`th aliased `a<i>`, each of its
980    /// variables `$<name>` renamed `$<name>_<i>`.
981    ///
982    /// What batches many reads, or many writes, into one request. Linear executes each aliased
983    /// field as it would the document alone, and answers it under its alias; a field it refuses
984    /// is answered with an error whose `path` starts at that alias, and — every root this source
985    /// batches being non-null — with no `data` at all. A document of mutations is applied whole
986    /// or not at all: one refused alias leaves every other unapplied, as measured against a
987    /// sandbox team on 2026-11-11.
988    #[must_use]
989    pub fn composed(singles: &[&str]) -> String {
990        let mut kind = "query";
991        let mut declared = Vec::with_capacity(singles.len());
992        let mut fields = Vec::with_capacity(singles.len());
993        for (at, single) in singles.iter().enumerate() {
994            let (head, body) = parts(single);
995            let (operation, variables) = head
996                .split_once('(')
997                .map_or((head.trim(), ""), |(operation, rest)| {
998                    (operation.trim(), rest.trim_end().trim_end_matches(')'))
999                });
1000            kind = operation;
1001            if !variables.is_empty() {
1002                declared.push(suffixed(variables, at));
1003            }
1004            fields.push(format!("a{at}: {}", suffixed(body, at)));
1005        }
1006        if declared.is_empty() {
1007            format!("{kind}{{ {} }}", fields.join(" "))
1008        } else {
1009            format!("{kind}({}){{ {} }}", declared.join(","), fields.join(" "))
1010        }
1011    }
1012
1013    /// A single-root document split into what comes before its selection and the selection's
1014    /// one root field.
1015    fn parts(single: &str) -> (&str, &str) {
1016        let (head, body) = single.split_once('{').unwrap_or((single, ""));
1017        (
1018            head,
1019            body.trim_end().strip_suffix('}').unwrap_or(body).trim(),
1020        )
1021    }
1022
1023    /// The documents of [`BATCHED`] `document` composes, in order, when it is one [`composed`]
1024    /// spells — what a server answering it answers each alias as.
1025    #[must_use]
1026    pub fn decomposed(document: &str) -> Option<Vec<&'static str>> {
1027        let count = (0..)
1028            .take_while(|at| document.contains(&format!(" a{at}: ")))
1029            .count();
1030        if count == 0 {
1031            return None;
1032        }
1033        let mut singles = Vec::with_capacity(count);
1034        for at in 0..count {
1035            let single = BATCHED.into_iter().find(|single| {
1036                document.contains(&format!("a{at}: {}", suffixed(parts(single).1, at)))
1037            })?;
1038            singles.push(single);
1039        }
1040        (composed(&singles) == document).then_some(singles)
1041    }
1042
1043    /// Every `$name` in `text` renamed `$name_<at>`.
1044    fn suffixed(text: &str, at: usize) -> String {
1045        let mut renamed = String::with_capacity(text.len() + 8);
1046        let mut chars = text.chars().peekable();
1047        while let Some(character) = chars.next() {
1048            renamed.push(character);
1049            if character != '$' {
1050                continue;
1051            }
1052            while let Some(next) = chars.peek().copied() {
1053                if next.is_ascii_alphanumeric() || next == '_' {
1054                    renamed.push(next);
1055                    chars.next();
1056                } else {
1057                    break;
1058                }
1059            }
1060            renamed.push_str(&format!("_{at}"));
1061        }
1062        renamed
1063    }
1064
1065    /// The variables of an [`aliased`] document: each item's own, each name suffixed `_<i>`.
1066    #[must_use]
1067    pub fn aliased_variables(each: &[serde_json::Value]) -> serde_json::Value {
1068        let mut merged = serde_json::Map::new();
1069        for (at, variables) in each.iter().enumerate() {
1070            for (name, value) in variables.as_object().into_iter().flatten() {
1071                merged.insert(format!("{name}_{at}"), value.clone());
1072            }
1073        }
1074        serde_json::Value::Object(merged)
1075    }
1076
1077    /// The single document [`aliased`] batched `document` repeats and how many times, when it is
1078    /// one.
1079    #[must_use]
1080    pub fn unaliased(document: &str) -> Option<(&'static str, usize)> {
1081        let singles = decomposed(document)?;
1082        let first = *singles.first()?;
1083        singles
1084            .iter()
1085            .all(|single| *single == first)
1086            .then_some((first, singles.len()))
1087    }
1088
1089    /// The variables of the `at`th item of an [`aliased`] document, as its single document
1090    /// takes them.
1091    #[must_use]
1092    pub fn alias_variables(variables: &serde_json::Value, at: usize) -> serde_json::Value {
1093        let suffix = format!("_{at}");
1094        serde_json::Value::Object(
1095            variables
1096                .as_object()
1097                .into_iter()
1098                .flatten()
1099                .filter_map(|(name, value)| {
1100                    name.strip_suffix(&suffix)
1101                        .map(|plain| (plain.to_owned(), value.clone()))
1102                })
1103                .collect(),
1104        )
1105    }
1106}
1107
1108use graphql::{
1109    DOCUMENT, DOCUMENTS, ISSUE, ISSUE_RELATIONS, ISSUES, LABELS, PROJECT, PROJECT_RELATIONS,
1110    PROJECTS, VIEWER,
1111};
1112
1113/// One `linear` source's configuration.
1114///
1115/// It names the credential's environment variable, never its value. Serializable so the
1116/// schema it is published under carries each member's default, which is what a configuration
1117/// that leaves the member out means.
1118#[derive(Debug, Clone, Deserialize, serde::Serialize, schemars::JsonSchema)]
1119#[serde(default, deny_unknown_fields)]
1120pub struct LinearConfig {
1121    /// Environment variable resolved by the host.
1122    #[schemars(with = "String")]
1123    api_key_env: EnvName,
1124    /// Linear team key/id used to narrow reads and required for item writes.
1125    team: Option<Team>,
1126    /// GraphQL endpoint override, primarily for fixture servers.
1127    #[schemars(with = "String")]
1128    endpoint: Endpoint,
1129    /// Which workflow state of the configured team a task's status category is, and which of
1130    /// the workspace's project statuses a project's is — the shared `status_mapping` grammar.
1131    ///
1132    /// Linear has no built-in names, so this is the whole of what a status is written as and
1133    /// read by: a category is written as exactly the name its kind maps it to, and a status
1134    /// write it gives no name for is refused before any mutation, naming the key to set; an
1135    /// item at a name its kind maps reads as that category under the name, and every other
1136    /// name reads as `unknown`. A source without it reads every item as `unknown` and refuses
1137    /// every status write. Two categories mapped to one name of one kind are refused when this
1138    /// configuration is read.
1139    status_mapping: StatusMapping,
1140    /// The id of one Linear project of the configured team, scoping this source to it.
1141    ///
1142    /// When set, every task read is narrowed to that project's issues, project and document
1143    /// reads return only that project and its documents, a task or a document written with
1144    /// no project is placed in it, and one naming another project is refused. Absent, the
1145    /// source reads and writes team-wide.
1146    project: Option<ProjectScope>,
1147    /// The link types this source mirrors as Linear's own `related` issue relation, each as
1148    /// `<type>: {"native": "related"}` — the one word a Linear source mirrors a link as. A type
1149    /// not named here is kept in the store's metadata alone.
1150    link_types: std::collections::BTreeMap<String, onetaskgraph_plugin_api::LinkTypeConfig>,
1151}
1152
1153/// The id of one Linear project, which a scoped source holds alone.
1154#[derive(Debug, Clone, Deserialize, serde::Serialize, schemars::JsonSchema)]
1155#[serde(try_from = "String", into = "String")]
1156#[schemars(rename = "LinearProjectId", extend("minLength" = 1))]
1157struct ProjectScope(String);
1158impl From<ProjectScope> for String {
1159    fn from(value: ProjectScope) -> Self {
1160        value.0
1161    }
1162}
1163impl TryFrom<String> for ProjectScope {
1164    type Error = String;
1165    fn try_from(value: String) -> Result<Self, Self::Error> {
1166        if value.trim().is_empty() {
1167            Err("a project id cannot be blank".into())
1168        } else {
1169            Ok(Self(value))
1170        }
1171    }
1172}
1173
1174#[derive(Debug, Clone, Deserialize, serde::Serialize)]
1175#[serde(try_from = "String", into = "String")]
1176struct EnvName(String);
1177impl From<EnvName> for String {
1178    fn from(value: EnvName) -> Self {
1179        value.0
1180    }
1181}
1182impl TryFrom<String> for EnvName {
1183    type Error = String;
1184    fn try_from(value: String) -> Result<Self, Self::Error> {
1185        let mut bytes = value.bytes();
1186        if bytes
1187            .next()
1188            .is_some_and(|byte| byte == b'_' || byte.is_ascii_uppercase())
1189            && bytes.all(|byte| byte == b'_' || byte.is_ascii_uppercase() || byte.is_ascii_digit())
1190        {
1191            Ok(Self(value))
1192        } else {
1193            Err("must be an uppercase environment-variable name".into())
1194        }
1195    }
1196}
1197/// A Linear team's key or id.
1198#[derive(Debug, Clone, PartialEq, Eq, Deserialize, serde::Serialize, schemars::JsonSchema)]
1199#[serde(try_from = "String", into = "String")]
1200#[schemars(rename = "LinearTeam", extend("minLength" = 1))]
1201struct Team(String);
1202impl From<Team> for String {
1203    fn from(value: Team) -> Self {
1204        value.0
1205    }
1206}
1207impl TryFrom<String> for Team {
1208    type Error = String;
1209    fn try_from(value: String) -> Result<Self, Self::Error> {
1210        if value.trim().is_empty() {
1211            Err("must not be empty".into())
1212        } else {
1213            Ok(Self(value))
1214        }
1215    }
1216}
1217#[derive(Debug, Clone, Deserialize, serde::Serialize)]
1218#[serde(try_from = "String", into = "String")]
1219struct Endpoint(String);
1220impl From<Endpoint> for String {
1221    fn from(value: Endpoint) -> Self {
1222        value.0
1223    }
1224}
1225impl TryFrom<String> for Endpoint {
1226    type Error = String;
1227    fn try_from(value: String) -> Result<Self, Self::Error> {
1228        let url = reqwest::Url::parse(&value).map_err(|e| e.to_string())?;
1229        if matches!(url.scheme(), "http" | "https") {
1230            Ok(Self(value))
1231        } else {
1232            Err("must use http or https".into())
1233        }
1234    }
1235}
1236
1237impl Default for LinearConfig {
1238    fn default() -> Self {
1239        Self {
1240            api_key_env: EnvName("LINEAR_API_KEY".into()),
1241            team: None,
1242            endpoint: Endpoint(DEFAULT_ENDPOINT.into()),
1243            status_mapping: StatusMapping::default(),
1244            project: None,
1245            link_types: std::collections::BTreeMap::new(),
1246        }
1247    }
1248}
1249
1250/// An item kind as this source's configuration and reports spell it.
1251const fn kind_word(kind: ItemKind) -> &'static str {
1252    match kind {
1253        ItemKind::Task => "task",
1254        ItemKind::Project => "project",
1255    }
1256}
1257
1258/// What a name of `kind` is called in Linear, for a message.
1259const fn vocabulary_word(kind: ItemKind) -> &'static str {
1260    match kind {
1261        ItemKind::Task => "workflow state",
1262        ItemKind::Project => "project status",
1263    }
1264}
1265
1266/// A `WorkflowState.type` a workflow state `sources fields --apply` creates is given — the five
1267/// Linear's `WorkflowStateCreateInput.type` documents taking.
1268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1269enum CreatedStateType {
1270    Backlog,
1271    Unstarted,
1272    Started,
1273    Completed,
1274    Canceled,
1275}
1276
1277impl CreatedStateType {
1278    /// The type as Linear spells it.
1279    const fn as_str(self) -> &'static str {
1280        match self {
1281            Self::Backlog => "backlog",
1282            Self::Unstarted => "unstarted",
1283            Self::Started => "started",
1284            Self::Completed => "completed",
1285            Self::Canceled => "canceled",
1286        }
1287    }
1288}
1289
1290/// A `ProjectStatusType` a project status `sources fields --apply` creates is given — a member
1291/// of that enum, which `paused` is too and which nothing here creates.
1292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1293enum CreatedStatusType {
1294    Backlog,
1295    Planned,
1296    Started,
1297    Completed,
1298    Canceled,
1299}
1300
1301impl CreatedStatusType {
1302    /// The type as Linear spells it.
1303    const fn as_str(self) -> &'static str {
1304        match self {
1305            Self::Backlog => "backlog",
1306            Self::Planned => "planned",
1307            Self::Started => "started",
1308            Self::Completed => "completed",
1309            Self::Canceled => "canceled",
1310        }
1311    }
1312}
1313
1314/// The `WorkflowState.type` a workflow state `sources fields --apply` creates for `category`
1315/// is given, and the `ProjectStatusType` a project status it creates is given.
1316///
1317/// One row per category, fixed: a category is created as the type whose meaning is nearest
1318/// it, and `draft`, `queued` and `unknown` — which no type of either vocabulary means — as the
1319/// nearest neighbour's. An exhaustive match, so a category the contract adds fails to compile
1320/// here rather than being created as something unstated.
1321const fn created_types(category: StatusCategory) -> (CreatedStateType, CreatedStatusType) {
1322    match category {
1323        StatusCategory::Backlog | StatusCategory::Draft => {
1324            (CreatedStateType::Backlog, CreatedStatusType::Backlog)
1325        }
1326        StatusCategory::Todo | StatusCategory::Queued => {
1327            (CreatedStateType::Unstarted, CreatedStatusType::Planned)
1328        }
1329        StatusCategory::InProgress | StatusCategory::Unknown => {
1330            (CreatedStateType::Started, CreatedStatusType::Started)
1331        }
1332        StatusCategory::Done => (CreatedStateType::Completed, CreatedStatusType::Completed),
1333        StatusCategory::Cancelled => (CreatedStateType::Canceled, CreatedStatusType::Canceled),
1334    }
1335}
1336
1337/// The type, as Linear spells it, a name of `kind` that `sources fields --apply` creates for
1338/// `category` is given.
1339const fn created_type(category: StatusCategory, kind: ItemKind) -> &'static str {
1340    let (state, status) = created_types(category);
1341    match kind {
1342        ItemKind::Task => state.as_str(),
1343        ItemKind::Project => status.as_str(),
1344    }
1345}
1346
1347/// The colour every workflow state and project status `sources fields --apply` creates is
1348/// given: Linear's own neutral grey, because both create inputs require one and nothing in a
1349/// status mapping says which colour a name should be. A person recolours it in Linear.
1350const CREATED_COLOR: &str = "#95a2b3";
1351
1352/// One workflow state of the configured team, or one project status of the workspace.
1353#[derive(Debug, Clone)]
1354struct Held {
1355    id: NativeId,
1356    name: StatusName,
1357    /// Its `WorkflowState.type` or `ProjectStatusType`, verbatim: Linear adds types this
1358    /// source must not refuse (`duplicate` among them).
1359    // llmlint: ignore[invalid_states_unrepresentable] Linear's own open `String!` vocabulary, held verbatim for a report; an enum here would refuse a type Linear adds.
1360    kind: String,
1361}
1362
1363impl Held {
1364    /// One workflow state or project status, as Linear answered it.
1365    fn read(node: &Value) -> Result<Self, SourceError> {
1366        Ok(Self {
1367            id: NativeId(backend_id(node, "id")?.into()),
1368            name: held_name(node)?,
1369            kind: str_at(node, "type")?.to_owned(),
1370        })
1371    }
1372}
1373
1374/// A project status's place in the workspace's project flow, as Linear answered it.
1375fn position_of(node: &Value) -> Result<f64, SourceError> {
1376    node.get("position")
1377        .and_then(Value::as_f64)
1378        .ok_or_else(|| SourceError::Malformed {
1379            message: "missing number field position".into(),
1380        })
1381}
1382
1383/// One name `sources fields --apply` created, as Linear answered its create.
1384#[derive(Debug, Clone)]
1385enum Created {
1386    /// A workflow state of the team.
1387    State(Held),
1388    /// A project status of the workspace, at its place in the workspace's project flow.
1389    Status { held: Held, position: f64 },
1390}
1391
1392impl Created {
1393    fn held(&self) -> &Held {
1394        match self {
1395            Self::State(held) | Self::Status { held, .. } => held,
1396        }
1397    }
1398}
1399
1400/// The name of one workflow state or project status Linear answered with, which no name in
1401/// Linear is blank.
1402fn held_name(node: &Value) -> Result<StatusName, SourceError> {
1403    StatusName::try_from(str_at(node, "name")?.to_owned()).map_err(|refused| {
1404        SourceError::Malformed {
1405            message: format!("Linear answered a status name this source cannot hold: {refused}"),
1406        }
1407    })
1408}
1409
1410/// What a status write resolves: the configured team's id, its workflow states and the
1411/// workspace's project statuses.
1412///
1413/// Read in one request and held by one source instance for its own lifetime — never by the
1414/// process, never shared between sources, and kept across [`TaskSource::end_command`] — so
1415/// every status write after the first sends its mutation alone. A name not found in it is
1416/// looked for once more in a fresh read, so a name added in Linear after it was read is found;
1417/// nothing a failed call answered is held.
1418#[derive(Debug, Clone)]
1419struct Vocabulary {
1420    /// The workspace the credential reached, which is what makes a declaration of this
1421    /// source as private one that has been verified rather than taken on trust — `None` when
1422    /// the answer named none, which verifies nothing and resolves everything else as before.
1423    workspace: Option<NativeId>,
1424    team: NativeId,
1425    states: Vec<Held>,
1426    statuses: Vec<Held>,
1427    /// Where the workspace's project flow ends: the greatest `position` among its project
1428    /// statuses, zero when it holds none. A project status `sources fields --apply` creates is
1429    /// placed after it.
1430    last_position: f64,
1431}
1432
1433impl Vocabulary {
1434    fn read(data: &Value, source: &SourceName, team: &str) -> Result<Self, SourceError> {
1435        let teams = data
1436            .pointer("/teams/nodes")
1437            .and_then(Value::as_array)
1438            .ok_or_else(|| SourceError::Malformed {
1439                message: "missing teams.nodes".into(),
1440            })?;
1441        let found = match teams.as_slice() {
1442            [found] => found,
1443            other => {
1444                return Err(SourceError::Refused {
1445                    message: format!(
1446                        "source {source} cannot resolve the configured team {team:?}: found {} \
1447                         matches; next: set team to the key of exactly one team this \
1448                         credential can see",
1449                        other.len()
1450                    ),
1451                });
1452            }
1453        };
1454        let nodes = |pointer: &str| {
1455            data.pointer(pointer)
1456                .and_then(Value::as_array)
1457                .ok_or_else(|| SourceError::Malformed {
1458                    message: format!(
1459                        "missing {}",
1460                        pointer.trim_start_matches('/').replace('/', ".")
1461                    ),
1462                })
1463        };
1464        let team = NativeId(backend_id(found, "id")?.into());
1465        let workspace = data
1466            .get("organization")
1467            .filter(|organization| !organization.is_null())
1468            .map(|organization| backend_id(organization, "id").map(|id| NativeId(id.into())))
1469            .transpose()?;
1470        // Read whole or not at all: a name on a page this did not read would be refused as
1471        // missing, or a second name of that spelling would go unseen.
1472        for (more, held) in [
1473            (
1474                "/teams/nodes/0/states/pageInfo/hasNextPage",
1475                "workflow states of its team",
1476            ),
1477            (
1478                "/projectStatuses/pageInfo/hasNextPage",
1479                "project statuses of its workspace",
1480            ),
1481        ] {
1482            let more = data.pointer(more).and_then(Value::as_bool).ok_or_else(|| {
1483                SourceError::Malformed {
1484                    message: format!(
1485                        "missing boolean {}",
1486                        more.trim_start_matches('/').replace('/', ".")
1487                    ),
1488                }
1489            })?;
1490            if more {
1491                return Err(SourceError::Refused {
1492                    message: format!(
1493                        "source {source} reads the {held} in one page of 250, and Linear holds \
1494                         more; next: archive the ones no longer used, so the rest fit one page"
1495                    ),
1496                });
1497            }
1498        }
1499        let statuses = nodes("/projectStatuses/nodes")?;
1500        Ok(Self {
1501            workspace,
1502            team,
1503            states: nodes("/teams/nodes/0/states/nodes")?
1504                .iter()
1505                .map(Held::read)
1506                .collect::<Result<_, _>>()?,
1507            statuses: statuses.iter().map(Held::read).collect::<Result<_, _>>()?,
1508            last_position: statuses
1509                .iter()
1510                .map(position_of)
1511                .try_fold(0.0_f64, |last, position| Ok(last.max(position?)))?,
1512        })
1513    }
1514
1515    /// Hold one name `sources fields --apply` created beside the ones read.
1516    fn add(&mut self, created: Created) {
1517        match created {
1518            Created::State(held) => self.states.push(held),
1519            Created::Status { held, position } => {
1520                self.statuses.push(held);
1521                self.last_position = self.last_position.max(position);
1522            }
1523        }
1524    }
1525
1526    fn of(&self, kind: ItemKind) -> &[Held] {
1527        match kind {
1528            ItemKind::Task => &self.states,
1529            ItemKind::Project => &self.statuses,
1530        }
1531    }
1532
1533    /// The one name of `kind` matching `name` ignoring case, `None` when there is none, and a
1534    /// refusal naming every id when there are several: a write must not guess between them.
1535    fn find(
1536        &self,
1537        kind: ItemKind,
1538        name: &str,
1539        source: &SourceName,
1540    ) -> Result<Option<&Held>, SourceError> {
1541        let matched = self
1542            .of(kind)
1543            .iter()
1544            .filter(|held| held.name.matches(name))
1545            .collect::<Vec<_>>();
1546        match matched.as_slice() {
1547            [] => Ok(None),
1548            [held] => Ok(Some(held)),
1549            several => Err(SourceError::Refused {
1550                message: format!(
1551                    "source {source} cannot resolve {} {name:?}: found {} matches with ids {:?}",
1552                    vocabulary_word(kind),
1553                    several.len(),
1554                    several
1555                        .iter()
1556                        .map(|held| held.id.0.as_str())
1557                        .collect::<Vec<_>>()
1558                ),
1559            }),
1560        }
1561    }
1562}
1563
1564/// The Linear plugin factory.
1565#[derive(Debug, Clone, Copy, Default)]
1566pub struct Plugin;
1567
1568impl SourcePlugin for Plugin {
1569    fn kind(&self) -> &'static str {
1570        KIND
1571    }
1572    /// The endpoint and the team: what names the Linear work a source reads.
1573    fn remote_identity(&self, config: &serde_json::Value) -> Option<String> {
1574        let config: LinearConfig = serde_json::from_value(config.clone()).ok()?;
1575        Some(format!(
1576            "{}\n{}",
1577            config.endpoint.0,
1578            config.team.map(|team| team.0).unwrap_or_default()
1579        ))
1580    }
1581    fn config_schema(&self) -> Schema {
1582        schema_for!(LinearConfig)
1583    }
1584    fn build(
1585        &self,
1586        name: &SourceName,
1587        config: &Value,
1588        secrets: &dyn SecretResolver,
1589    ) -> Result<Box<dyn TaskSource>, SourceError> {
1590        self.build_with_clock(
1591            name,
1592            config,
1593            secrets,
1594            onetaskgraph_plugin_api::system_clock(),
1595        )
1596    }
1597    fn build_with_clock(
1598        &self,
1599        name: &SourceName,
1600        config: &Value,
1601        secrets: &dyn SecretResolver,
1602        clock: onetaskgraph_plugin_api::SharedClock,
1603    ) -> Result<Box<dyn TaskSource>, SourceError> {
1604        let config: LinearConfig =
1605            serde_json::from_value(config.clone()).map_err(|e| SourceError::Config {
1606                message: format!("source {name}: {e}"),
1607            })?;
1608        let mut source = LinearSource::new(name, config, secrets)?;
1609        source.clock = clock;
1610        Ok(Box::new(source))
1611    }
1612}
1613
1614/// What `onetaskgraph sources fields` reports for a `linear` source: every name its
1615/// `status_mapping` gives a task, checked against the configured team's workflow states, and
1616/// every name it gives a project, checked against the workspace's project statuses.
1617///
1618/// With `--apply`, each name a kind's vocabulary lacks is created first — a workflow state on
1619/// the team, a project status in the workspace — of the type its category derives (see the
1620/// crate's ruling on `sources fields --apply`), and the report names what it created. Nothing that exists is renamed,
1621/// retyped or deleted. A create Linear refuses stops the run: [`Self::refused`] names it, and
1622/// every name created before it is reported created.
1623#[derive(Debug, Clone, PartialEq, serde::Serialize, schemars::JsonSchema)]
1624pub struct StatusNamesReport {
1625    /// The configured source name.
1626    pub source: SourceName,
1627    /// The configured team, as `team` names it.
1628    team: Team,
1629    /// Every name `status_mapping` gives a task, then every name it gives a project, each in
1630    /// category order. A bare name is reported once for each kind. Empty when it names none.
1631    pub names: Vec<MappedStatusName>,
1632    /// The create Linear refused, which stopped an `--apply`; absent when nothing was refused.
1633    #[serde(skip_serializing_if = "Option::is_none")]
1634    pub refused: Option<RefusedCreate>,
1635}
1636
1637impl StatusNamesReport {
1638    /// The configured team, as `team` names it.
1639    #[must_use]
1640    pub fn team(&self) -> &str {
1641        &self.team.0
1642    }
1643}
1644
1645/// A name `sources fields --apply` could not create, and why.
1646#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, schemars::JsonSchema)]
1647pub struct RefusedCreate {
1648    /// Whether it was a workflow state (`task`) or a project status (`project`).
1649    pub kind: ItemKind,
1650    /// The name it would have created.
1651    pub name: StatusName,
1652    /// What Linear said.
1653    pub message: String,
1654}
1655
1656/// One name a `status_mapping` gives one kind, and whether that kind's vocabulary has it.
1657#[derive(Debug, Clone, PartialEq)]
1658pub struct MappedStatusName {
1659    kind: ItemKind,
1660    category: StatusCategory,
1661    name: StatusName,
1662    found: Found,
1663}
1664
1665/// Whether a kind's vocabulary has a name of the one the mapping gives, and whether this run
1666/// put it there.
1667#[derive(Debug, Clone, PartialEq, Eq)]
1668pub enum Found {
1669    /// It has it, of this type — a `WorkflowState.type` (`backlog`, `unstarted`, `started`,
1670    /// `completed`, `canceled`, `triage`, …) or a `ProjectStatusType` (`backlog`, `planned`,
1671    /// `started`, `paused`, `completed`, `canceled`) — reported verbatim because Linear adds
1672    /// types this report must not refuse.
1673    // llmlint: ignore[invalid_states_unrepresentable] Linear's own open `String!` vocabulary, reported verbatim; an enum here would refuse a type Linear adds, which a report must not.
1674    Present(String),
1675    /// It has no name of that spelling.
1676    Missing,
1677    /// It had none, and `sources fields --apply` created it, of this type.
1678    // llmlint: ignore[invalid_states_unrepresentable] As `Present`: Linear's own open `String!` vocabulary, reported verbatim as Linear answered the create.
1679    Created(String),
1680}
1681
1682impl MappedStatusName {
1683    /// Whether the name is a task's workflow state or a project's project status.
1684    #[must_use]
1685    pub fn kind(&self) -> ItemKind {
1686        self.kind
1687    }
1688
1689    /// The category the mapping sends to the name.
1690    #[must_use]
1691    pub fn category(&self) -> StatusCategory {
1692        self.category
1693    }
1694
1695    /// The name, as the mapping spells it.
1696    #[must_use]
1697    pub fn name(&self) -> &str {
1698        self.name.as_str()
1699    }
1700
1701    /// Whether the vocabulary has it, and of which type.
1702    #[must_use]
1703    pub fn found(&self) -> &Found {
1704        &self.found
1705    }
1706
1707    /// Whether this run created it.
1708    #[must_use]
1709    pub fn created(&self) -> bool {
1710        matches!(self.found, Found::Created(_))
1711    }
1712
1713    /// The type a name of this category is created as — what a present name of another type
1714    /// differs from.
1715    #[must_use]
1716    pub fn expected_type(&self) -> &'static str {
1717        created_type(self.category, self.kind)
1718    }
1719}
1720
1721/// [`MappedStatusName`] as it is written: `present`, and the name's `type` where it is.
1722///
1723/// The wire shape of the report, spelled once for its serialization and its schema, so the
1724/// public type can hold only the combinations [`Found`] allows.
1725#[derive(serde::Serialize, schemars::JsonSchema)]
1726#[schemars(rename = "MappedStatusName")]
1727struct MappedStatusNameWire<'a> {
1728    /// `task` for a workflow state of the team, `project` for a project status of the workspace.
1729    kind: ItemKind,
1730    /// The category the mapping sends to the name.
1731    category: StatusCategory,
1732    /// The name, as the mapping spells it.
1733    name: &'a StatusName,
1734    /// Whether that kind's vocabulary has a name of that spelling, ignoring case.
1735    present: bool,
1736    /// The name's type in Linear — a `WorkflowState.type` for a task, a `ProjectStatusType`
1737    /// for a project — absent when it is missing.
1738    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
1739    found_type: Option<&'a str>,
1740    /// The type `--apply` creates a missing name of this category and kind as; a present name
1741    /// of another type is reported and left as it is.
1742    expected_type: &'static str,
1743    /// Whether this run created the name; absent when it did not.
1744    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1745    // Kept in the schema as `"default": false` although the JSON leaves `false` out, so both
1746    // SDKs model an absent `created` as `false` rather than as a member that must be there.
1747    #[schemars(!skip_serializing_if)]
1748    created: bool,
1749}
1750
1751impl<'a> From<&'a MappedStatusName> for MappedStatusNameWire<'a> {
1752    fn from(mapped: &'a MappedStatusName) -> Self {
1753        let found_type = match &mapped.found {
1754            Found::Present(kind) | Found::Created(kind) => Some(kind.as_str()),
1755            Found::Missing => None,
1756        };
1757        Self {
1758            kind: mapped.kind,
1759            category: mapped.category,
1760            name: &mapped.name,
1761            present: found_type.is_some(),
1762            found_type,
1763            expected_type: mapped.expected_type(),
1764            created: mapped.created(),
1765        }
1766    }
1767}
1768
1769impl serde::Serialize for MappedStatusName {
1770    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1771        MappedStatusNameWire::from(self).serialize(serializer)
1772    }
1773}
1774
1775impl schemars::JsonSchema for MappedStatusName {
1776    fn schema_name() -> std::borrow::Cow<'static, str> {
1777        MappedStatusNameWire::schema_name()
1778    }
1779
1780    fn json_schema(generator: &mut schemars::SchemaGenerator) -> Schema {
1781        MappedStatusNameWire::json_schema(generator)
1782    }
1783}
1784
1785/// Report every name one `linear` source's `status_mapping` gives each kind, as present in
1786/// that kind's vocabulary with its type or missing from it — and, with `apply`, create every
1787/// missing one first.
1788///
1789/// # Errors
1790///
1791/// [`SourceError::Config`] or [`SourceError::Auth`] for a source that cannot be built, a
1792/// refusal for one with no `team`, and whatever else Linear could not answer. A create Linear
1793/// refuses is not an error here: it is [`StatusNamesReport::refused`], beside what was created.
1794pub async fn status_names(
1795    name: &SourceName,
1796    config: LinearConfig,
1797    secrets: &dyn SecretResolver,
1798    apply: bool,
1799) -> Result<StatusNamesReport, SourceError> {
1800    LinearSource::new(name, config, secrets)?
1801        .status_names(apply)
1802        .await
1803}
1804
1805/// How many times a page Linear refused for a cursor it cannot find is read again before the
1806/// refusal is the caller's, and the pause before the first of them, doubling before each after:
1807/// 0.5, 1, 2 and 4 seconds, 7.5 in all. Only a page that names a cursor and is refused for it
1808/// waits, so no other read's requests or time change.
1809const STALE_CURSOR_REREADS: u32 = 4;
1810const STALE_CURSOR_PAUSE: std::time::Duration = std::time::Duration::from_millis(500);
1811const STALE_CURSOR_WAIT: onetaskgraph_plugin_api::WaitCause =
1812    onetaskgraph_plugin_api::WaitCause::new("linear-cursor-lag");
1813
1814/// Whether a request's variables ask for a page after (or before) a cursor, rather than a
1815/// connection's first page.
1816fn resumes_a_page(variables: &Value) -> bool {
1817    ["after", "before"]
1818        .iter()
1819        .any(|key| variables.get(key).is_some_and(Value::is_string))
1820}
1821
1822/// How long Linear's filtered reads may go on missing a comment after it was made or edited,
1823/// which a read of the comments made since an instant sets its watermark back by.
1824const COMMENT_FILTER_LAG: std::time::Duration = std::time::Duration::from_secs(60);
1825
1826struct LinearSource {
1827    clock: onetaskgraph_plugin_api::SharedClock,
1828    /// Built on the first request rather than with the source: building one loads the
1829    /// system's certificate store, tens of milliseconds a source that a command never sends to
1830    /// should not cost its process.
1831    client: std::sync::OnceLock<reqwest::Client>,
1832    endpoint: Endpoint,
1833    key: SecretString,
1834    team: Option<Team>,
1835    /// This source's configured name, kept for one comparison: a far end recorded as
1836    /// `<this name>:<native>` is a Linear item Linear itself relates, so the reserved key
1837    /// is refused for it exactly as a bare id of the same kind is.
1838    name: SourceName,
1839    /// Which name each status category is, for a task and for a project.
1840    statuses: StatusMapping,
1841    /// The one Linear project this source is scoped to, when it is.
1842    project: Option<ProjectScope>,
1843    /// What a status write resolves, once it has been read; see [`Vocabulary`].
1844    vocabulary: std::sync::Mutex<Option<std::sync::Arc<Vocabulary>>>,
1845    /// Whether the store's cache stands in front of this source — [`TaskSource::attach_cache`]
1846    /// — so its issue reads carry the relations page a `lin1` token's third part is read from.
1847    attached: std::sync::atomic::AtomicBool,
1848    /// The token the response answering the last dependency read of each item in each
1849    /// direction spelled, while that walk's pages agree on it; see
1850    /// [`TaskSource::edges_version`].
1851    edges_versions: std::sync::Mutex<std::collections::HashMap<EdgesRead, String>>,
1852    /// What the answer to this instance's latest long-form write of each item said Linear now
1853    /// stores as its content, until [`TaskSource::stored_content`] takes it; see the ruling on
1854    /// what Linear does to Markdown on write.
1855    stored: std::sync::Mutex<std::collections::HashMap<(MetadataRecord, NativeId), String>>,
1856    /// The whole item the answer to this instance's latest long-form write of it selected — the
1857    /// fields a read of it maps, which every such write selects — until a later write's own
1858    /// read of that item takes it in place of a request, another write of it lets it go, or
1859    /// [`TaskSource::end_command`]. What Linear answered a write with is what a read by id a
1860    /// moment later answers (spike `spike-linear-stored-content`), so a follow-up write that
1861    /// keeps the metadata slot byte for byte reads nothing after the write before it.
1862    written: std::sync::Mutex<std::collections::HashMap<(MetadataRecord, NativeId), Value>>,
1863    /// Each issue as the last read or write of it in this process answered it, whole: what
1864    /// `write_context` hands the store's cache to keep beside its entry, so a write it expects at
1865    /// that version takes it back instead of reading the issue again.
1866    contexts: std::sync::Mutex<std::collections::HashMap<NativeId, Value>>,
1867    /// Whether `write_tasks` is gathering the creates it sends together: each `write_task` it
1868    /// makes is queued rather than sent.
1869    deferring_creates: std::sync::atomic::AtomicBool,
1870    /// The creates `write_tasks` gathered, in order.
1871    queued_creates: std::sync::Mutex<Vec<batch::QueuedCreate>>,
1872    /// What each issue `write_tasks` created was sent, by its id, until the write a copy then
1873    /// makes of it — see `just_created_as`.
1874    created_inputs: std::sync::Mutex<std::collections::HashMap<NativeId, Value>>,
1875    /// Whether a copy asked, through `begin_deferred_writes`, for the relations of the issues it
1876    /// creates to wait for its `finish_writes`.
1877    deferring: std::sync::atomic::AtomicBool,
1878    /// The relation creates waiting for `finish_writes`: each near issue and its variables.
1879    deferred_relations: std::sync::Mutex<Vec<(NativeId, Value)>>,
1880    /// What a copy's read ahead read of each item it named — its raw fields, and for a task or
1881    /// a project the first page of its forward relations — each answering the next read of it
1882    /// once, and none outliving the command or any write; see
1883    /// [`TaskSource::read_ahead_records_for_copy`].
1884    ahead: std::sync::Mutex<std::collections::HashMap<(MetadataRecord, NativeId), Value>>,
1885    /// The forward relations page [`Self::ahead`] read beside each task and project.
1886    edges_ahead: std::sync::Mutex<std::collections::HashMap<(MetadataRecord, NativeId), Value>>,
1887    /// Where each item this instance wrote is, as its latest write's own answer said — what
1888    /// [`TaskSource::written_location`] answers, so a copy records where it landed an item it
1889    /// created without reading it.
1890    locations: std::sync::Mutex<std::collections::HashMap<(MetadataRecord, NativeId), String>>,
1891    /// The ids Linear's editor gave each record's headings, as the latest answer this instance
1892    /// read or wrote it with carried them — what [`TaskSource::stored_headings`] answers.
1893    headings: std::sync::Mutex<
1894        std::collections::HashMap<
1895            (MetadataRecord, NativeId),
1896            Vec<onetaskgraph_plugin_api::StoredHeading>,
1897        >,
1898    >,
1899    /// The markup the engine handed this source for its bodies — Linear's collapsible sections —
1900    /// applied to every long form and comment body this source sends and receives; see
1901    /// [`TaskSource::attach_body_markup`] and [`marked`].
1902    body_markup: std::sync::OnceLock<onetaskgraph_plugin_api::SharedBodyMarkup>,
1903    /// What each item this instance wrote holds, as its latest write's own answer said — what
1904    /// [`TaskSource::written_task`] and [`TaskSource::written_version`] answer.
1905    answered: std::sync::Mutex<std::collections::HashMap<(MetadataRecord, NativeId), Answered>>,
1906    /// What [`TaskSource::read_ahead_origins_for_copy`] read, until the next write or
1907    /// [`TaskSource::end_command`]; see [`origins::OriginsAhead`].
1908    origins_ahead: std::sync::Mutex<origins::OriginsAhead>,
1909    /// The link types this source mirrors as Linear's `related` relation.
1910    link_types: onetaskgraph_plugin_api::LinkTypes,
1911}
1912
1913/// One item's dependency read in one direction, as [`LinearSource::edges_versions`] keys it.
1914type EdgesRead = (DependencyRoot, Direction, NativeId);
1915
1916impl LinearSource {
1917    fn new(
1918        name: &SourceName,
1919        config: LinearConfig,
1920        secrets: &dyn SecretResolver,
1921    ) -> Result<Self, SourceError> {
1922        for kind in [ItemKind::Task, ItemKind::Project] {
1923            StatusMapping::distinct(
1924                name,
1925                kind,
1926                config
1927                    .status_mapping
1928                    .names(kind)
1929                    .map(|(category, mapped)| (category, mapped.as_str())),
1930            )?;
1931        }
1932        let link_types = onetaskgraph_plugin_api::LinkTypes::checked(
1933            KIND,
1934            &config.link_types,
1935            &[relations::MIRRORED],
1936            relations::REFUSED_WORDS,
1937        )
1938        .map_err(|error| match error {
1939            SourceError::Config { message } => SourceError::Config {
1940                message: format!("source {name}: {message}"),
1941            },
1942            other => other,
1943        })?;
1944        let key = secrets
1945            .get(&config.api_key_env.0)
1946            .filter(|v| !v.expose_secret().trim().is_empty())
1947            .ok_or_else(|| SourceError::Auth {
1948                message: format!("set environment variable {}", config.api_key_env.0),
1949            })?;
1950        Ok(Self {
1951            clock: onetaskgraph_plugin_api::system_clock(),
1952            client: std::sync::OnceLock::new(),
1953            endpoint: config.endpoint,
1954            key,
1955            team: config.team,
1956            name: name.clone(),
1957            statuses: config.status_mapping,
1958            project: config.project,
1959            vocabulary: std::sync::Mutex::new(None),
1960            attached: std::sync::atomic::AtomicBool::new(false),
1961            edges_versions: std::sync::Mutex::new(std::collections::HashMap::new()),
1962            stored: std::sync::Mutex::new(std::collections::HashMap::new()),
1963            written: std::sync::Mutex::new(std::collections::HashMap::new()),
1964            contexts: std::sync::Mutex::new(std::collections::HashMap::new()),
1965            deferring_creates: std::sync::atomic::AtomicBool::new(false),
1966            queued_creates: std::sync::Mutex::new(Vec::new()),
1967            created_inputs: std::sync::Mutex::new(std::collections::HashMap::new()),
1968            deferring: std::sync::atomic::AtomicBool::new(false),
1969            deferred_relations: std::sync::Mutex::new(Vec::new()),
1970            ahead: std::sync::Mutex::new(std::collections::HashMap::new()),
1971            edges_ahead: std::sync::Mutex::new(std::collections::HashMap::new()),
1972            locations: std::sync::Mutex::new(std::collections::HashMap::new()),
1973            headings: std::sync::Mutex::new(std::collections::HashMap::new()),
1974            body_markup: std::sync::OnceLock::new(),
1975            answered: std::sync::Mutex::new(std::collections::HashMap::new()),
1976            origins_ahead: std::sync::Mutex::new(origins::OriginsAhead::default()),
1977            link_types,
1978        })
1979    }
1980}
1981/// Which kind of item a write is of — and so, for a label, which of Linear's two label sets
1982/// it names.
1983#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1984pub(crate) enum WriteKind {
1985    Task,
1986    Project,
1987}
1988/// Linear's native relation type for a task edge.
1989fn issue_relation_type(kind: DependencyKind) -> &'static str {
1990    match kind {
1991        DependencyKind::Blocks => "blocks",
1992        DependencyKind::Related => "related",
1993    }
1994}
1995
1996/// What a whole write already knows of the relations its item holds.
1997enum HeldRelations<'a> {
1998    /// None: the item was just created.
1999    None,
2000    /// The item as the rewrite's own answer reported it, the first page of its relations and
2001    /// its long form among its members.
2002    Page(&'a Value),
2003    /// Nothing yet, so they are read.
2004    Unread,
2005}
2006enum Lookup {
2007    IssueLabel(String),
2008    ProjectLabel(String),
2009}
2010impl Lookup {
2011    fn query(&self) -> &'static str {
2012        match self {
2013            Self::IssueLabel(_) => graphql::ISSUE_LABEL,
2014            Self::ProjectLabel(_) => graphql::PROJECT_LABEL,
2015        }
2016    }
2017    fn connection(&self) -> &'static str {
2018        match self {
2019            Self::IssueLabel(_) => "issueLabels",
2020            Self::ProjectLabel(_) => "projectLabels",
2021        }
2022    }
2023    fn diagnostic(&self) -> String {
2024        match self {
2025            Self::IssueLabel(name) | Self::ProjectLabel(name) => format!("label {name:?}"),
2026        }
2027    }
2028    fn variables(&self) -> Value {
2029        match self {
2030            Self::IssueLabel(name) | Self::ProjectLabel(name) => json!({"name":name}),
2031        }
2032    }
2033}
2034#[derive(Clone, Copy)]
2035enum MutationRoot {
2036    IssueCreate,
2037    IssueUpdate,
2038    ProjectCreate,
2039    ProjectUpdate,
2040    IssueRelationCreate,
2041    ProjectRelationCreate,
2042    IssueRelationDelete,
2043    ProjectRelationDelete,
2044    IssueDelete,
2045    ProjectDelete,
2046    DocumentCreate,
2047    DocumentUpdate,
2048    DocumentDelete,
2049    CommentCreate,
2050    CommentUpdate,
2051    CommentDelete,
2052    WorkflowStateCreate,
2053    ProjectStatusCreate,
2054}
2055impl MutationRoot {
2056    fn as_str(self) -> &'static str {
2057        match self {
2058            Self::IssueCreate => "issueCreate",
2059            Self::IssueUpdate => "issueUpdate",
2060            Self::ProjectCreate => "projectCreate",
2061            Self::ProjectUpdate => "projectUpdate",
2062            Self::IssueRelationCreate => "issueRelationCreate",
2063            Self::ProjectRelationCreate => "projectRelationCreate",
2064            Self::IssueRelationDelete => "issueRelationDelete",
2065            Self::ProjectRelationDelete => "projectRelationDelete",
2066            Self::IssueDelete => "issueDelete",
2067            Self::ProjectDelete => "projectDelete",
2068            Self::DocumentCreate => "documentCreate",
2069            Self::DocumentUpdate => "documentUpdate",
2070            Self::DocumentDelete => "documentDelete",
2071            Self::CommentCreate => "commentCreate",
2072            Self::CommentUpdate => "commentUpdate",
2073            Self::CommentDelete => "commentDelete",
2074            Self::WorkflowStateCreate => "workflowStateCreate",
2075            Self::ProjectStatusCreate => "projectStatusCreate",
2076        }
2077    }
2078}
2079
2080#[derive(Deserialize)]
2081struct Envelope {
2082    // llmlint: ignore[invalid_states_unrepresentable] One transport envelope carries eight distinct GraphQL data shapes; each operation immediately validates its own complete mapper into typed plugin-api values, so malformed external data cannot cross the plugin boundary and a union here would duplicate every query response solely inside transport code.
2083    data: Option<Value>,
2084    #[serde(default)]
2085    errors: Vec<GqlError>,
2086}
2087#[derive(Deserialize)]
2088struct GqlError {
2089    message: String,
2090    // Held raw rather than typed, for two reasons. Linear puts the whole of *why* it
2091    // refused in here — `message` is a category name like `Argument Validation Error`,
2092    // which named neither the field nor the value when the live project-relation write
2093    // was refused by it — so a refusal carries this verbatim and a reader diagnoses from
2094    // it. And a typed shape with a required `code` fails the whole envelope's
2095    // deserialization when Linear sends extensions without one, turning a refusal this
2096    // source could explain into an unexplained malformed response.
2097    extensions: Option<Value>,
2098    /// Where in the answer the error is, its first member the root field — or the alias — it
2099    /// is about; absent for an error about the whole request.
2100    #[serde(default)]
2101    path: Option<Vec<Value>>,
2102}
2103#[derive(Deserialize)]
2104#[serde(rename_all = "camelCase")]
2105struct GqlExtensions {
2106    code: GqlErrorCode,
2107    retry_after: Option<u64>,
2108}
2109impl GqlError {
2110    fn rate_limited(&self, retry: Option<u64>, status: reqwest::StatusCode) -> Option<SourceError> {
2111        let extensions = self
2112            .coded()
2113            .filter(|extensions| matches!(extensions.code, GqlErrorCode::RateLimited))?;
2114        Some(SourceError::RateLimited {
2115            retry_after_seconds: retry.or(extensions.retry_after),
2116            message: Some(format!("Linear returned HTTP {status}")),
2117        })
2118    }
2119
2120    /// The rate-limit shape of [`Self::extensions`], when it has one.
2121    fn coded(&self) -> Option<GqlExtensions> {
2122        self.extensions
2123            .as_ref()
2124            .and_then(|value| serde_json::from_value(value.clone()).ok())
2125    }
2126    /// Everything Linear said about this refusal, on one line and cut to [`SAID_LIMIT`].
2127    ///
2128    /// Linear's own sentence comes first, then the raw envelope, because only the first
2129    /// of those two is short enough to survive [`SAID_LIMIT`] on its merits. `message` is
2130    /// a category name — `Argument Validation Error` — and the sentence naming the field
2131    /// and the values it would have taken is `extensions.userPresentableMessage`, one of
2132    /// several keys in an envelope whose `validationErrors` echoes the whole rejected
2133    /// input back. Observed against the real API on 2026-09-04, a `projectRelationCreate`
2134    /// refusal rendered past the cut, and the echo is what got cut.
2135    ///
2136    /// That the sentence itself did not was luck: this build of `serde_json` renders an
2137    /// object's keys sorted, and `userPresentableMessage` happens to sort ahead of
2138    /// `validationErrors`. Nobody chose that — Linear sends the echo first — and any key
2139    /// Linear adds sorting between the two would move the sentence behind an echo longer
2140    /// than the whole limit, as would turning `preserve_order` on. Leading with it makes
2141    /// what a reader diagnoses from independent of both.
2142    fn said(&self) -> String {
2143        let Some(extensions) = &self.extensions else {
2144            return elided(&self.message);
2145        };
2146        match extensions
2147            .get("userPresentableMessage")
2148            .and_then(Value::as_str)
2149            .filter(|sentence| !sentence.is_empty())
2150        {
2151            Some(sentence) => elided(&format!("{}: {sentence} {extensions}", self.message)),
2152            None => elided(&format!("{}: {extensions}", self.message)),
2153        }
2154    }
2155}
2156#[derive(Deserialize)]
2157enum GqlErrorCode {
2158    #[serde(rename = "RATELIMITED", alias = "RATE_LIMITED")]
2159    RateLimited,
2160    #[serde(other)]
2161    Other,
2162}
2163
2164/// One GraphQL error Linear answered a request with, before it is made a [`SourceError`].
2165struct Refusal(GqlError);
2166
2167impl Refusal {
2168    /// The index of the alias of an [`graphql::aliased`] document this refusal is about, when
2169    /// its path names one.
2170    fn alias(&self) -> Option<usize> {
2171        self.0
2172            .path
2173            .as_ref()?
2174            .first()?
2175            .as_str()?
2176            .strip_prefix('a')?
2177            .parse()
2178            .ok()
2179    }
2180
2181    /// Whether Linear refused because the issue the request addressed is not there.
2182    ///
2183    /// Linear answers a mutation addressing an id it does not hold with an errored response —
2184    /// `Entity not found: Issue`, whose `userPresentableMessage` reads `Could not find
2185    /// referenced Issue.` — rather than a null payload. Both spellings are recognised, so a
2186    /// rewording of either one alone still reads as what it is; an entity of any other kind,
2187    /// and anything else, is a refusal. The live capability journey sends this mutation
2188    /// to a nonexistent issue and requires `None`, so changed service wording fails the lane.
2189    fn entity_missing(&self) -> bool {
2190        self.missing(
2191            graphql::ISSUE_NOT_FOUND_MESSAGE,
2192            graphql::ISSUE_NOT_FOUND_PRESENTABLE,
2193        )
2194    }
2195
2196    /// Whether Linear refused because the project the request addressed is not there, on the
2197    /// terms of [`Self::entity_missing`].
2198    fn project_missing(&self) -> bool {
2199        self.missing(
2200            graphql::PROJECT_NOT_FOUND_MESSAGE,
2201            graphql::PROJECT_NOT_FOUND_PRESENTABLE,
2202        )
2203    }
2204
2205    /// Whether Linear refused because the document the request addressed is not there, on the
2206    /// terms of [`Self::entity_missing`].
2207    fn document_missing(&self) -> bool {
2208        self.missing(
2209            graphql::DOCUMENT_NOT_FOUND_MESSAGE,
2210            graphql::DOCUMENT_NOT_FOUND_PRESENTABLE,
2211        )
2212    }
2213
2214    /// Whether Linear refused a page because it cannot find the cursor the page was asked to
2215    /// follow, in either of its spellings.
2216    fn cursor_missing(&self) -> bool {
2217        self.missing(
2218            graphql::CURSOR_NOT_FOUND_MESSAGE,
2219            graphql::CURSOR_NOT_FOUND_PRESENTABLE,
2220        )
2221    }
2222
2223    /// Whether this refusal is Linear's `message` — or its `presentable` alternative — for the
2224    /// one entity the request addressed.
2225    fn missing(&self, message: &str, presentable: &str) -> bool {
2226        let lowered = self.0.message.to_ascii_lowercase();
2227        // The entity the mutation addressed, and nothing it merely refers to: a state the input
2228        // names that Linear does not hold is a refusal of the write, never no such item.
2229        lowered.trim_end() == message.to_ascii_lowercase()
2230            || lowered.starts_with(&format!("{} ", message.to_ascii_lowercase()))
2231            || self
2232                .0
2233                .extensions
2234                .as_ref()
2235                .and_then(|extensions| extensions.get("userPresentableMessage"))
2236                .and_then(Value::as_str)
2237                .is_some_and(|said| {
2238                    said.to_ascii_lowercase()
2239                        .starts_with(&presentable.trim_end_matches('.').to_ascii_lowercase())
2240                })
2241    }
2242
2243    fn into_error(self) -> SourceError {
2244        SourceError::Refused {
2245            message: self.0.said(),
2246        }
2247    }
2248}
2249
2250/// One targeted update composed for sending — see `LinearSource::compose_update`.
2251struct Composed {
2252    /// The issue as it was read before the update.
2253    before: Task,
2254    /// What `issueUpdate` is sent; empty when nothing differs.
2255    input: serde_json::Map<String, Value>,
2256    /// The relations to write after it, when the update names dependencies that differ.
2257    relations: Option<Vec<DependencyEdge>>,
2258}
2259
2260/// How [`LinearSource::answer_with`] reads a GraphQL error Linear sends under HTTP 400 that is no
2261/// rate limit and no missing item.
2262#[derive(Clone, Copy, PartialEq, Eq)]
2263enum Under400 {
2264    /// As the call failing, [`SourceError::Unavailable`] naming the status — what every read and
2265    /// every write but a keyed create reports.
2266    Unavailable,
2267    /// As Linear's refusal of the request, which it did not apply.
2268    Refusal,
2269}
2270
2271/// How [`LinearSource::send_write`] settled a write.
2272enum Written {
2273    /// Linear answered it, with `data`; `sent` is the id a keyed create was sent under.
2274    Answered { data: Value, sent: Option<NativeId> },
2275    /// A keyed create's item an earlier or concurrent attempt made, under that id.
2276    Held(NativeId),
2277}
2278
2279/// How many ids a create key derives: see [`linear_ids_of_key`].
2280pub const CREATE_ID_GENERATIONS: u8 = 8;
2281
2282/// How much of a failed response's body a refusal carries.
2283///
2284/// Enough for Linear's own error envelope, which is one or two sentences naming the field
2285/// or argument it would not accept, and short enough that a proxy's HTML error page does
2286/// not become the whole message.
2287const SAID_LIMIT: usize = 400;
2288
2289/// `said` made safe to put in a message: one line of printable text, cut to [`SAID_LIMIT`].
2290///
2291/// A failed response's body is whatever answered — Linear's error envelope, or an HTML
2292/// page from a proxy in front of it — and this message is written to a terminal. So every
2293/// control character goes, escape sequences with them, and each run of whitespace becomes
2294/// one space: a body cannot move the cursor, repaint the line or hide the rest of the
2295/// diagnostic behind itself. Cut by characters rather than bytes, because slicing UTF-8
2296/// mid-codepoint would panic inside the path that exists to explain a failure.
2297fn elided(said: &str) -> String {
2298    let mut printable = String::new();
2299    let mut spaced = true;
2300    for character in said.chars() {
2301        if character.is_control() || character.is_whitespace() {
2302            if !spaced {
2303                printable.push(' ');
2304                spaced = true;
2305            }
2306            continue;
2307        }
2308        printable.push(character);
2309        spaced = false;
2310    }
2311    let printable = printable.trim_end();
2312    if printable.chars().count() <= SAID_LIMIT {
2313        return printable.to_owned();
2314    }
2315    let kept: String = printable.chars().take(SAID_LIMIT).collect();
2316    format!("{kept}…")
2317}
2318
2319impl LinearSource {
2320    async fn send(&self, query: &str, variables: Value) -> Result<Value, SourceError> {
2321        if !resumes_a_page(&variables) {
2322            return self
2323                .answer(query, variables)
2324                .await?
2325                .map_err(|refusal| refusal.into_error());
2326        }
2327        // The same page after the same cursor is read again (see
2328        // [`graphql::CURSOR_NOT_FOUND_MESSAGE`]) rather than the walk restarted from its first
2329        // page, which would hand the caller rows it already has.
2330        let mut pause = STALE_CURSOR_PAUSE;
2331        let mut reread = 0;
2332        loop {
2333            match self.answer(query, variables.clone()).await? {
2334                Ok(data) => return Ok(data),
2335                Err(refusal) if refusal.cursor_missing() && reread < STALE_CURSOR_REREADS => {
2336                    reread += 1;
2337                    self.clock.sleep_because(pause, STALE_CURSOR_WAIT).await;
2338                    pause = pause.saturating_mul(2);
2339                }
2340                Err(refusal) if refusal.cursor_missing() => {
2341                    return Err(SourceError::Refused {
2342                        message: format!(
2343                            "Linear did not recognise the page's cursor on {} reads of it: {}; \
2344                             start the walk again from its first page",
2345                            reread + 1,
2346                            refusal.0.said()
2347                        ),
2348                    });
2349                }
2350                Err(refusal) => return Err(refusal.into_error()),
2351            }
2352        }
2353    }
2354
2355    /// Send a mutation addressing one item by id, answering `None` when Linear refuses it
2356    /// because there is no such item.
2357    ///
2358    /// What lets a status write answer "no such task" without reading the issue first: Linear
2359    /// reports an id naming nothing as an errored response rather than a null payload, and
2360    /// [`Refusal::entity_missing`] is how that refusal is told apart from every other.
2361    async fn send_to_held(
2362        &self,
2363        query: &str,
2364        variables: Value,
2365    ) -> Result<Option<Value>, SourceError> {
2366        match self.answer(query, variables).await? {
2367            Ok(data) => Ok(Some(data)),
2368            Err(refusal) if refusal.entity_missing() => Ok(None),
2369            Err(refusal) => Err(refusal.into_error()),
2370        }
2371    }
2372
2373    /// Send a read of one item by id, answering `None` when Linear refuses it because the item
2374    /// of the kind `missing` recognises is not there.
2375    ///
2376    /// Linear answers `issue(id:)`, `project(id:)` and `document(id:)` naming nothing with an
2377    /// errored response — `Entity not found: <type>` — rather than a null, whatever HTTP status
2378    /// it sends it under, so a read by an id this workspace does not hold is told apart here
2379    /// from every other refusal. A not-found naming an entity of another kind is a refusal: it
2380    /// is about something the read did not address.
2381    async fn send_to_read(
2382        &self,
2383        query: &str,
2384        variables: Value,
2385        missing: fn(&Refusal) -> bool,
2386    ) -> Result<Option<Value>, SourceError> {
2387        match self.answer(query, variables).await? {
2388            Ok(data) => Ok(Some(data)),
2389            Err(refusal) if missing(&refusal) => Ok(None),
2390            Err(refusal) => Err(refusal.into_error()),
2391        }
2392    }
2393
2394    /// Send a long-form write: an update, or a create with no key, as it is; a create carrying a
2395    /// key under each generation of the id its key derives — [`linear_ids_of_key`] — in turn.
2396    ///
2397    /// A keyed create Linear refuses is followed by a read of the id it was sent under, for the
2398    /// item an earlier or a concurrent attempt made there, answered [`Written::Held`] when there
2399    /// is one. Otherwise the id is held by something this source cannot read — a record deleted
2400    /// since, a copy's undo of an earlier attempt among them, or one of another workspace, and
2401    /// Linear lets one id name one record ever — so the create is sent under the next
2402    /// generation. An answer that did not arrive is never followed by another create, because
2403    /// Linear may have applied it: it is read for, and otherwise its own failure is the answer.
2404    /// When every generation is refused, the last refusal is.
2405    ///
2406    /// A create sent under its origin's key — [`CreateId::Origin`] — is held to more: it tries
2407    /// the next generation only when Linear refused the last because a record holds that id, and
2408    /// a record there copied from the same origin is the counterpart an earlier copy made, which
2409    /// the copy's lookup did not list. That create is refused naming it, and nothing is created:
2410    /// see the crate documentation's ruling on how a copy finds what it wrote.
2411    async fn send_write(
2412        &self,
2413        record: MetadataRecord,
2414        query: &str,
2415        mut variables: Value,
2416        create: &CreateId,
2417    ) -> Result<Written, SourceError> {
2418        let (key, origin) = match create {
2419            CreateId::Unchosen => {
2420                return Ok(Written::Answered {
2421                    data: self.send(query, variables).await?,
2422                    sent: None,
2423                });
2424            }
2425            CreateId::Keyed(key) => (key.hyphenated().to_string(), None),
2426            CreateId::Origin { key, origin } => {
2427                (key.hyphenated().to_string(), Some(origin.as_str()))
2428            }
2429        };
2430        let key = key.as_str();
2431        let mut refused = None;
2432        for (generation, id) in linear_ids_of_key(key)?.into_iter().enumerate() {
2433            // A create after a refused one is asked for as every other write is: the hold that
2434            // admitted the first may since have passed to another attempt.
2435            if generation > 0 {
2436                <dyn onetaskgraph_plugin_api::WriteGuard>::check().await?;
2437            }
2438            variables["input"]["id"] = Value::String(id.clone());
2439            let error = match self
2440                .answer_with(query, variables.clone(), Under400::Refusal)
2441                .await
2442            {
2443                Ok(Ok(data)) => {
2444                    return Ok(Written::Answered {
2445                        data,
2446                        sent: Some(NativeId(id)),
2447                    });
2448                }
2449                Ok(Err(refusal)) => {
2450                    // A create under its origin's key moves to the next id only for a record
2451                    // holding this one; any other refusal is the create's answer, as it is for a
2452                    // create Linear chooses the id of.
2453                    if origin.is_some()
2454                        && !refusal
2455                            .0
2456                            .message
2457                            .trim()
2458                            .eq_ignore_ascii_case(graphql::id_conflict_message(record))
2459                    {
2460                        self.forget_vocabulary();
2461                        return Err(refusal.into_error());
2462                    }
2463                    Ok(refusal.into_error())
2464                }
2465                Err(error) => Err(error),
2466            };
2467            self.forget_vocabulary();
2468            if let Some(origin) = origin {
2469                // Whatever holds the id is read, and a read that fails is the answer: an id
2470                // this create cannot see past may hold its counterpart, so no other is tried.
2471                if error.is_ok()
2472                    && let Some(held) = self
2473                        .copied_at(record, &NativeId(id.clone()), origin)
2474                        .await?
2475                {
2476                    // An issue an earlier copy made of this origin is this create's counterpart,
2477                    // which a copy finds by its create's own conflict rather than by a read
2478                    // before it: it is brought in step by a compared update — see `write_task`.
2479                    if record == MetadataRecord::Task {
2480                        return Ok(Written::Held(held));
2481                    }
2482                    return Err(SourceError::Refused {
2483                        message: format!(
2484                            "Linear already holds {} {}, which an earlier copy made of {origin}, \
2485                             though this copy's lookup by origin did not list it; nothing was \
2486                             created; next: copy again, which finds it by that id",
2487                            record_noun(record),
2488                            held.0
2489                        ),
2490                    });
2491                }
2492            } else if let Ok(Some(held)) = self.held_at(record, &NativeId(id)).await {
2493                // The read's own failure says nothing of the create, so it is never the answer.
2494                return Ok(Written::Held(held));
2495            }
2496            match error {
2497                Ok(refusal) => refused = Some(refusal),
2498                Err(unanswered) => return Err(unanswered),
2499            }
2500        }
2501        Err(refused.unwrap_or_else(|| SourceError::Malformed {
2502            message: format!("create key {key:?} derives no id"),
2503        }))
2504    }
2505
2506    /// The id of the `record` this source holds under `id`, if it holds one.
2507    async fn held_at(
2508        &self,
2509        record: MetadataRecord,
2510        id: &NativeId,
2511    ) -> Result<Option<NativeId>, SourceError> {
2512        Ok(match record {
2513            MetadataRecord::Task => self.get_task(id).await?.map(|task| task.id),
2514            MetadataRecord::Project => self.get_project(id).await?.map(|project| project.id),
2515            MetadataRecord::Document => self.get_document(id).await?.map(|document| document.id),
2516        })
2517    }
2518
2519    // llmlint: ignore[invalid_states_unrepresentable] This private generic transport accepts only variables constructed immediately at typed TaskSource call sites, never untrusted input; per-operation response mappers validate every external field before returning public values.
2520    async fn answer(
2521        &self,
2522        query: &str,
2523        variables: Value,
2524    ) -> Result<Result<Value, Refusal>, SourceError> {
2525        self.answer_with(query, variables, Under400::Unavailable)
2526            .await
2527    }
2528
2529    /// [`Self::answer`], reading a GraphQL error Linear sends under HTTP 400 as `under_400` says.
2530    // llmlint: ignore[invalid_states_unrepresentable] As `answer` above: a private transport taking only variables its typed call sites construct.
2531    async fn answer_with(
2532        &self,
2533        query: &str,
2534        variables: Value,
2535        under_400: Under400,
2536    ) -> Result<Result<Value, Refusal>, SourceError> {
2537        // A write may change which items record an origin, so nothing read ahead outlives it.
2538        if query.trim_start().starts_with("mutation") {
2539            self.forget_origins_ahead(false);
2540            self.forget_ahead();
2541        }
2542        // Every body crosses here, so this is the one place the engine's markup is applied: each
2543        // one sent is written in it, and each one answered read back out of it.
2544        let markup = self.body_markup.get();
2545        let variables = match markup {
2546            Some(markup) => marked(variables, &|body| markup.written(body)),
2547            None => variables,
2548        };
2549        let answered = self
2550            .answer_using(
2551                self.client.get_or_init(reqwest::Client::new),
2552                query,
2553                variables,
2554                under_400,
2555            )
2556            .await;
2557        let answered = match (answered, markup) {
2558            (Ok(Ok(data)), Some(markup)) => Ok(Ok(marked(data, &|body| markup.read(body)))),
2559            (answered, _) => answered,
2560        };
2561        match answered {
2562            Err(SourceError::RateLimited {
2563                retry_after_seconds,
2564                ..
2565            }) => Err(SourceError::RateLimited {
2566                retry_after_seconds,
2567                message: None,
2568            }),
2569            Ok(Ok(data)) => {
2570                // Every read and every write that selects a record's editor state says where
2571                // its headings are stored, and is the only thing that does.
2572                let carried = headings::carried(&data);
2573                if !carried.is_empty() {
2574                    let mut held = self
2575                        .headings
2576                        .lock()
2577                        .unwrap_or_else(std::sync::PoisonError::into_inner);
2578                    for (record, headings) in carried {
2579                        match headings {
2580                            Some(headings) => {
2581                                held.insert(record, headings);
2582                            }
2583                            None => {
2584                                held.remove(&record);
2585                            }
2586                        }
2587                    }
2588                }
2589                Ok(Ok(data))
2590            }
2591            result => result,
2592        }
2593    }
2594
2595    async fn answer_using(
2596        &self,
2597        client: &reqwest::Client,
2598        query: &str,
2599        variables: Value,
2600        under_400: Under400,
2601    ) -> Result<Result<Value, Refusal>, SourceError> {
2602        // Every mutation but a create is asked for immediately before it is sent — a create's
2603        // relations, the whole write that finishes a create answered as an id already held, an
2604        // upload, a comment — so a copy that owns the create renews its hold first, and one that
2605        // has lost it sends nothing more. A write retried later is asked for again here.
2606        if query.trim_start().starts_with("mutation")
2607            && ![
2608                graphql::ISSUE_CREATE,
2609                graphql::PROJECT_CREATE,
2610                graphql::DOCUMENT_CREATE,
2611            ]
2612            .contains(&query)
2613        {
2614            <dyn onetaskgraph_plugin_api::WriteGuard>::check().await?;
2615        }
2616        let response = client
2617            .post(&self.endpoint.0)
2618            .header("Authorization", self.key.expose_secret())
2619            .json(&json!({"query": query, "variables": variables}))
2620            .send()
2621            .await
2622            .map_err(|e| SourceError::Unavailable {
2623                message: with_causes(&e),
2624            })?;
2625        let status = response.status();
2626        let retry = reset_wait(response.headers()).map(|wait| {
2627            wait.as_secs()
2628                .saturating_add(u64::from(wait.subsec_nanos() > 0))
2629        });
2630        if status.as_u16() == 429 {
2631            return Err(SourceError::RateLimited {
2632                retry_after_seconds: retry,
2633                message: Some(format!("Linear returned HTTP {status}")),
2634            });
2635        }
2636        if status.as_u16() == 401 || status.as_u16() == 403 {
2637            return Err(SourceError::Auth {
2638                message: format!("Linear rejected the configured credential: HTTP {status}"),
2639            });
2640        }
2641        if !status.is_success() {
2642            // Linear puts its GraphQL error envelope in the *body* of a 400, so the status
2643            // alone names the whole call and nothing about what Linear objected to. The
2644            // body is Linear's answer to this request and holds no credential; it is cut
2645            // because a proxy in front of Linear can answer with a page.
2646            let text = response.text().await.unwrap_or_default();
2647            if let Some(limited) = serde_json::from_str::<Envelope>(&text)
2648                .ok()
2649                .and_then(|body| body.errors.into_iter().next())
2650                .and_then(|error| error.rate_limited(retry, status))
2651            {
2652                return Err(limited);
2653            }
2654            // An id naming nothing, and a cursor Linear cannot place, are the refusals a caller
2655            // acts on rather than reports, so each reads the same whichever status Linear sends
2656            // it under.
2657            if let Some(missing) = serde_json::from_str::<Envelope>(&text)
2658                .ok()
2659                .and_then(|body| body.errors.into_iter().next())
2660                .map(Refusal)
2661                .filter(|refusal| {
2662                    refusal.entity_missing()
2663                        || refusal.project_missing()
2664                        || refusal.document_missing()
2665                        || refusal.cursor_missing()
2666                })
2667            {
2668                return Ok(Err(missing));
2669            }
2670            // Linear's own refusal of the request, which it did not apply, for the one caller
2671            // that has to tell that from an answer that never arrived: a create, which tries the
2672            // next generation of its id only when Linear refused the last.
2673            if under_400 == Under400::Refusal
2674                && status.as_u16() == 400
2675                && let Some(error) = serde_json::from_str::<Envelope>(&text)
2676                    .ok()
2677                    .and_then(|body| body.errors.into_iter().next())
2678            {
2679                return Ok(Err(Refusal(error)));
2680            }
2681            let said = elided(&text);
2682            return Err(SourceError::Unavailable {
2683                message: if said.is_empty() {
2684                    format!("Linear returned HTTP {status}")
2685                } else {
2686                    format!("Linear returned HTTP {status}: {said}")
2687                },
2688            });
2689        }
2690        let body: Envelope = response.json().await.map_err(|e| SourceError::Malformed {
2691            message: format!("HTTP {status}: {e}"),
2692        })?;
2693        if let Some(error) = body.errors.into_iter().next() {
2694            if let Some(limited) = error.rate_limited(retry, status) {
2695                return Err(limited);
2696            }
2697            return Ok(Err(Refusal(error)));
2698        }
2699        body.data.map(Ok).ok_or_else(|| SourceError::Malformed {
2700            message: "GraphQL response has no data".into(),
2701        })
2702    }
2703
2704    // llmlint: ignore-block[contracts_have_one_source_or_a_drift_gate] These operators follow the accepted 2026-08-24 Linear contract, but Linear exposes their authoritative definitions only through an authenticated unversioned explorer; the real-HTTP tests assert every serialized operator and the shared CLI journeys assert resulting rows without making credentials required.
2705    /// The label predicates, which really are spelled the same at both levels.
2706    ///
2707    /// `IssueFilter.labels` is an `IssueLabelCollectionFilter` and `ProjectFilter.labels`
2708    /// is a `ProjectLabelCollectionFilter` — two types — but `some`, `every` and a `name`
2709    /// of `StringComparator` are members of both, so one spelling satisfies each. That is
2710    /// the whole of what the two filters have in common, and everything else about them is
2711    /// built separately for the reason recorded on the two builders below.
2712    ///
2713    /// "At least one of these" is a disjunction of `eqIgnoreCase` rather than one
2714    /// case-insensitive list operator, because Linear has no such operator. This source
2715    /// sent `labels:{some:{name:{inIgnoreCase:[…]}}}` until Linear refused it outright,
2716    /// HTTP 400, on the first read of the live lane that ever reached a label filter:
2717    ///
2718    /// ```text
2719    /// Variable "$filter" got invalid value { inIgnoreCase: […] } at
2720    /// "filter.and[1].labels.some.name"; Field "inIgnoreCase" is not defined by
2721    /// type "StringComparator". Did you mean "eqIgnoreCase" or "neqIgnoreCase"?
2722    /// ```
2723    ///
2724    /// That refusal is also the evidence for the replacement: Linear named the two members
2725    /// of `StringComparator` closest to what it was sent, and `eqIgnoreCase` is one of
2726    /// them — the same operator `all_of` below has always sent and the live lane has always
2727    /// exercised. `in` exists there too and would need no `or`, but it is case-sensitive,
2728    /// so `any_of` would stop agreeing with `all_of` and `none_of` and with what the table
2729    /// at the top of this file says this source does.
2730    fn label_parts(labels: &onetaskgraph_plugin_api::LabelFilter) -> Vec<Value> {
2731        let mut parts = Vec::new();
2732        if !labels.any_of.is_empty() {
2733            parts.push(json!({"or": labels
2734                .any_of
2735                .iter()
2736                .map(|name| json!({"labels": {"some": {"name": {"eqIgnoreCase": name}}}}))
2737                .collect::<Vec<_>>()}));
2738        }
2739        for name in &labels.all_of {
2740            parts.push(json!({"labels": {"some": {"name": {"eqIgnoreCase": name}}}}));
2741        }
2742        for name in &labels.none_of {
2743            parts.push(json!({"labels": {"every": {"name": {"neqIgnoreCase": name}}}}));
2744        }
2745        parts
2746    }
2747    fn narrowed(mut parts: Vec<Value>) -> Value {
2748        if parts.len() == 1 {
2749            parts.pop().unwrap()
2750        } else {
2751            json!({"and": parts})
2752        }
2753    }
2754    /// The filter this source sends to `issues(filter:)`.
2755    ///
2756    /// **`IssueFilter` and `ProjectFilter` are different input types, and one builder for
2757    /// both is what put two wrong fields on the wire.** They read as though they were the
2758    /// same filter over different rows — the label member really is spelled alike, and the
2759    /// `and`/`or` are identical — and a single builder producing one object for both
2760    /// connections had shipped `team` and the issue's `state` shape into `projects(filter:)`
2761    /// since long before this branch. Linear refused the first outright:
2762    ///
2763    /// ```text
2764    /// Variable "$filter" got invalid value { team: { key: [Object] } };
2765    /// Field "team" is not defined by type "ProjectFilter". Did you mean "lead"?
2766    /// ```
2767    ///
2768    /// So there are two builders, and each names its own type's members. Adding a predicate
2769    /// means deciding twice, on purpose, rather than once by accident.
2770    fn issue_filter(&self, query: &TaskQuery) -> Result<Value, SourceError> {
2771        let mut parts = self.issue_scope();
2772        parts.extend(Self::label_parts(&query.labels));
2773        if !query.statuses.is_empty() {
2774            parts.extend(self.status_narrowing(ItemKind::Task, &query.statuses));
2775        }
2776        match &query.project {
2777            ProjectFilter::Orphans => parts.push(json!({"project": {"null": true}})),
2778            ProjectFilter::Is(id) => parts.push(json!({"project": {"id": {"eq": id.0}}})),
2779            ProjectFilter::Any => {}
2780        }
2781        // The narrowings below are each confirmed in process by `confirms` before a row is
2782        // returned: Linear's comparators are a candidate set, and the contract's predicate is
2783        // what decides. None of them can drop a row the predicate keeps — see the module
2784        // documentation's ruling on the follow-up searches for what each one rests on.
2785        if !query.priorities.is_empty() {
2786            parts.push(json!({"priority": {"in": query
2787                .priorities
2788                .iter()
2789                .map(|priority| linear_priority(*priority))
2790                .collect::<Vec<_>>()}}));
2791        }
2792        if let Some(since) = query.commented_since {
2793            let since = since.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true);
2794            parts.push(json!({"comments": {"some": {"or": [
2795                {"createdAt": {"gte": since}},
2796                {"updatedAt": {"gte": since}},
2797            ]}}}));
2798        }
2799        for wanted in &query.metadata {
2800            parts.extend(slot_phrase(wanted.value()));
2801        }
2802        if let Some(origin) = &query.origin {
2803            parts.extend(slot_phrase(origin));
2804        }
2805        if let Some(text) = &query.text {
2806            let title = json!({"title": {"containsIgnoreCase": text.terms}});
2807            let content = json!({"description": {"containsIgnoreCase": text.terms}});
2808            parts.push(match text.fields {
2809                TextFields::Title => title,
2810                TextFields::Content => content,
2811                TextFields::TitleOrContent => json!({"or": [title, content]}),
2812            });
2813        }
2814        Ok(Self::narrowed(parts))
2815    }
2816
2817    /// What every issue read of this source is narrowed to before any predicate: the
2818    /// configured team, and the project this source is scoped to, when it is.
2819    fn issue_scope(&self) -> Vec<Value> {
2820        let mut parts = Vec::new();
2821        if let Some(team) = &self.team {
2822            parts.push(json!({"team": {"key": {"eqIgnoreCase": team.0}}}));
2823        }
2824        if let Some(project) = &self.project {
2825            parts.push(json!({"project": {"id": {"eq": project.0}}}));
2826        }
2827        parts
2828    }
2829
2830    /// The status narrowing for `statuses` over one kind's items, through this instance's
2831    /// mapping — `state` on an issue, `status` on a project, each compared by name.
2832    ///
2833    /// Each category asks for exactly what reads as it: the items at the name its kind maps it
2834    /// to, and — for `unknown` — every item at a name that kind's mapping does not name at
2835    /// all. A category the kind has no name for asks for nothing, because nothing reads as it.
2836    /// `None` is the one narrowing that is everything: `unknown` over a kind whose mapping
2837    /// names nothing, where every item reads as `unknown`.
2838    ///
2839    /// Compared ignoring case, as a read matches a name: `eqIgnoreCase` for a mapped name and
2840    /// `neqIgnoreCase` for every name an `unknown` excludes, because `in` and `nin` are the
2841    /// case-sensitive list operators and a state spelled `TODO` reads as a mapping's `Todo`.
2842    fn status_narrowing(&self, kind: ItemKind, statuses: &[StatusCategory]) -> Option<Value> {
2843        let member = match kind {
2844            ItemKind::Task => "state",
2845            ItemKind::Project => "status",
2846        };
2847        let named = |name: &str, operator: &str| json!({ (member): {"name": {(operator): name}}});
2848        let mut alternatives = Vec::new();
2849        for category in statuses {
2850            if let Ok(name) = self.statuses.name_for(*category, kind) {
2851                alternatives.push(named(name.as_str(), "eqIgnoreCase"));
2852            }
2853            if *category == StatusCategory::Unknown {
2854                let unmapped: Vec<Value> = self
2855                    .statuses
2856                    .names(kind)
2857                    .map(|(_, name)| named(name.as_str(), "neqIgnoreCase"))
2858                    .collect();
2859                if unmapped.is_empty() {
2860                    return None;
2861                }
2862                alternatives.push(Self::narrowed(unmapped));
2863            }
2864        }
2865        Some(match alternatives.len() {
2866            // Nothing asked for has a name of this kind: a name no item is at, which matches
2867            // nothing and is refused by nothing.
2868            0 => json!({ (member): {"name": {"in": Vec::<&str>::new()}}}),
2869            1 => alternatives.pop().expect("one alternative"),
2870            _ => json!({ "or": alternatives }),
2871        })
2872    }
2873
2874    /// Whether one task this source read satisfies every predicate of `query` that a
2875    /// narrowing above only approximates — the metadata matches, the origin, the text and the
2876    /// priorities — by the contract's own statement of each.
2877    fn confirms(query: &TaskQuery, task: &Task) -> bool {
2878        (query.statuses.is_empty() || query.statuses.contains(&task.status.category))
2879            && query.metadata_matches(&task.metadata)
2880            && query.origin_matches(&task.metadata)
2881            && (query.priorities.is_empty() || query.priorities.contains(&task.priority))
2882            && query
2883                .text
2884                .as_ref()
2885                .is_none_or(|text| text_holds(&task.title, task.content.as_deref(), text))
2886    }
2887
2888    /// The filter this source sends to `projects(filter:)`.
2889    ///
2890    /// Two members differ from [`Self::issue_filter`] and both are Linear's doing; see that
2891    /// builder for why they are written out twice rather than shared.
2892    ///
2893    /// **A project has no `team`.** It has the teams it is accessible from, and
2894    /// `ProjectFilter.accessibleTeams` is a `TeamCollectionFilter`, so the same team key
2895    /// reaches it under `some:`. `leadTeam` is the other team-shaped member and is a
2896    /// different set — one designated team rather than every team the project is in — so
2897    /// narrowing by it would drop projects the configured team really does hold.
2898    ///
2899    /// **A project's status is not an issue's state.** An issue's is a `WorkflowState` of the
2900    /// team, reached through `IssueFilter.state`; a project's is a `ProjectStatus` of the
2901    /// workspace, reached through `ProjectFilter.status` — `ProjectFilter.state` exists and is
2902    /// *not* it: that member is a bare `StringComparator` over a different thing. The two are
2903    /// different vocabularies of names, which is why `status_mapping` names each kind's
2904    /// separately, and why each is narrowed by its own kind's names
2905    /// ([`Self::status_narrowing`]).
2906    fn project_filter(
2907        &self,
2908        labels: &onetaskgraph_plugin_api::LabelFilter,
2909        statuses: &[StatusCategory],
2910    ) -> Value {
2911        let mut parts = self.project_scope();
2912        parts.extend(Self::label_parts(labels));
2913        if !statuses.is_empty() {
2914            parts.extend(self.status_narrowing(ItemKind::Project, statuses));
2915        }
2916        Self::narrowed(parts)
2917    }
2918
2919    /// What every project read of this source is narrowed to: the projects the configured
2920    /// team can reach, and the one project this source is scoped to, when it is.
2921    fn project_scope(&self) -> Vec<Value> {
2922        let mut parts = Vec::new();
2923        if let Some(team) = &self.team {
2924            parts.push(json!({"accessibleTeams": {"some": {"key": {"eqIgnoreCase": team.0}}}}));
2925        }
2926        if let Some(project) = &self.project {
2927            parts.push(json!({"id": {"eq": project.0}}));
2928        }
2929        parts
2930    }
2931
2932    /// Whether an item filed under `project` is one this source holds: always, unless it is
2933    /// scoped to one project and this is not filed under it.
2934    fn in_scope(&self, project: Option<&NativeId>) -> bool {
2935        self.project
2936            .as_ref()
2937            .is_none_or(|scope| project.is_some_and(|project| project.0 == scope.0))
2938    }
2939
2940    /// The project a task or a document written with `project` is filed under: that one, or
2941    /// the scope when it names none — and a refusal naming both when it names another.
2942    fn filed_in(
2943        &self,
2944        project: Option<&NativeId>,
2945        what: &str,
2946    ) -> Result<Option<String>, SourceError> {
2947        match (&self.project, project) {
2948            (None, project) => Ok(project.map(|id| id.0.clone())),
2949            (Some(scope), None) => Ok(Some(scope.0.clone())),
2950            (Some(scope), Some(project)) if project.0 == scope.0 => Ok(Some(scope.0.clone())),
2951            (Some(scope), Some(project)) => Err(SourceError::Refused {
2952                message: format!(
2953                    "source {} is scoped to the Linear project {} and cannot hold a {what} in                      the project {}; next: write it with no project, or with {}, or to a                      source scoped to {}",
2954                    self.name, scope.0, project.0, scope.0, project.0
2955                ),
2956            }),
2957        }
2958    }
2959    // llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate]
2960
2961    /// The refusal of a project write to `target` — `None` for a new project — when this
2962    /// source is scoped to another: it holds that project and no other, so it writes no other,
2963    /// because a project it created would be one none of its reads could find. Asked before
2964    /// any request is sent.
2965    fn project_out_of_scope(&self, target: Option<&NativeId>) -> Option<SourceError> {
2966        let scope = self.project.as_ref()?;
2967        if target.is_some_and(|target| target.0 == scope.0) {
2968            return None;
2969        }
2970        Some(SourceError::Refused {
2971            message: format!(
2972                "source {} is scoped to the Linear project {} and holds no other project, so it \
2973                 cannot write {}; next: copy the project to a source with no `project`, or copy \
2974                 its tasks here",
2975                self.name,
2976                scope.0,
2977                target.map_or_else(
2978                    || "a new one".to_owned(),
2979                    |target| format!("the project {}", target.0)
2980                ),
2981            ),
2982        })
2983    }
2984
2985    async fn one_id(&self, lookup: Lookup) -> Result<NativeId, SourceError> {
2986        let data = self.send(lookup.query(), lookup.variables()).await?;
2987        self.only_id(&lookup, &data)
2988    }
2989
2990    /// The one id `data`, a lookup's answer, names — refused naming the lookup when it names
2991    /// none or several.
2992    fn only_id(&self, lookup: &Lookup, data: &Value) -> Result<NativeId, SourceError> {
2993        let connection = lookup.connection();
2994        let nodes = data
2995            .get(connection)
2996            .and_then(|v| v.get("nodes"))
2997            .and_then(Value::as_array)
2998            .ok_or_else(|| SourceError::Malformed {
2999                message: format!("missing {connection}.nodes"),
3000            })?;
3001        match nodes.as_slice() {
3002            [] => Err(SourceError::Refused {
3003                message: format!(
3004                    "source {} cannot resolve {}: found 0 matches",
3005                    self.name,
3006                    lookup.diagnostic()
3007                ),
3008            }),
3009            [node] => Ok(NativeId(backend_id(node, "id")?.to_owned())),
3010            nodes => {
3011                let ids = nodes
3012                    .iter()
3013                    .map(|node| backend_id(node, "id"))
3014                    .collect::<Result<Vec<_>, _>>()?;
3015                Err(SourceError::Refused {
3016                    message: format!(
3017                        "source {} cannot resolve {}: found {} matches with ids {ids:?}",
3018                        self.name,
3019                        lookup.diagnostic(),
3020                        nodes.len()
3021                    ),
3022                })
3023            }
3024        }
3025    }
3026
3027    /// What a status write resolves, as this instance holds it — read in one request the first
3028    /// time anything needs it, or again when `fresh` asks — and whether this call read it.
3029    ///
3030    /// Only an answer that read completely is held, so a failed or malformed read leaves the
3031    /// next call reading again rather than resolving against nothing.
3032    async fn vocabulary(
3033        &self,
3034        fresh: bool,
3035    ) -> Result<(std::sync::Arc<Vocabulary>, bool), SourceError> {
3036        if !fresh && let Some(held) = self.held_vocabulary() {
3037            return Ok((held, false));
3038        }
3039        let team = self.team.as_ref().ok_or_else(|| SourceError::Refused {
3040            message: format!(
3041                "source {} needs config.team before it can write a Linear item or a status",
3042                self.name
3043            ),
3044        })?;
3045        let data = self
3046            .send(graphql::RESOLUTION, json!({"key": team.0}))
3047            .await?;
3048        let read = std::sync::Arc::new(Vocabulary::read(&data, &self.name, &team.0)?);
3049        *self
3050            .vocabulary
3051            .lock()
3052            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(read.clone());
3053        if let Some(key) = self.shared_key() {
3054            shared::vocabularies().insert(key, read.clone());
3055        }
3056        Ok((read, true))
3057    }
3058
3059    fn held_vocabulary(&self) -> Option<std::sync::Arc<Vocabulary>> {
3060        let mut held = self
3061            .vocabulary
3062            .lock()
3063            .unwrap_or_else(std::sync::PoisonError::into_inner);
3064        if held.is_none() {
3065            // What another instance of this tracker in this process already read.
3066            *held = self
3067                .shared_key()
3068                .and_then(|key| shared::vocabularies().get(&key).cloned());
3069        }
3070        held.clone()
3071    }
3072
3073    /// The tracker this source reads: its endpoint and the workspace its API key belongs to,
3074    /// told apart by a digest of the key that never leaves this process — every hosted source
3075    /// shares one endpoint, and two workspaces may each have a team spelled the same.
3076    fn tracker(&self) -> String {
3077        use std::hash::{Hash as _, Hasher as _};
3078        let mut digest = std::collections::hash_map::DefaultHasher::new();
3079        self.key.expose_secret().hash(&mut digest);
3080        format!("{} {:016x}", self.endpoint.0, digest.finish())
3081    }
3082
3083    /// The key every instance of this source's tracker in this process shares what it reads of
3084    /// the team under: the tracker and the team — `None` for a source with no team, which
3085    /// resolves nothing.
3086    fn shared_key(&self) -> Option<(String, String)> {
3087        self.team
3088            .as_ref()
3089            .map(|team| (self.tracker(), team.0.clone()))
3090    }
3091
3092    /// Drop what this instance holds, after a write carrying one of its ids failed: the id may
3093    /// be what Linear refused, and the next write reads afresh rather than sending it again.
3094    fn forget_vocabulary(&self) {
3095        *self
3096            .vocabulary
3097            .lock()
3098            .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
3099        if let Some(key) = self.shared_key() {
3100            shared::vocabularies().remove(&key);
3101            shared::labels().retain(|(tracker, _, _), _| *tracker != key.0);
3102        }
3103    }
3104
3105    /// Hold one name `sources fields --apply` created beside the ones read, so the writes after
3106    /// it resolve it without another read.
3107    fn remember(&self, created: &Created) {
3108        let mut guard = self
3109            .vocabulary
3110            .lock()
3111            .unwrap_or_else(std::sync::PoisonError::into_inner);
3112        if let Some(vocabulary) = guard.as_mut() {
3113            std::sync::Arc::make_mut(vocabulary).add(created.clone());
3114            if let Some(key) = self.shared_key() {
3115                shared::vocabularies().insert(key, vocabulary.clone());
3116            }
3117        }
3118    }
3119
3120    async fn team_id(&self) -> Result<NativeId, SourceError> {
3121        Ok(self.vocabulary(false).await?.0.team.clone())
3122    }
3123
3124    /// The id and the name Linear holds of the name `category` is for `kind` — refused before
3125    /// any request when the mapping gives that kind no name for it, and refused naming the name
3126    /// when the kind's vocabulary lacks it even after one fresh read.
3127    async fn status_id(
3128        &self,
3129        category: StatusCategory,
3130        kind: ItemKind,
3131    ) -> Result<(NativeId, String), SourceError> {
3132        let name = self
3133            .statuses
3134            .name_for(category, kind)
3135            .map_err(|why| why.refusal(&self.name, category, kind))?;
3136        let (vocabulary, fresh) = self.vocabulary(false).await?;
3137        if let Some(held) = vocabulary.find(kind, name.as_str(), &self.name)? {
3138            return Ok((held.id.clone(), held.name.as_str().to_owned()));
3139        }
3140        if !fresh {
3141            let (vocabulary, _) = self.vocabulary(true).await?;
3142            if let Some(held) = vocabulary.find(kind, name.as_str(), &self.name)? {
3143                return Ok((held.id.clone(), held.name.as_str().to_owned()));
3144            }
3145        }
3146        let category_key = category_word(category);
3147        let kind_key = kind_word(kind);
3148        let held_by = match kind {
3149            ItemKind::Task => format!(
3150                "team {}",
3151                self.team.as_ref().map_or("(none)", |team| team.0.as_str())
3152            ),
3153            ItemKind::Project => "this workspace".to_owned(),
3154        };
3155        Err(SourceError::Refused {
3156            message: format!(
3157                "source {} maps the {kind_key} status {category_key} to the {} {:?}, which {held_by} \
3158                 does not have; next: run `onetaskgraph sources fields {} --apply` to create it, \
3159                 or point status_mapping.{category_key}.{kind_key} of this source at a {} \
3160                 {held_by} has",
3161                self.name,
3162                vocabulary_word(kind),
3163                name.as_str(),
3164                self.name,
3165                vocabulary_word(kind),
3166            ),
3167        })
3168    }
3169
3170    /// The ids of `labels`, each held for every instance of this tracker in this process once
3171    /// read, and every one not yet held read in one aliased request.
3172    async fn label_ids(
3173        &self,
3174        labels: &[Label],
3175        kind: WriteKind,
3176    ) -> Result<Vec<NativeId>, SourceError> {
3177        let tracker = self.tracker();
3178        let key = |name: &str| (tracker.clone(), kind, name.to_owned());
3179        let lookup = |name: &'_ str| match kind {
3180            WriteKind::Project => Lookup::ProjectLabel(name.to_owned()),
3181            WriteKind::Task => Lookup::IssueLabel(name.to_owned()),
3182        };
3183        let missing: Vec<&str> = {
3184            let held = shared::labels();
3185            let mut missing: Vec<&str> = Vec::new();
3186            for label in labels {
3187                if !held.contains_key(&key(&label.name)) && !missing.contains(&label.name.as_str())
3188                {
3189                    missing.push(label.name.as_str());
3190                }
3191            }
3192            missing
3193        };
3194        match missing.as_slice() {
3195            [] => {}
3196            [name] => {
3197                let id = self.one_id(lookup(name)).await?;
3198                shared::labels().insert(key(name), id);
3199            }
3200            names => {
3201                let lookups: Vec<Lookup> = names.iter().map(|name| lookup(name)).collect();
3202                let each: Vec<Value> = lookups.iter().map(Lookup::variables).collect();
3203                let single = lookups[0].query();
3204                let values = match self.send_aliased(single, &each).await? {
3205                    batch::Aliased::Answered(values) => values,
3206                    batch::Aliased::Refused(_, refusal) => return Err(refusal.into_error()),
3207                };
3208                for ((name, lookup), value) in names.iter().zip(&lookups).zip(values) {
3209                    let id = self.only_id(lookup, &json!({ lookup.connection(): value }))?;
3210                    shared::labels().insert(key(name), id);
3211                }
3212            }
3213        }
3214        let held = shared::labels();
3215        Ok(labels
3216            .iter()
3217            .filter_map(|label| held.get(&key(&label.name)).cloned())
3218            .collect())
3219    }
3220    fn write_description(
3221        &self,
3222        content: Option<&str>,
3223        metadata: &std::collections::BTreeMap<String, Value>,
3224        repositories: &[Repository],
3225        classification: Classification,
3226        edges: &[DependencyEdge],
3227        kind: WriteKind,
3228    ) -> Result<Option<String>, SourceError> {
3229        Self::long_form(
3230            content,
3231            metadata,
3232            repositories,
3233            classification,
3234            self.recorded_ends(edges, kind),
3235        )
3236    }
3237
3238    /// The far ends of `edges` no relation of this workspace can name — another level, or
3239    /// another source — as the reserved key records them.
3240    fn recorded_ends(&self, edges: &[DependencyEdge], kind: WriteKind) -> Vec<Value> {
3241        edges
3242            .iter()
3243            .filter(|edge| {
3244                edge.to.kind
3245                    != match kind {
3246                        WriteKind::Task => ItemKind::Task,
3247                        WriteKind::Project => ItemKind::Project,
3248                    }
3249                    || edge.to.designator().is_some()
3250                    || edge
3251                        .to
3252                        .id()
3253                        .split_once(':')
3254                        .is_some_and(|(source, _)| source != self.name.as_str())
3255            })
3256            .map(|edge| serde_json::to_value(&edge.to).expect("an endpoint renders as JSON"))
3257            .collect()
3258    }
3259
3260    /// Every forward edge `id` holds, relations and recorded far ends alike, walked to
3261    /// exhaustion.
3262    async fn forward_edges(&self, id: &NativeId) -> Result<Vec<DependencyEdge>, SourceError> {
3263        let mut edges = Vec::new();
3264        let mut cursor = None;
3265        loop {
3266            // The plain document even with the cache attached: a write's own read of the edges
3267            // it replaces fills no entry.
3268            let page = self
3269                .dependencies(
3270                    graphql::ISSUE_DEPENDS_ON,
3271                    DependencyRoot::Issue,
3272                    id,
3273                    Direction::DependsOn,
3274                    &PageRequest {
3275                        cursor,
3276                        limit: MAX_PAGE_SIZE,
3277                    },
3278                )
3279                .await?;
3280            edges.extend(page.items);
3281            match page.next {
3282                Some(next) => cursor = Some(next),
3283                None => return Ok(edges),
3284            }
3285        }
3286    }
3287
3288    /// Apply one targeted update to one issue; see [`TaskSource::update_task`].
3289    ///
3290    /// **An update naming a status and nothing else reads nothing first:** it is one
3291    /// `issueUpdate` carrying the `stateId` its category's task name resolves to, whose own
3292    /// selection answers the task — see [`Self::status_written`]. Writing a category the issue
3293    /// already reads as therefore sends the same state again, and an issue at a name the
3294    /// mapping does not name, which reads as `unknown`, moves to the mapped `unknown` name.
3295    ///
3296    /// **Any other update reads the issue once**, then sends one `issueUpdate` carrying only
3297    /// the members that differ from it — `title`, `description` (content and metadata slot
3298    /// together), `stateId`, `priority` — and, when the named edges differ from the ones the
3299    /// issue holds, its relations replaced. The read is what the description is merged from:
3300    /// Linear has no conditional update, so writing the metadata slot without it would
3301    /// overwrite whatever a person wrote there since. Nothing is sent for a field already
3302    /// holding the requested value, and nothing at all when nothing differs. `delivers` lands
3303    /// in the metadata slot under its reserved key, as a copy writes it.
3304    ///
3305    /// Either way the task answered is the one the mutation's own selection reports, so its
3306    /// status is Linear's, and nothing is read after the write.
3307    /// The `issueUpdate` input that applies `update` to the issue `before` holds, whose raw
3308    /// description is `description` — empty when nothing differs — and the relations it is to
3309    /// write after, when it names dependencies that differ. Nothing is sent but the reads of
3310    /// its forward edges such an update needs.
3311    async fn compose_update(
3312        &self,
3313        update: &TaskUpdate,
3314        before: Task,
3315        description: Option<String>,
3316    ) -> Result<Composed, SourceError> {
3317        let (visible, held) = metadata_description(description)?;
3318        let mut slot = held.clone();
3319        for (key, value) in &update.metadata_set {
3320            slot.insert(key.as_str().to_owned(), value.clone());
3321        }
3322        for key in &update.metadata_remove {
3323            slot.remove(key.as_str());
3324        }
3325        if let Some(delivers) = &update.delivers {
3326            set_task_list(&mut slot, TaskRef::DELIVERS_KEY, delivers);
3327        }
3328        // Recorded exactly as a whole write records it: none for an empty list.
3329        if let Some(repositories) = &update.repositories {
3330            if repositories.is_empty() {
3331                slot.remove(Repository::METADATA_KEY);
3332            } else {
3333                slot.insert(Repository::METADATA_KEY.into(), json!(repositories));
3334            }
3335        }
3336        let mut relations = None;
3337        if let Some(wanted) = &update.depends_on {
3338            let current = self.forward_edges(&before.id).await?;
3339            let ends = |edges: &[DependencyEdge]| {
3340                let mut ends: Vec<(String, String)> = edges
3341                    .iter()
3342                    .map(|edge| {
3343                        (
3344                            edge.to.id().to_owned(),
3345                            format!("{:?}{:?}", edge.to.kind, edge.kind),
3346                        )
3347                    })
3348                    .collect();
3349                ends.sort();
3350                ends
3351            };
3352            if ends(&current) != ends(wanted) {
3353                let prepared = self.prepare_edges(wanted, WriteKind::Task).await?;
3354                let recorded = self.recorded_ends(&prepared, WriteKind::Task);
3355                if recorded.is_empty() {
3356                    slot.remove(DependencyEdge::RECORDED_KEY);
3357                } else {
3358                    slot.insert(DependencyEdge::RECORDED_KEY.into(), Value::Array(recorded));
3359                }
3360                relations = Some(prepared);
3361            }
3362        }
3363        let mut input = serde_json::Map::new();
3364        if let Some(title) = update
3365            .title
3366            .as_ref()
3367            .filter(|title| **title != before.title)
3368        {
3369            input.insert("title".into(), json!(title));
3370        }
3371        // A content write keeps the task's `## Links` section, re-rendered from the links the
3372        // slot holds once written.
3373        let relinked = update
3374            .content
3375            .as_deref()
3376            .map(|content| onetaskgraph_plugin_api::relinked(content, visible.as_deref(), &slot));
3377        let content = relinked.as_deref().or(visible.as_deref());
3378        if content != visible.as_deref() || slot != held {
3379            let written = Self::described(content, &slot)?;
3380            // Checked before anything is sent: content ending in what this source reads as
3381            // its own slot would read back as metadata rather than as the content it was.
3382            let (reads, read) = metadata_description(written.clone())?;
3383            if reads.as_deref().unwrap_or_default() != content.unwrap_or_default() || read != slot {
3384                return Err(SourceError::Refused {
3385                    message: format!(
3386                        "this content would read back from source {} as something other than \
3387                         itself, or ends in what it reads as its own metadata slot; next: change \
3388                         how the content ends",
3389                        self.name
3390                    ),
3391                });
3392            }
3393            input.insert("description".into(), json!(written));
3394        }
3395        if let Some(status) = update
3396            .status
3397            .as_ref()
3398            .filter(|status| status.category != before.status.category)
3399        {
3400            let (state, _) = self.status_id(status.category, ItemKind::Task).await?;
3401            input.insert("stateId".into(), json!(state.0));
3402        }
3403        if let Some(priority) = update
3404            .priority
3405            .filter(|priority| *priority != before.priority)
3406        {
3407            input.insert("priority".into(), json!(linear_priority(priority)));
3408        }
3409        Ok(Composed {
3410            before,
3411            input,
3412            relations,
3413        })
3414    }
3415
3416    async fn targeted_update(
3417        &self,
3418        id: &NativeId,
3419        update: &TaskUpdate,
3420    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
3421        self.update_checked(id, update)?;
3422        if let Some(status) = update.status.as_ref().filter(|_| {
3423            TaskUpdate {
3424                status: None,
3425                ..update.clone()
3426            }
3427            .is_empty()
3428        }) {
3429            let Some(task) = self.status_written(id, status.category).await? else {
3430                return Ok(None);
3431            };
3432            return Ok(Some(TaskUpdateOutcome {
3433                delivers_before: task.delivers.clone(),
3434                written: std::iter::once(UpdatedField::Status).collect(),
3435                task,
3436            }));
3437        }
3438        let held = if update.status.is_some() && self.held_vocabulary().is_none() {
3439            self.issue_resolving(id).await?
3440        } else {
3441            self.issue_held(id, Read::ForWrite).await?
3442        };
3443        let Some((before, description)) = held else {
3444            return Ok(None);
3445        };
3446        let composed = self.compose_update(update, before, description).await?;
3447        self.send_composed(id, update, composed).await
3448    }
3449
3450    /// Refuse, before any request, an update that contradicts itself, a `delivers` list naming
3451    /// what a task cannot deliver, and a category the mapping gives a task no name for — none of
3452    /// which Linear could answer differently for another issue.
3453    fn update_checked(&self, id: &NativeId, update: &TaskUpdate) -> Result<(), SourceError> {
3454        update.consistent()?;
3455        if let Some(delivers) = &update.delivers {
3456            TaskRef::listed(
3457                TaskRef::DELIVERS_KEY,
3458                id,
3459                Some(&self.name),
3460                delivers.clone(),
3461            )
3462            .map_err(|message| SourceError::Refused { message })?;
3463        }
3464        if let Some(status) = &update.status {
3465            self.statuses
3466                .name_for(status.category, ItemKind::Task)
3467                .map_err(|why| why.refusal(&self.name, status.category, ItemKind::Task))?;
3468        }
3469        Ok(())
3470    }
3471
3472    /// Send one composed update alone — its `issueUpdate` when anything differs, then the
3473    /// relations it writes — and answer what `update_task` answers.
3474    async fn send_composed(
3475        &self,
3476        id: &NativeId,
3477        update: &TaskUpdate,
3478        composed: Composed,
3479    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
3480        let Composed {
3481            before,
3482            input,
3483            relations,
3484        } = composed;
3485        let carries_state = input.contains_key("stateId");
3486        let task = if input.is_empty() {
3487            before.clone()
3488        } else {
3489            let answered = self
3490                .send(
3491                    graphql::ISSUE_UPDATE_READ,
3492                    json!({"id":before.id.0,"input":Value::Object(input)}),
3493                )
3494                .await
3495                .and_then(|data| self.updated_issue(&data, &before.id));
3496            match answered {
3497                Ok(Some(task)) => task,
3498                Ok(None) => {
3499                    return Err(SourceError::Malformed {
3500                        message: format!("task {id} was updated and then answered as no issue"),
3501                    });
3502                }
3503                Err(error) => {
3504                    if carries_state {
3505                        self.forget_vocabulary();
3506                    }
3507                    return Err(error);
3508                }
3509            }
3510        };
3511        if let Some(prepared) = &relations {
3512            self.write_relations(&before.id, prepared, WriteKind::Task, HeldRelations::Unread)
3513                .await?;
3514        }
3515        let mut written = update.changed(&before, &task);
3516        if relations.is_some() {
3517            written.insert(UpdatedField::DependsOn);
3518        }
3519        Ok(Some(TaskUpdateOutcome {
3520            task,
3521            written,
3522            delivers_before: before.delivers,
3523        }))
3524    }
3525
3526    /// Set one issue's state to the one `category`'s task name resolves to, in one
3527    /// `issueUpdate` whose selection answers the task as Linear now holds it — or `None` when
3528    /// Linear holds no such issue, which it says by refusing the mutation as naming nothing.
3529    ///
3530    /// No read before it, so this is the whole of a status write's cost once the resolution is
3531    /// held: one request — for a source scoped to one project as well. A status write goes to
3532    /// the issue it names wherever that issue is filed, because the item is named outright and
3533    /// the scope governs what this source reads, lists and creates, not where a status it is
3534    /// asked to set may land.
3535    async fn status_written(
3536        &self,
3537        id: &NativeId,
3538        category: StatusCategory,
3539    ) -> Result<Option<Task>, SourceError> {
3540        let (state, _) = self.status_id(category, ItemKind::Task).await?;
3541        let target = id.clone();
3542        // `stateId` alone, so nothing else about the issue can move: Linear's
3543        // `IssueUpdateInput` makes every member optional and leaves an absent one as it was.
3544        let answered = self
3545            .send_to_held(
3546                graphql::ISSUE_UPDATE_READ,
3547                json!({"id":target.0,"input":{"stateId":state.0}}),
3548            )
3549            .await;
3550        match answered {
3551            Ok(Some(data)) => self.updated_issue(&data, &target),
3552            Ok(None) => Ok(None),
3553            Err(error) => {
3554                self.forget_vocabulary();
3555                Err(error)
3556            }
3557        }
3558    }
3559
3560    /// The task an `issueUpdate` sent as [`graphql::ISSUE_UPDATE_READ`] answered with — `None`
3561    /// for an issue in the trash, on the terms a read by id answers — refusing an answer about
3562    /// another issue than the one asked for.
3563    ///
3564    /// Not narrowed to this source's scope: the issue was named outright and has been written,
3565    /// so it is answered wherever it is filed.
3566    ///
3567    /// `asked` may be the backend id or the identifier (`ENG-1`), because Linear takes either.
3568    fn updated_issue(&self, data: &Value, asked: &NativeId) -> Result<Option<Task>, SourceError> {
3569        // A write of the issue lets go of what an earlier one answered.
3570        self.take_written(MetadataRecord::Task, asked);
3571        let issue = mutation_payload(data, MutationRoot::IssueUpdate)?
3572            .get("issue")
3573            .filter(|issue| !issue.is_null())
3574            .ok_or_else(|| SourceError::Malformed {
3575                message: "missing issueUpdate.issue".into(),
3576            })?;
3577        if optional_str(issue, "identifier")? != Some(asked.0.as_str()) {
3578            written_is(issue, asked)?;
3579        }
3580        self.remember_context(asked, issue);
3581        let task = optional(&json!({ "issue": issue }), "issue", |v| {
3582            map_task(v, &self.name, &self.statuses, self.spelling())
3583        })?;
3584        if let Some(task) = &task {
3585            self.answered().insert(
3586                (MetadataRecord::Task, asked.clone()),
3587                Answered {
3588                    version: task.version.clone(),
3589                    task: Some(task.clone()),
3590                },
3591            );
3592        }
3593        Ok(task)
3594    }
3595
3596    /// The one long-form field a Linear item has, with this source's own slot at the end.
3597    ///
3598    /// Shared by every kind this source writes rather than reimplemented per kind: a
3599    /// document keeps caller metadata in exactly the slot an issue and a project do, which
3600    /// is what lets the same read side take it back out.
3601    fn long_form(
3602        content: Option<&str>,
3603        metadata: &std::collections::BTreeMap<String, Value>,
3604        repositories: &[Repository],
3605        classification: Classification,
3606        recorded: Vec<Value>,
3607    ) -> Result<Option<String>, SourceError> {
3608        let mut metadata = metadata.clone();
3609        classification.record(&mut metadata);
3610        if repositories.is_empty() {
3611            metadata.remove(Repository::METADATA_KEY);
3612        } else {
3613            metadata.insert(Repository::METADATA_KEY.into(), json!(repositories));
3614        }
3615        if recorded.is_empty() {
3616            metadata.remove(DependencyEdge::RECORDED_KEY);
3617        } else {
3618            metadata.insert(DependencyEdge::RECORDED_KEY.into(), Value::Array(recorded));
3619        }
3620        Self::described(content, &metadata)
3621    }
3622
3623    /// The long-form field holding `content` and a slot of exactly `metadata`, in the one
3624    /// encoding [`long_form`](Self::long_form) writes: the content alone when there is no
3625    /// metadata, and otherwise the slot after one blank line.
3626    fn described(
3627        content: Option<&str>,
3628        metadata: &std::collections::BTreeMap<String, Value>,
3629    ) -> Result<Option<String>, SourceError> {
3630        let visible = content.unwrap_or_default();
3631        if metadata.is_empty() {
3632            return Ok((!visible.is_empty()).then(|| visible.to_owned()));
3633        }
3634        let slot = slot_text(metadata)?;
3635        Ok(Some(if visible.is_empty() {
3636            slot
3637        } else {
3638            format!("{visible}\n\n{slot}")
3639        }))
3640    }
3641    /// What this source says when asked for a project edge carrying no ordering.
3642    ///
3643    /// Linear's project relations have exactly one type and it is an ordering. Asked on
3644    /// 2026-09-04 to create one typed `related` — and separately `blocks` and `dependsOn`
3645    /// — the real API refused each with `Argument Validation Error` and
3646    /// `constraints: {"isEnum": "type must be one of the following values: dependency"}`.
3647    /// That is Linear's own enumeration of the field, from the validator behind GraphQL
3648    /// where introspection cannot reach it, and it has one member. An issue relation is a
3649    /// different relation with a different set, which does include `related`, so this
3650    /// reaches projects alone.
3651    fn unordered_project_relation(&self, near: &NativeId, far: &str) -> SourceError {
3652        SourceError::Refused {
3653            message: format!(
3654                "source {} cannot carry an unordered dependency between projects, because \
3655                 Linear types every project relation `dependency` and that is an ordering; \
3656                 record {near} to {far} as a dependency, or between tasks",
3657                self.name,
3658                near = near.0,
3659            ),
3660        }
3661    }
3662    /// The one edge [`Self::unordered_project_relation`] refuses, if there is one here.
3663    fn unordered_project_edge(edges: &[DependencyEdge]) -> Option<&DependencyEdge> {
3664        edges
3665            .iter()
3666            .find(|edge| edge.to.kind == ItemKind::Project && edge.kind == DependencyKind::Related)
3667    }
3668    /// Set the relations `near` holds of `kind` to exactly `edges`. Matching issue relations
3669    /// are retained; obsolete relations are deleted and missing ones created.
3670    ///
3671    /// `held` is what is already known of the ones it holds: none, for an item the write this
3672    /// follows created; the first page of them, for one a rewrite's own answer reported; and
3673    /// otherwise nothing, so they are read. Only a page that says there are more is followed.
3674    async fn write_relations(
3675        &self,
3676        near: &NativeId,
3677        edges: &[DependencyEdge],
3678        kind: WriteKind,
3679        held: HeldRelations<'_>,
3680    ) -> Result<(), SourceError> {
3681        let wanted: std::collections::BTreeSet<_> = edges
3682            .iter()
3683            .filter(|_| matches!(kind, WriteKind::Task))
3684            .filter_map(|edge| {
3685                self.relation_target(edge, kind)
3686                    .map(|far| (far.to_owned(), issue_relation_type(edge.kind).to_owned()))
3687            })
3688            .collect();
3689        let mut kept = std::collections::BTreeSet::new();
3690        let mut cursor: Option<Cursor> = None;
3691        // A created issue holds no relation to reconcile, so its creates may wait for the
3692        // copy's `finish_writes` and go with every other's in one request.
3693        let deferred = matches!(held, HeldRelations::None)
3694            && matches!(kind, WriteKind::Task)
3695            && self.deferring.load(std::sync::atomic::Ordering::SeqCst);
3696        // The `related` relations mirroring a link the item holds, which no dependency write
3697        // takes away: read off the long form beside the relations wherever it was read.
3698        let mut mirrors = std::collections::BTreeSet::new();
3699        let mut answered = match held {
3700            HeldRelations::None => None,
3701            HeldRelations::Page(issue) => {
3702                mirrors = self.mirrored_in(issue.get("description").and_then(Value::as_str))?;
3703                Some(issue["relations"].clone())
3704            }
3705            HeldRelations::Unread => Some(Value::Null),
3706        };
3707        while let Some(page) = answered.take() {
3708            let relations = if page.is_null() {
3709                let data = self
3710                    .send(
3711                        // The plain documents even with the cache attached: this read neither fills
3712                        // an entry nor pins a read, so the token's parts would only add complexity.
3713                        if matches!(kind, WriteKind::Project) {
3714                            PROJECT_RELATIONS
3715                        } else {
3716                            ISSUE_RELATIONS
3717                        },
3718                        json!({"id":near.0,"first":MAX_PAGE_SIZE,"after":cursor.as_ref().map(|cursor|&cursor.0)}),
3719                    )
3720                    .await?;
3721                let root = data
3722                    .get(if matches!(kind, WriteKind::Project) {
3723                        "project"
3724                    } else {
3725                        "issue"
3726                    })
3727                    .ok_or_else(|| SourceError::Malformed {
3728                        message: "missing relation item".into(),
3729                    })?;
3730                if matches!(kind, WriteKind::Task) {
3731                    mirrors
3732                        .extend(self.mirrored_in(root.get("description").and_then(Value::as_str))?);
3733                }
3734                root.get("relations")
3735                    .cloned()
3736                    .ok_or_else(|| SourceError::Malformed {
3737                        message: "missing relations".into(),
3738                    })?
3739            } else {
3740                page
3741            };
3742            for relation in relations
3743                .get("nodes")
3744                .and_then(Value::as_array)
3745                .ok_or_else(|| SourceError::Malformed {
3746                    message: "missing relations.nodes".into(),
3747                })?
3748            {
3749                let id = backend_id(relation, "id")?;
3750                if !mirrors.is_empty()
3751                    && str_at(relation, "type")? == relations::MIRRORED
3752                    && backend_id(&relation["relatedIssue"], "id")
3753                        .is_ok_and(|far| mirrors.contains(far))
3754                {
3755                    continue;
3756                }
3757                if !wanted.is_empty() {
3758                    let far = backend_id(&relation["relatedIssue"], "id")?;
3759                    let relation_type = str_at(relation, "type")?;
3760                    let key = (far.to_owned(), relation_type.to_owned());
3761                    if wanted.contains(&key) {
3762                        kept.insert(key);
3763                        continue;
3764                    }
3765                }
3766                let (query, mutation) = if matches!(kind, WriteKind::Project) {
3767                    (
3768                        graphql::PROJECT_RELATION_DELETE,
3769                        MutationRoot::ProjectRelationDelete,
3770                    )
3771                } else {
3772                    (
3773                        graphql::ISSUE_RELATION_DELETE,
3774                        MutationRoot::IssueRelationDelete,
3775                    )
3776                };
3777                let deleted = self.send(query, json!({"id":id})).await?;
3778                mutation_payload(&deleted, mutation)?;
3779                self.unknown_version(near);
3780            }
3781            if let Some(next) = page_next(&relations)? {
3782                cursor = Some(next);
3783                answered = Some(Value::Null);
3784            }
3785        }
3786        // Linear requires an anchor at each end of a project relation and validates both
3787        // against an enum GraphQL cannot see: `ProjectRelationCreateInput` declares them
3788        // `String!` and enumerates nothing, and the field descriptions read as a choice
3789        // between the project and a milestone, which is not what they are. Linear's own
3790        // refusal enumerates them — sent `project` in both, it answered `anchorType must
3791        // be one of the following values: start, end, milestone` — and `milestone` needs
3792        // an id this source never sends, so the two whole-project anchors are the whole of
3793        // what it can send.
3794        //
3795        // **Which of them goes where carries the direction, and the two id slots do not.**
3796        // Linear stores whatever pair it is given and reads a backwards dependency as
3797        // readily as the right one, so acceptance settles nothing; what does is Linear's
3798        // own reading of a stored relation, published as the computed `ProjectFilter`
3799        // members `hasBlockingRelations` ("projects which are blocking") and
3800        // `hasBlockedByRelations` ("projects which are blocked"). Three relations between
3801        // two scratch projects, read back through them on 2026-09-04:
3802        //
3803        // | `projectId` | `anchorType` | `relatedProjectId` | `relatedAnchorType` | blocked | blocking |
3804        // | ----------- | ------------ | ------------------ | ------------------- | ------- | -------- |
3805        // | A           | `start`      | B                  | `end`               | A       | B        |
3806        // | A           | `end`        | B                  | `start`             | B       | A        |
3807        // | B           | `end`        | A                  | `start`             | A       | B        |
3808        //
3809        // Rows one and three exchange the ids and the anchors together and read alike;
3810        // rows one and two exchange only the anchors and the reading flips. So the project
3811        // anchored `start` is the one that waits, whichever slot it sits in, and row one is
3812        // what this source sends — `near`, the item that depends, in `projectId`. Linear's
3813        // own callers put the blocker there instead, so copying their `end`/`start` pair
3814        // across by position would state every dependency backwards in the workspace, and
3815        // nothing would refuse it.
3816        const NEAR_ANCHOR: &str = "start";
3817        const FAR_ANCHOR: &str = "end";
3818        for edge in edges {
3819            let Some(far) = self.relation_target(edge, kind) else {
3820                continue;
3821            };
3822            if matches!(kind, WriteKind::Task)
3823                && kept.contains(&(far.to_owned(), issue_relation_type(edge.kind).to_owned()))
3824            {
3825                continue;
3826            }
3827            // A project relation is not spelled the way an issue relation is, and this is
3828            // the whole of what a project's `type` may say.
3829            //
3830            // `blocks` there is what the live journey's project write was refused for
3831            // once the two anchors above stopped being missing: Linear answered HTTP 200
3832            // with `Argument Validation Error`, the message class its input validator
3833            // raises for a value outside an accepted set, having already accepted every
3834            // field of the same input by name — which is what tells that refusal apart
3835            // from the missing-field one before it, and what says the anchors were not the
3836            // cause.
3837            //
3838            // Which field, and what it takes, was measured against the real API on
3839            // 2026-09-04 rather than inferred. Each of `blocks`, `dependsOn`, `related`
3840            // and `DEPENDENCY` was refused with `property: "type"` and
3841            // `constraints: {"isEnum": "type must be one of the following values:
3842            // dependency"}`; `dependency` was accepted. That enumeration, like the
3843            // anchors' above, reaches this source through the validator's `extensions`;
3844            // see `GqlError::said`.
3845            //
3846            // A `Related` project edge is refused at the top of this function by that same
3847            // enumeration: it has one member and it is an ordering. An issue relation is a
3848            // different relation with a different set, which does include `related`.
3849            let relation_type = match (kind, edge.kind) {
3850                (WriteKind::Project, DependencyKind::Blocks) => "dependency",
3851                (WriteKind::Task, dependency) => issue_relation_type(dependency),
3852                // Unreachable past `write_project`'s guard, and an error rather than a
3853                // skip so it stays that way: an edge dropped here would be a copy
3854                // reporting success for a dependency the destination does not hold.
3855                (WriteKind::Project, DependencyKind::Related) => {
3856                    return Err(self.unordered_project_relation(near, edge.to.id()));
3857                }
3858            };
3859            let (query, input) = if matches!(kind, WriteKind::Project) {
3860                (
3861                    graphql::PROJECT_RELATION_CREATE,
3862                    json!({"projectId":near.0,"relatedProjectId":far,"type":relation_type,"anchorType":NEAR_ANCHOR,"relatedAnchorType":FAR_ANCHOR}),
3863                )
3864            } else {
3865                (
3866                    graphql::ISSUE_RELATION_CREATE,
3867                    json!({"issueId":near.0,"relatedIssueId":far,"type":relation_type}),
3868                )
3869            };
3870            if deferred {
3871                self.deferred_relations
3872                    .lock()
3873                    .unwrap_or_else(std::sync::PoisonError::into_inner)
3874                    .push((near.clone(), json!({"input": input})));
3875                continue;
3876            }
3877            let data = self.send(query, json!({"input":input})).await?;
3878            self.unknown_version(near);
3879            let mutation = if matches!(kind, WriteKind::Project) {
3880                MutationRoot::ProjectRelationCreate
3881            } else {
3882                MutationRoot::IssueRelationCreate
3883            };
3884            let payload = mutation_payload(&data, mutation)?;
3885            let relation = payload
3886                .get(if matches!(kind, WriteKind::Project) {
3887                    "projectRelation"
3888                } else {
3889                    "issueRelation"
3890                })
3891                .ok_or_else(|| SourceError::Malformed {
3892                    message: format!("missing {} relation", mutation.as_str()),
3893                })?;
3894            backend_id(relation, "id")?;
3895        }
3896        Ok(())
3897    }
3898
3899    /// A native endpoint a Linear relation can hold, with this source's qualifier removed.
3900    fn relation_target<'a>(&self, edge: &'a DependencyEdge, kind: WriteKind) -> Option<&'a str> {
3901        let expected = match kind {
3902            WriteKind::Task => ItemKind::Task,
3903            WriteKind::Project => ItemKind::Project,
3904        };
3905        if edge.to.kind != expected || edge.to.designator().is_some() {
3906            return None;
3907        }
3908        match edge.to.id().split_once(':') {
3909            Some((source, native)) if source == self.name.as_str() => Some(native),
3910            Some(_) => None,
3911            None => Some(edge.to.id()),
3912        }
3913    }
3914
3915    async fn prepare_edges(
3916        &self,
3917        edges: &[DependencyEdge],
3918        kind: WriteKind,
3919    ) -> Result<Vec<DependencyEdge>, SourceError> {
3920        let mut prepared = Vec::with_capacity(edges.len());
3921        for edge in edges {
3922            let mut edge = edge.clone();
3923            if edge.to.kind
3924                == match kind {
3925                    WriteKind::Task => ItemKind::Task,
3926                    WriteKind::Project => ItemKind::Project,
3927                }
3928                && edge
3929                    .to
3930                    .id()
3931                    .split_once(':')
3932                    .is_some_and(|(source, _)| source != self.name.as_str())
3933            {
3934                // Narrowed to what this source holds — its team, and its project when it is
3935                // scoped to one — and, for an issue, to the ones whose description carries
3936                // the far end as its origin: a copy of the far end is an item of this source,
3937                // and an item of another team or project carrying the same origin is not one
3938                // this source could relate. The origin is confirmed over the parsed slot below.
3939                let filter = match kind {
3940                    WriteKind::Project => Self::narrowed(self.project_scope()),
3941                    WriteKind::Task => {
3942                        let mut parts = self.issue_scope();
3943                        parts.extend(slot_phrase(edge.to.id()));
3944                        Self::narrowed(parts)
3945                    }
3946                };
3947                let mut cursor: Option<Cursor> = None;
3948                loop {
3949                    // The plain document even with the cache attached: this scan neither fills
3950                    // an entry nor pins a read, so the relations page would only add complexity.
3951                    let data = self.send(if matches!(kind, WriteKind::Project) { PROJECTS } else { ISSUES }, json!({"first":MAX_PAGE_SIZE,"after":cursor.as_ref().map(|cursor|&cursor.0),"filter":filter})).await?;
3952                    let (items, next) = if matches!(kind, WriteKind::Project) {
3953                        let page = connection(&data, "projects", |v| {
3954                            map_project(v, &self.statuses, self.spelling())
3955                        })?;
3956                        (
3957                            page.items
3958                                .into_iter()
3959                                .map(|item| (item.id, item.metadata))
3960                                .collect::<Vec<_>>(),
3961                            page.next,
3962                        )
3963                    } else {
3964                        let page = connection(&data, "issues", |v| {
3965                            map_task(v, &self.name, &self.statuses, self.spelling())
3966                        })?;
3967                        (
3968                            page.items
3969                                .into_iter()
3970                                .map(|item| (item.id, item.metadata))
3971                                .collect::<Vec<_>>(),
3972                            page.next,
3973                        )
3974                    };
3975                    if let Some((id, _)) = items.into_iter().find(|(_, metadata)| {
3976                        metadata.get("onetaskgraph.origin").and_then(Value::as_str)
3977                            == Some(edge.to.id())
3978                    }) {
3979                        edge.to = DependencyEndpoint::from_native(id, edge.to.kind);
3980                        break;
3981                    }
3982                    let Some(next) = next else { break };
3983                    cursor = Some(next);
3984                }
3985            }
3986            prepared.push(edge);
3987        }
3988        Ok(prepared)
3989    }
3990}
3991
3992/// Why a Linear task's token does not vouch for its comments while no cache is attached.
3993const COMMENTS_UNATTACHED: &str = "a linear issue's updatedAt moved for none of a comment added, \
3994     edited or deleted (0 of 3 in spike-linear-coverage), so its token vouches for its comments \
3995     only once the cache attaches the comments page its comments part is read from";
3996
3997/// Why a Linear task's token does not vouch for its forward edges while no cache is attached.
3998const EDGES_UNATTACHED: &str = "a linear issue's relations moved no part of its token \
3999     (spike-linear-coverage) until the cache attaches the relations page its token is read from";
4000
4001/// Why a Linear task's token does not vouch for its reverse edges while no cache is attached.
4002const REVERSE_EDGES_UNATTACHED: &str = "a relation another linear issue records with this one \
4003     moves no part of this issue's token until the cache attaches the inverse relations page its \
4004     inverse part is read from";
4005
4006/// Why a Linear project's token does not vouch for its reverse edges while no cache is attached.
4007const PROJECT_REVERSE_EDGES_UNATTACHED: &str = "a linear project's updatedAt moved for 0 of 2 \
4008     relation changes another project made with it (spike-linear-coverage), so its token vouches \
4009     for its reverse edges only once the cache attaches the inverse relations page its inverse \
4010     part is read from";
4011
4012/// Why a Linear project's token does not vouch for its forward edges while no cache is attached.
4013const PROJECT_EDGES_UNATTACHED: &str = "a linear project's updatedAt moved for 0 of 2 relation \
4014     changes (spike-linear-coverage), so its token vouches for its forward edges only once the \
4015     cache attaches the relations page its relations part is read from";
4016
4017/// Why a Linear document's token does not vouch for its assets.
4018const DOCUMENT_ASSETS_UNCOVERED: &str =
4019    "linear's asset reads send no request, so there is nothing for a cache to save";
4020
4021/// What `write_or_queue` did with one task write.
4022pub(crate) enum Landed {
4023    /// It was written, and the issue is held under this id.
4024    At(NativeId),
4025    /// It was composed and queued for the `write_tasks` gathering it; nothing was sent.
4026    Queued,
4027}
4028
4029impl LinearSource {
4030    /// [`TaskSource::write_task`], or — while `write_tasks` gathers creates — the create
4031    /// composed and queued for it.
4032    pub(crate) async fn write_or_queue(
4033        &self,
4034        write: &ItemWrite<Task>,
4035    ) -> Result<Landed, SourceError> {
4036        // Before anything is read or written, because nothing Linear could answer changes
4037        // either: neither list may name the task itself or name one task twice, a category
4038        // this source has disabled is refused in the words a status write is refused with,
4039        // and a project other than the one this source is scoped to is refused naming both.
4040        let near = write.target.as_ref().unwrap_or(&write.item.id);
4041        for (key, entries) in [
4042            (TaskRef::DELIVERS_KEY, &write.item.delivers),
4043            (TaskRef::DELIVERED_BY_KEY, &write.item.delivered_by),
4044        ] {
4045            TaskRef::listed(key, near, Some(&self.name), entries.clone())
4046                .map_err(|message| SourceError::Refused { message })?;
4047        }
4048        let project = self.filed_in(write.item.project.as_ref(), "task")?;
4049        // The status is resolved before anything else is sent: a category the mapping gives a
4050        // task no name for is refused before any request, and a name the team lacks before any
4051        // mutation. The mapping decides alone; the status's own name plays no part.
4052        let (state, _) = self
4053            .status_id(write.item.status.category, ItemKind::Task)
4054            .await?;
4055        let edges = self
4056            .prepare_edges(&write.depends_on, WriteKind::Task)
4057            .await?;
4058        let team = self.team_id().await?;
4059        let labels = self.label_ids(&write.item.labels, WriteKind::Task).await?;
4060        // The typed lists are what land, whatever the caller's own metadata held under their
4061        // keys: a key of either name travelling beside the field would be a second answer to
4062        // the same question, and the field is the one the contract names.
4063        let mut metadata = write.item.metadata.clone();
4064        // A create's key is the issue's own id here, and stays in its slot as every source keeps
4065        // it, so a later copy reads the issue as the one it wrote.
4066        let create_id = self.create_id(MetadataRecord::Task, &metadata, write.target.as_ref())?;
4067        set_task_list(&mut metadata, TaskRef::DELIVERS_KEY, &write.item.delivers);
4068        set_task_list(
4069            &mut metadata,
4070            TaskRef::DELIVERED_BY_KEY,
4071            &write.item.delivered_by,
4072        );
4073        // A linked task keeps its `## Links` section, each line rendered from its links: the
4074        // write holds no stored description to keep the other ends' titles from, and reading
4075        // one would cost every write a request.
4076        let content = write
4077            .item
4078            .content
4079            .as_deref()
4080            .map(|content| onetaskgraph_plugin_api::relinked(content, None, &metadata));
4081        let description = self.write_description(
4082            content.as_deref(),
4083            &metadata,
4084            &write.item.repositories,
4085            write.item.classification,
4086            &edges,
4087            WriteKind::Task,
4088        )?;
4089        // `priority` on a create and on an update alike, `0` included: an update that left
4090        // it out would keep whatever the destination held, so a copy moving an issue back to
4091        // no priority would report success for a priority the destination still carries.
4092        let input = json!({"title":write.item.title,"description":description,"stateId":state,"priority":linear_priority(write.item.priority),"labelIds":labels,"projectId":project});
4093        // The write a copy makes of an issue it has just created together with others, saying
4094        // exactly what that create wrote and naming no edge, writes nothing: what Linear answered
4095        // the create stands as this write's answer.
4096        if let Some(id) = &write.target
4097            && edges.is_empty()
4098            && self.just_created_as(id, &input)?
4099        {
4100            return Ok(Landed::At(id.clone()));
4101        }
4102        let sent_input = input.clone();
4103        if write.target.is_none()
4104            && self
4105                .deferring_creates
4106                .load(std::sync::atomic::Ordering::SeqCst)
4107        {
4108            self.create_queued(write, input, team, &create_id, edges)?;
4109            return Ok(Landed::Queued);
4110        }
4111        let (query, variables, root) = match &write.target {
4112            // Its relations read back in the same request, so a rewrite needs no read of them.
4113            Some(id) => (
4114                graphql::ISSUE_REWRITE,
4115                json!({"id":id.0,"input":input,"first":MAX_PAGE_SIZE}),
4116                MutationRoot::IssueUpdate,
4117            ),
4118            None => (
4119                graphql::ISSUE_CREATE,
4120                {
4121                    let mut input = input;
4122                    input["teamId"] = Value::String(team.0);
4123                    json!({"input":input})
4124                },
4125                MutationRoot::IssueCreate,
4126            ),
4127        };
4128        let (data, sent) = match self
4129            .send_write(MetadataRecord::Task, query, variables, &create_id)
4130            .await
4131        {
4132            Ok(Written::Answered { data, sent }) => (data, sent),
4133            // An earlier attempt's issue, or a concurrent one's: this create's, brought in step
4134            // with what this create would have written by a compared update of only the fields
4135            // that differ — so what a person did to it since, a metadata key they added among
4136            // them, is kept.
4137            Ok(Written::Held(held)) => {
4138                self.bring_in_step(
4139                    &held,
4140                    write,
4141                    &state,
4142                    &labels,
4143                    description.as_deref(),
4144                    &edges,
4145                )
4146                .await?;
4147                // The write a copy makes of it next, saying what this create did, is the one
4148                // this compared update already made, and writes nothing more.
4149                self.created_inputs
4150                    .lock()
4151                    .unwrap_or_else(std::sync::PoisonError::into_inner)
4152                    .insert(held.clone(), sent_input);
4153                return Ok(Landed::At(held));
4154            }
4155            Err(error) => {
4156                self.forget_vocabulary();
4157                return Err(error);
4158            }
4159        };
4160        let issue =
4161            mutation_payload(&data, root)?
4162                .get("issue")
4163                .ok_or_else(|| SourceError::Malformed {
4164                    message: format!("missing {}.issue", root.as_str()),
4165                })?;
4166        let id = created_as(
4167            NativeId(backend_id(issue, "id")?.into()),
4168            sent.as_ref(),
4169            "issue",
4170        )?;
4171        self.hold_stored(MetadataRecord::Task, &id, issue)?;
4172        let held = held_relations(write.target.as_ref(), issue)?;
4173        self.write_relations(&id, &edges, WriteKind::Task, held)
4174            .await?;
4175        Ok(Landed::At(id))
4176    }
4177}
4178
4179#[async_trait::async_trait]
4180impl TaskSource for LinearSource {
4181    /// Linear names no `user` for a comment an integration or a bot made, and names one for
4182    /// every comment a person made: so a comment with an author is a person's, and one with
4183    /// none a bot's.
4184    fn comment_author_kind(
4185        &self,
4186        comment: &onetaskgraph_plugin_api::Comment,
4187    ) -> onetaskgraph_plugin_api::AuthorKind {
4188        if comment.author.is_some() {
4189            onetaskgraph_plugin_api::AuthorKind::Person
4190        } else {
4191            onetaskgraph_plugin_api::AuthorKind::Bot
4192        }
4193    }
4194    /// Linear's filtered reads lag its writes by seconds, so a read of the comments made since
4195    /// an instant sets its watermark back by [`COMMENT_FILTER_LAG`].
4196    fn comment_consistency_window(&self) -> std::time::Duration {
4197        COMMENT_FILTER_LAG
4198    }
4199    fn kind(&self) -> &'static str {
4200        KIND
4201    }
4202    /// A task's fields always, and its comments and forward edges once the cache is attached.
4203    /// §4.13d of `docs/plugin-protocol.md` states each with what `spike-linear-coverage`
4204    /// measured.
4205    fn version_coverage(&self) -> onetaskgraph_plugin_api::VersionCoverage {
4206        onetaskgraph_plugin_api::VersionCoverage {
4207            fields: onetaskgraph_plugin_api::Coverage::Covered,
4208            comments: self.attached_coverage(COMMENTS_UNATTACHED),
4209            forward_edges: self.attached_coverage(EDGES_UNATTACHED),
4210        }
4211    }
4212    /// A project's fields always, and its forward edges once the cache is attached.
4213    fn project_version_coverage(&self) -> onetaskgraph_plugin_api::ProjectVersionCoverage {
4214        onetaskgraph_plugin_api::ProjectVersionCoverage {
4215            fields: onetaskgraph_plugin_api::Coverage::Covered,
4216            forward_edges: self.attached_coverage(PROJECT_EDGES_UNATTACHED),
4217        }
4218    }
4219    /// A task's and a project's reverse edges once the cache is attached: the token then carries
4220    /// the digest of its first page of inverse relations, which moves for every relation another
4221    /// item adds or removes with it.
4222    fn reverse_edges_coverage(&self, kind: ItemKind) -> onetaskgraph_plugin_api::Coverage {
4223        self.attached_coverage(match kind {
4224            ItemKind::Task => REVERSE_EDGES_UNATTACHED,
4225            ItemKind::Project => PROJECT_REVERSE_EDGES_UNATTACHED,
4226        })
4227    }
4228    /// A document's fields; never its asset manifest.
4229    fn document_version_coverage(&self) -> onetaskgraph_plugin_api::DocumentVersionCoverage {
4230        onetaskgraph_plugin_api::DocumentVersionCoverage {
4231            fields: onetaskgraph_plugin_api::Coverage::Covered,
4232            assets: onetaskgraph_plugin_api::Coverage::Uncovered {
4233                reason: DOCUMENT_ASSETS_UNCOVERED.to_owned(),
4234            },
4235        }
4236    }
4237    fn order_versions(&self, a: &str, b: &str) -> Option<std::cmp::Ordering> {
4238        change_token::order(a, b)
4239    }
4240    /// From here on, every issue read carries its first page of comments, relations and inverse
4241    /// relations, every project read its first page of relations, and a dependency read the
4242    /// token's other parts — see [`graphql::ISSUES_CACHED`] and the documents beside it
4243    /// — so a task's token covers its comments and its edges both ways, and a project's its
4244    /// forward edges.
4245    fn attach_cache(&self) {
4246        self.attached
4247            .store(true, std::sync::atomic::Ordering::Relaxed);
4248    }
4249    fn forward_edges_version(&self, id: &NativeId) -> Option<String> {
4250        self.edges_version(ItemKind::Task, id, Direction::DependsOn)
4251    }
4252    fn edges_version(&self, kind: ItemKind, id: &NativeId, direction: Direction) -> Option<String> {
4253        let root = match kind {
4254            ItemKind::Task => DependencyRoot::Issue,
4255            ItemKind::Project => DependencyRoot::Project,
4256        };
4257        self.edges_versions()
4258            .get(&(root, direction, id.clone()))
4259            .cloned()
4260    }
4261    fn capabilities(&self) -> Capabilities {
4262        Capabilities {
4263            projects: Support::Native,
4264            documents: Support::Native,
4265            comments: Support::Native,
4266            assets: Support::Native,
4267            priority: Support::Native,
4268            filter_by_priority: Support::Native,
4269            filter_by_comment_activity: Support::Native,
4270            filter_by_metadata: Support::Native,
4271            filter_by_origin: Support::Native,
4272            reconcile_status: Support::Unsupported,
4273            complete_by_issue: Support::Unsupported,
4274            orphan_tasks: Support::Native,
4275            filter_by_label: Support::Native,
4276            filter_by_status: Support::Native,
4277            search_title: Support::Native,
4278            search_content: Support::Native,
4279            task_dependencies: DependencySupport::BothDirections,
4280            project_dependencies: DependencySupport::BothDirections,
4281            max_page_size: MAX_PAGE_SIZE,
4282        }
4283    }
4284    fn writes(&self) -> WriteSupport {
4285        WriteSupport::Supported
4286    }
4287    /// The name `status_mapping` gives the kind and the category, which is the whole of what a
4288    /// write sends; see the ruling on what a status is. A category it gives no name is left as
4289    /// it is, for the write to refuse.
4290    async fn stored_status(&self, kind: ItemKind, status: &Status) -> Result<Status, SourceError> {
4291        Ok(match self.statuses.name_for(status.category, kind) {
4292            Ok(name) => Status {
4293                category: status.category,
4294                name: name.as_str().to_owned(),
4295            },
4296            Err(_) => status.clone(),
4297        })
4298    }
4299    /// Where the item is, as the answer to this instance's latest write of it said: every
4300    /// long-form write selects its `url`.
4301    fn written_location(&self, record: MetadataRecord, id: &NativeId) -> Option<Location> {
4302        let held = self
4303            .locations
4304            .lock()
4305            .unwrap_or_else(std::sync::PoisonError::into_inner)
4306            .get(&(record, id.clone()))
4307            .cloned();
4308        web_address(held.as_deref())
4309    }
4310    /// The issue, project or document whose own id is one of `key`'s generations — see
4311    /// [`linear_ids_of_key`] — the ids a create carrying it is sent under here, in turn; Linear
4312    /// answers a read by id at once, so it never lags. Every generation is read, because one an
4313    /// earlier create was refused under reads as absent whatever holds it.
4314    async fn created_with_key(
4315        &self,
4316        record: MetadataRecord,
4317        key: &str,
4318        _since: Option<chrono::DateTime<chrono::Utc>>,
4319        _target: &onetaskgraph_plugin_api::WriteTarget<'_>,
4320    ) -> Result<Vec<NativeId>, SourceError> {
4321        let mut found = Vec::new();
4322        for id in linear_ids_of_key(key)? {
4323            found.extend(self.held_at(record, &NativeId(id)).await?);
4324        }
4325        Ok(found)
4326    }
4327    /// The task as this instance's latest write of it was answered with — never a request.
4328    async fn written_task(&self, id: &NativeId) -> Option<Task> {
4329        self.answered()
4330            .get(&(MetadataRecord::Task, id.clone()))
4331            .and_then(|answered| answered.task.clone())
4332    }
4333    /// The token the answer to this instance's latest write of the item spelled, when it
4334    /// carried every part a read spells one from.
4335    async fn written_version(&self, record: MetadataRecord, id: &NativeId) -> Option<String> {
4336        self.answered()
4337            .get(&(record, id.clone()))
4338            .and_then(|answered| answered.version.clone())
4339    }
4340    /// The ids Linear's editor gave the item's headings, as the latest answer that selected its
4341    /// editor state carried them: every read of one item, every issue and document listing and
4342    /// every write of a long form selects it, and the project listings, which no section link
4343    /// reads ids from, do not.
4344    fn stored_headings(
4345        &self,
4346        record: MetadataRecord,
4347        id: &NativeId,
4348    ) -> Option<Vec<onetaskgraph_plugin_api::StoredHeading>> {
4349        self.headings
4350            .lock()
4351            .unwrap_or_else(std::sync::PoisonError::into_inner)
4352            .get(&(record, id.clone()))
4353            .cloned()
4354    }
4355    /// Applied in [`LinearSource::answer_with`], the one place every request and answer passes.
4356    fn attach_body_markup(&self, markup: onetaskgraph_plugin_api::SharedBodyMarkup) {
4357        let _ = self.body_markup.set(markup);
4358    }
4359    /// The content the latest write of the item selected in its own answer, the metadata slot
4360    /// and its separator removed; see the ruling on what Linear stores.
4361    fn stored_content(&self, record: MetadataRecord, id: &NativeId) -> Option<String> {
4362        self.stored
4363            .lock()
4364            .unwrap_or_else(std::sync::PoisonError::into_inner)
4365            .remove(&(record, id.clone()))
4366    }
4367    /// Private, once this instance's credential has reached its workspace: a Linear workspace
4368    /// is readable by its members alone and no setting of Linear's makes it readable by
4369    /// anybody else, so what is verified is that the workspace is really there to write into.
4370    ///
4371    /// Read inside the resolution a cold write sends anyway and held with it for this
4372    /// instance's lifetime, so a source declared private spends no request on it: a cold write
4373    /// sends what it always sent, and a warm one sends nothing more. A source with no `team`
4374    /// cannot make that read, and refuses rather than answering on trust.
4375    async fn visibility(
4376        &self,
4377        _target: &onetaskgraph_plugin_api::WriteTarget<'_>,
4378    ) -> Result<onetaskgraph_plugin_api::Visibility, SourceError> {
4379        let (vocabulary, _) = self.vocabulary(false).await.map_err(|error| match error {
4380            SourceError::Refused { message } => SourceError::Refused {
4381                message: format!(
4382                    "source {} cannot verify that it is private: {message}",
4383                    self.name
4384                ),
4385            },
4386            other => other,
4387        })?;
4388        if vocabulary.workspace.is_none() {
4389            return Err(SourceError::Malformed {
4390                message: format!(
4391                    "source {} cannot verify that it is private: Linear named no workspace for \
4392                     its credential",
4393                    self.name
4394                ),
4395            });
4396        }
4397        Ok(onetaskgraph_plugin_api::Visibility::Private)
4398    }
4399    async fn health(&self) -> Result<Health, SourceError> {
4400        let data = self.send(VIEWER, json!({})).await?;
4401        str_at(
4402            data.get("viewer").ok_or_else(|| SourceError::Malformed {
4403                message: "missing viewer".into(),
4404            })?,
4405            "id",
4406        )?;
4407        Ok(Health {
4408            reachable: true,
4409            detail: None,
4410        })
4411    }
4412    /// The workspace's organization id, digested: one request. A team or a project scope
4413    /// narrows what this source reads, never which workspace it is, so every source of one
4414    /// workspace designates the same tracker.
4415    async fn designator(&self) -> Result<Option<Designator>, SourceError> {
4416        // A copy's batched origin read carries the organization id, held for the command.
4417        self.send_origins_ahead().await?;
4418        let organization = match self.held_organization()? {
4419            Some(organization) => organization,
4420            None => {
4421                let data = self.send(graphql::ORGANIZATION, json!({})).await?;
4422                str_at(
4423                    data.get("organization")
4424                        .ok_or_else(|| SourceError::Malformed {
4425                            message: "missing organization".into(),
4426                        })?,
4427                    "id",
4428                )?
4429                .to_owned()
4430            }
4431        };
4432        let organization = organization.as_str();
4433        // An empty id names no workspace, and its digest would name one all the same.
4434        if organization.trim().is_empty() {
4435            return Err(SourceError::Malformed {
4436                message: "Linear answered an organization with an empty id".into(),
4437            });
4438        }
4439        Designator::of_backend(KIND, organization)
4440            .map(Some)
4441            .map_err(|message| SourceError::Malformed { message })
4442    }
4443    async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError> {
4444        Ok(self.issue_held(id, Read::Load).await?.map(|(task, _)| task))
4445    }
4446    /// Each issue with the page of its comments `comments` names in one request,
4447    /// [`graphql::ISSUE_DETAIL`]; an issue alone, as [`get_task`](Self::get_task) reads it,
4448    /// when no page is asked for.
4449    async fn get_task_details(
4450        &self,
4451        ids: &[NativeId],
4452        comments: Option<&PageRequest>,
4453    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
4454        if let Some(page) = comments
4455            && let Some(read) = self.details_batched(ids, page).await
4456        {
4457            return read;
4458        }
4459        let mut read = Vec::with_capacity(ids.len());
4460        for id in ids {
4461            read.push(match comments {
4462                Some(page) => self.issue_detail(id, page).await,
4463                None => self.issue_held(id, Read::Load).await.map(|held| {
4464                    held.map(|(task, _)| TaskDetailRead {
4465                        task,
4466                        comments: None,
4467                    })
4468                }),
4469            });
4470        }
4471        read
4472    }
4473    async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError> {
4474        Ok(self
4475            .project_held(id, Read::Load)
4476            .await?
4477            .map(|(project, _)| project))
4478    }
4479    async fn query_tasks(
4480        &self,
4481        query: &TaskQuery,
4482        page: &PageRequest,
4483    ) -> Result<Page<Task>, SourceError> {
4484        if query.origin.is_some() {
4485            self.send_origins_ahead().await?;
4486        }
4487        // A copy's lookup by origin that lists nothing reads the issue an earlier copy created
4488        // under that origin's key by id, which no filtered read can be behind.
4489        if let Some(held) = self.held_origin_tasks(query, page)? {
4490            return self.tasks_with_copied_by_key(query, page, held).await;
4491        }
4492        let d=self.send(self.read_document(ISSUES),json!({"first":page.limit.min(MAX_PAGE_SIZE),"after":page.cursor.as_ref().map(|c|&c.0),"filter":self.issue_filter(query)?})).await?;
4493        let listed = connection(&d, "issues", |v| {
4494            map_task(v, &self.name, &self.statuses, self.spelling())
4495        })?;
4496        let listed = Page {
4497            items: listed
4498                .items
4499                .into_iter()
4500                .filter(|task| Self::confirms(query, task))
4501                .collect(),
4502            next: listed.next,
4503        };
4504        self.tasks_with_copied_by_key(query, page, listed).await
4505    }
4506    async fn query_projects(
4507        &self,
4508        query: &ProjectQuery,
4509        page: &PageRequest,
4510    ) -> Result<Page<Project>, SourceError> {
4511        // llmlint: ignore[changed_behavior_has_e2e] The shared CLI journey `every_complete_dataset_source_filters_projects_by_label_status_and_text` asserts that Linear status filtering returns only P-2 and reports native pushdown; `item_reads_and_transport_error_boundaries_are_exercised` separately asserts the serialized `status:{name:{eqIgnoreCase:…}}` predicate the mapping names.
4512        let d=self.send(self.read_document(PROJECTS),json!({"first":page.limit.min(self.projects_page()),"after":page.cursor.as_ref().map(|c|&c.0),"filter":self.project_filter(&query.labels,&query.statuses)})).await?;
4513        let page = connection(&d, "projects", |v| {
4514            map_project(v, &self.statuses, self.spelling())
4515        })?;
4516        // A project's text is applied here, over the page Linear answered: `search_title` and
4517        // `search_content` are declared for every level, and `ProjectFilter` is not asked for
4518        // a content match — so the rule decides, over every row of the page.
4519        Ok(Page {
4520            items: page
4521                .items
4522                .into_iter()
4523                .filter(|project| {
4524                    (query.statuses.is_empty() || query.statuses.contains(&project.status.category))
4525                        && query.text.as_ref().is_none_or(|text| {
4526                            text_holds(&project.title, project.content.as_deref(), text)
4527                        })
4528                })
4529                .collect(),
4530            next: page.next,
4531        })
4532    }
4533    /// The scope's projects walked and narrowed to `origin`, as the trait's default walks them —
4534    /// or, at the first page, what [`read_ahead_origins_for_copy`](Self::read_ahead_origins_for_copy)
4535    /// held for it.
4536    async fn query_projects_by_origin(
4537        &self,
4538        origin: &str,
4539        page: &PageRequest,
4540    ) -> Result<Page<Project>, SourceError> {
4541        self.projects_by_origin(origin, page).await
4542    }
4543    /// The scope's documents walked and narrowed to `origin`, as the trait's default walks them,
4544    /// and the one an earlier copy created under that origin's key, read by id, when it lists
4545    /// none.
4546    async fn query_documents_by_origin(
4547        &self,
4548        origin: &str,
4549        page: &PageRequest,
4550    ) -> Result<Page<Document>, SourceError> {
4551        self.documents_by_origin(origin, page).await
4552    }
4553    /// One [`graphql::COUNTERPART_LOOKUPS`] per [`ORIGIN_BATCH`] origins; see the ruling on the
4554    /// requests a copy sends.
4555    async fn read_ahead_origins_for_copy(&self, origins: &[String]) -> Result<(), SourceError> {
4556        self.read_origins_ahead(origins).await
4557    }
4558    async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError> {
4559        let d = self
4560            .send(
4561                LABELS,
4562                json!({"first":page.limit.min(MAX_PAGE_SIZE),"after":page.cursor.as_ref().map(|c|&c.0)}),
4563            )
4564            .await?;
4565        connection(&d, "issueLabels", map_label)
4566    }
4567    async fn task_dependencies(
4568        &self,
4569        id: &NativeId,
4570        direction: Direction,
4571        page: &PageRequest,
4572    ) -> Result<Page<DependencyEdge>, SourceError> {
4573        let plain = match direction {
4574            Direction::DependsOn => graphql::ISSUE_DEPENDS_ON,
4575            Direction::DependedOnBy => graphql::ISSUE_DEPENDED_ON_BY,
4576        };
4577        self.dependencies(
4578            self.read_document(plain),
4579            DependencyRoot::Issue,
4580            id,
4581            direction,
4582            page,
4583        )
4584        .await
4585    }
4586    async fn project_dependencies(
4587        &self,
4588        id: &NativeId,
4589        direction: Direction,
4590        page: &PageRequest,
4591    ) -> Result<Page<DependencyEdge>, SourceError> {
4592        let plain = match direction {
4593            Direction::DependsOn => graphql::PROJECT_DEPENDS_ON,
4594            Direction::DependedOnBy => graphql::PROJECT_DEPENDED_ON_BY,
4595        };
4596        self.dependencies(
4597            self.read_document(plain),
4598            DependencyRoot::Project,
4599            id,
4600            direction,
4601            page,
4602        )
4603        .await
4604    }
4605    fn task_body_size(
4606        &self,
4607        write: &ItemWrite<Task>,
4608        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
4609    ) -> Option<onetaskgraph_plugin_api::BodySize> {
4610        let (content, mut metadata) =
4611            served(write.item.content.as_deref(), &write.item.metadata, assets);
4612        set_task_list(&mut metadata, TaskRef::DELIVERS_KEY, &write.item.delivers);
4613        set_task_list(
4614            &mut metadata,
4615            TaskRef::DELIVERED_BY_KEY,
4616            &write.item.delivered_by,
4617        );
4618        body_size(Self::long_form(
4619            content.as_deref(),
4620            &metadata,
4621            &write.item.repositories,
4622            write.item.classification,
4623            self.recorded_ends(&write.depends_on, WriteKind::Task),
4624        ))
4625    }
4626
4627    fn project_body_size(
4628        &self,
4629        write: &ItemWrite<Project>,
4630    ) -> Option<onetaskgraph_plugin_api::BodySize> {
4631        body_size(Self::long_form(
4632            write.item.content.as_deref(),
4633            &write.item.metadata,
4634            &write.item.repositories,
4635            write.item.classification,
4636            self.recorded_ends(&write.depends_on, WriteKind::Project),
4637        ))
4638    }
4639
4640    fn document_body_size(
4641        &self,
4642        write: &ItemWrite<Document>,
4643        assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
4644    ) -> Option<onetaskgraph_plugin_api::BodySize> {
4645        let (content, metadata) =
4646            served(write.item.content.as_deref(), &write.item.metadata, assets);
4647        body_size(Self::long_form(
4648            content.as_deref(),
4649            &metadata,
4650            &write.item.repositories,
4651            write.item.classification,
4652            Vec::new(),
4653        ))
4654    }
4655
4656    async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
4657        match self.write_or_queue(write).await? {
4658            Landed::At(id) => Ok(id),
4659            // Only `write_tasks` queues, and it never hands a queued create back as one written.
4660            Landed::Queued => Err(SourceError::Malformed {
4661                message: "a create was queued outside write_tasks".to_owned(),
4662            }),
4663        }
4664    }
4665    async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
4666        // Before anything is read or written, and before the item's own description
4667        // records these edges: an edge Linear will never accept has to refuse the whole
4668        // write, or a copy would create the project and then fail relating it, leaving the
4669        // undo to clean up a write that could have been refused without a call at all.
4670        if let Some(edge) = Self::unordered_project_edge(&write.depends_on) {
4671            return Err(self.unordered_project_relation(&write.item.id, edge.to.id()));
4672        }
4673        if let Some(key) = delivery_key_in(&write.item.metadata) {
4674            return Err(self.undeliverable(key, "project"));
4675        }
4676        if let Some(refused) = self.project_out_of_scope(write.target.as_ref()) {
4677            return Err(refused);
4678        }
4679        // Through the project side of the mapping, before anything else is sent: the item's
4680        // own status name plays no part, because a project's statuses are a vocabulary of
4681        // their own that the name a status was read under elsewhere says nothing about.
4682        let (status, _) = self
4683            .status_id(write.item.status.category, ItemKind::Project)
4684            .await?;
4685        let edges = self
4686            .prepare_edges(&write.depends_on, WriteKind::Project)
4687            .await?;
4688        let team = self.team_id().await?;
4689        let labels = self
4690            .label_ids(&write.item.labels, WriteKind::Project)
4691            .await?;
4692        let description = self.write_description(
4693            write.item.content.as_deref(),
4694            &write.item.metadata,
4695            &write.item.repositories,
4696            write.item.classification,
4697            &edges,
4698            WriteKind::Project,
4699        )?;
4700        let create_id = self.create_id(
4701            MetadataRecord::Project,
4702            &write.item.metadata,
4703            write.target.as_ref(),
4704        )?;
4705        // A project's long form is its `content`, not its `description`: Linear documents the
4706        // second as "the short description of the project", and the first — the project's
4707        // Markdown body — is the one with room for a description and a metadata slot.
4708        let input = json!({"name":write.item.title,"content":description,"statusId":status,"labelIds":labels});
4709        let (query, variables, root) = match &write.target {
4710            // Its relations read back in the same request, as an issue's are.
4711            Some(id) => (
4712                graphql::PROJECT_REWRITE,
4713                json!({"id":id.0,"input":input,"first":MAX_PAGE_SIZE}),
4714                MutationRoot::ProjectUpdate,
4715            ),
4716            None => (
4717                graphql::PROJECT_CREATE,
4718                {
4719                    let mut input = input;
4720                    input["teamIds"] = json!([team]);
4721                    json!({"input":input})
4722                },
4723                MutationRoot::ProjectCreate,
4724            ),
4725        };
4726        let (data, sent) = match self
4727            .send_write(MetadataRecord::Project, query, variables, &create_id)
4728            .await
4729        {
4730            Ok(Written::Answered { data, sent }) => (data, sent),
4731            // An earlier attempt's project, or a concurrent one's, written whole as an issue's is.
4732            Ok(Written::Held(held)) => {
4733                return self
4734                    .write_project(&ItemWrite {
4735                        target: Some(held),
4736                        item: write.item.clone(),
4737                        depends_on: write.depends_on.clone(),
4738                    })
4739                    .await;
4740            }
4741            Err(error) => {
4742                self.forget_vocabulary();
4743                return Err(error);
4744            }
4745        };
4746        let project = mutation_payload(&data, root)?
4747            .get("project")
4748            .ok_or_else(|| SourceError::Malformed {
4749                message: format!("missing {}.project", root.as_str()),
4750            })?;
4751        let id = created_as(
4752            NativeId(backend_id(project, "id")?.into()),
4753            sent.as_ref(),
4754            "project",
4755        )?;
4756        self.hold_stored(MetadataRecord::Project, &id, project)?;
4757        let held = held_relations(write.target.as_ref(), project)?;
4758        self.write_relations(&id, &edges, WriteKind::Project, held)
4759            .await?;
4760        Ok(id)
4761    }
4762    async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
4763        // An id naming nothing is the state this asks for, not an error — Linear reports
4764        // an unknown issue as an errored response rather than an unsuccessful payload, and
4765        // `get_task` answering `None` is what says the item is already gone.
4766        if self.get_task(id).await?.is_none() {
4767            return Ok(());
4768        }
4769        self.take_written(MetadataRecord::Task, id);
4770        let data = self.send(graphql::ISSUE_DELETE, json!({"id":id.0})).await?;
4771        mutation_payload(&data, MutationRoot::IssueDelete)?;
4772        Ok(())
4773    }
4774    async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
4775        // An id naming nothing is the state this asks for, on exactly the terms
4776        // `delete_task` reads it on.
4777        if self.get_project(id).await?.is_none() {
4778            return Ok(());
4779        }
4780        self.take_written(MetadataRecord::Project, id);
4781        let data = self
4782            .send(graphql::PROJECT_DELETE, json!({"id":id.0}))
4783            .await?;
4784        mutation_payload(&data, MutationRoot::ProjectDelete)?;
4785        Ok(())
4786    }
4787    async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
4788        // Read as an optional although the pinned `document(id:)` returns `Document!`, for
4789        // the reason `delete_task` records: Linear answers an id naming nothing with an
4790        // errored response rather than a null, and reading the null defensively is what
4791        // keeps a responder that does answer one from being a malformed-response failure.
4792        Ok(self.document_held(id).await?.map(|(document, _)| document))
4793    }
4794    async fn query_documents(
4795        &self,
4796        query: &DocumentQuery,
4797        page: &PageRequest,
4798    ) -> Result<Page<Document>, SourceError> {
4799        // A document's text is applied over each fetched page with the labels and the
4800        // orphans, by the contract's own rule: both searches are declared for every level.
4801        let want = page.limit.min(MAX_PAGE_SIZE) as usize;
4802        let mut filter = serde_json::Map::new();
4803        if let ProjectFilter::Is(id) = &query.project {
4804            if !self.in_scope(Some(id)) {
4805                return Ok(Page::last(Vec::new()));
4806            }
4807            filter.insert("project".into(), json!({"id": {"eq": id.0}}));
4808        } else if let Some(scope) = &self.project {
4809            filter.insert("project".into(), json!({"id": {"eq": scope.0}}));
4810        }
4811        let filter = Value::Object(filter);
4812        let mut items = Vec::new();
4813        let mut cursor = page.cursor.clone();
4814        loop {
4815            // Only what is still owed, so the predicates applied here can never make this
4816            // return more than the caller asked for, and never drop what it fetched.
4817            let first = want.saturating_sub(items.len()).max(1);
4818            let d = self
4819                .send(
4820                    DOCUMENTS,
4821                    json!({"first":first,"after":cursor.as_ref().map(|cursor|&cursor.0),"filter":filter}),
4822                )
4823                .await?;
4824            let fetched = connection(&d, "documents", map_document)?;
4825            items.extend(fetched.items.into_iter().filter(|document| {
4826                document_matches(document, &query.project, &query.labels)
4827                    && self.in_scope(document.project.as_ref())
4828                    && query.text.as_ref().is_none_or(|text| {
4829                        text_holds(&document.title, document.content.as_deref(), text)
4830                    })
4831            }));
4832            cursor = fetched.next;
4833            if cursor.is_none() || items.len() >= want {
4834                return Ok(Page {
4835                    items,
4836                    next: cursor,
4837                });
4838            }
4839        }
4840    }
4841    async fn write_task_with_assets(
4842        &self,
4843        write: &ItemWrite<Task>,
4844        _answers: Option<&std::collections::BTreeMap<String, Value>>,
4845        assets: &onetaskgraph_plugin_api::AssetWrite,
4846    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
4847        let mut write = write.clone();
4848        let uploads = self.upload_assets(assets).await?;
4849        let content = onetaskgraph_plugin_api::serve_asset_references(
4850            write.item.content.as_deref().unwrap_or_default(),
4851            &mut write.item.metadata,
4852            &uploads,
4853        );
4854        write.item.content = write.item.content.as_ref().map(|_| content);
4855        let id = self.write_task(&write).await?;
4856        Ok(onetaskgraph_plugin_api::AssetsWritten {
4857            id,
4858            content: write.item.content,
4859        })
4860    }
4861    async fn write_document_with_assets(
4862        &self,
4863        write: &ItemWrite<Document>,
4864        _answers: Option<&std::collections::BTreeMap<String, Value>>,
4865        assets: &onetaskgraph_plugin_api::AssetWrite,
4866    ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
4867        let mut write = write.clone();
4868        let uploads = self.upload_assets(assets).await?;
4869        let content = onetaskgraph_plugin_api::serve_asset_references(
4870            write.item.content.as_deref().unwrap_or_default(),
4871            &mut write.item.metadata,
4872            &uploads,
4873        );
4874        write.item.content = write.item.content.as_ref().map(|_| content);
4875        let id = self.write_document(&write).await?;
4876        Ok(onetaskgraph_plugin_api::AssetsWritten {
4877            id,
4878            content: write.item.content,
4879        })
4880    }
4881    async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
4882        // Two refusals by name rather than two silent drops. Linear's own document type
4883        // has no labels and a document is not work, so neither a label nor a dependency
4884        // has anywhere here to land — and a copy that dropped one would report success for
4885        // an item the destination does not hold.
4886        if !write.item.labels.is_empty() {
4887            let named = write
4888                .item
4889                .labels
4890                .iter()
4891                .map(|label| label.name.as_str())
4892                .collect::<Vec<_>>()
4893                .join(", ");
4894            return Err(SourceError::Refused {
4895                message: format!(
4896                    "source {} cannot carry a document's labels, because Linear's own \
4897                     document type has none: {named}",
4898                    self.name
4899                ),
4900            });
4901        }
4902        if !write.depends_on.is_empty()
4903            || write
4904                .item
4905                .metadata
4906                .contains_key(DependencyEdge::RECORDED_KEY)
4907        {
4908            return Err(SourceError::Refused {
4909                message: format!(
4910                    "source {} cannot carry {} on a document, because a document is not \
4911                     work and nothing may depend on one",
4912                    self.name,
4913                    DependencyEdge::RECORDED_KEY
4914                ),
4915            });
4916        }
4917        if let Some(key) = delivery_key_in(&write.item.metadata) {
4918            return Err(self.undeliverable(key, "document"));
4919        }
4920        let content = Self::long_form(
4921            write.item.content.as_deref(),
4922            &write.item.metadata,
4923            &write.item.repositories,
4924            write.item.classification,
4925            Vec::new(),
4926        )?;
4927        let project = self.filed_in(write.item.project.as_ref(), "document")?;
4928        let create_id = self.create_id(
4929            MetadataRecord::Document,
4930            &write.item.metadata,
4931            write.target.as_ref(),
4932        )?;
4933        let (query, variables, root) = match &write.target {
4934            Some(id) => {
4935                // A target this workspace does not hold is refused rather than created:
4936                // the engine established that id before asking, so an absent one is a race
4937                // this destination must not paper over by writing a second document.
4938                if self.get_document(id).await?.is_none() {
4939                    return Err(SourceError::Refused {
4940                        message: format!("source {} holds no document {}", self.name, id.0),
4941                    });
4942                }
4943                (
4944                    graphql::DOCUMENT_UPDATE,
4945                    json!({"id":id.0,"input":{"title":write.item.title,"content":content,"projectId":project}}),
4946                    MutationRoot::DocumentUpdate,
4947                )
4948            }
4949            None => {
4950                let mut input = json!({"title":write.item.title,"content":content});
4951                // A Linear document lives in a project, an initiative, an issue or a team.
4952                // One filed under no project needs the configured team to be its home, and
4953                // one filed under a project already has one — so the team is asked for
4954                // only where it is the answer, rather than made a condition of every write.
4955                //
4956                // **`projectId` is left out rather than sent as null, and that is Linear's
4957                // rule rather than tidiness.** `documentCreate` refuses an input that names
4958                // more than one home — `Exactly one of initiativeId, teamId, issueId,
4959                // releaseId, cycleId or projectId must be defined.` — and it counts a
4960                // *present* key, observed on 2026-09-04: `{projectId: null, teamId: …}` is
4961                // refused where `{teamId: …}` is accepted. So a document filed under no
4962                // project must carry no `projectId` at all. `documentUpdate` is the
4963                // opposite and keeps its explicit null, because there the null is the
4964                // instruction — it is how a document is moved out of a project, and
4965                // omitting the key would leave it where it was.
4966                match &project {
4967                    Some(project) => input["projectId"] = Value::String(project.clone()),
4968                    None => input["teamId"] = Value::String(self.team_id().await?.0),
4969                }
4970                (
4971                    graphql::DOCUMENT_CREATE,
4972                    json!({ "input": input }),
4973                    MutationRoot::DocumentCreate,
4974                )
4975            }
4976        };
4977        let (data, sent) = match self
4978            .send_write(MetadataRecord::Document, query, variables, &create_id)
4979            .await?
4980        {
4981            Written::Answered { data, sent } => (data, sent),
4982            // An earlier attempt's document, or a concurrent one's, written whole as an issue's is.
4983            Written::Held(held) => {
4984                return self
4985                    .write_document(&ItemWrite {
4986                        target: Some(held),
4987                        item: write.item.clone(),
4988                        depends_on: Vec::new(),
4989                    })
4990                    .await;
4991            }
4992        };
4993        let document = mutation_payload(&data, root)?
4994            .get("document")
4995            .ok_or_else(|| SourceError::Malformed {
4996                message: format!("missing {}.document", root.as_str()),
4997            })?;
4998        let id = created_as(
4999            NativeId(backend_id(document, "id")?.into()),
5000            sent.as_ref(),
5001            "document",
5002        )?;
5003        self.hold_stored(MetadataRecord::Document, &id, document)?;
5004        Ok(id)
5005    }
5006    async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
5007        // An id naming nothing is the state this asks for, on exactly the terms
5008        // `delete_task` reads it on.
5009        if self.get_document(id).await?.is_none() {
5010            return Ok(());
5011        }
5012        self.take_written(MetadataRecord::Document, id);
5013        let data = self
5014            .send(graphql::DOCUMENT_DELETE, json!({"id":id.0}))
5015            .await?;
5016        mutation_payload(&data, MutationRoot::DocumentDelete)?;
5017        Ok(())
5018    }
5019    async fn task_comments(
5020        &self,
5021        task: &NativeId,
5022        page: &PageRequest,
5023    ) -> Result<Option<Page<Comment>>, SourceError> {
5024        // A page of no rows is not a page: refused here rather than sent as `last: 0`, which
5025        // would answer an empty page that reads as a task with no comments.
5026        if page.limit == 0 {
5027            return Err(SourceError::Config {
5028                message: "a page limit of 0 is not a page; ask for at least 1 comment".to_owned(),
5029            });
5030        }
5031        // One request rather than a task lookup and then a read: the issue the comments
5032        // hang off answers "no such task" by itself, on exactly the terms `get_task` reads
5033        // it — null, or trashed.
5034        let d = self
5035            .send(
5036                graphql::ISSUE_COMMENTS,
5037                json!({"id":task.0,"last":page.limit.min(MAX_PAGE_SIZE),"before":page.cursor.as_ref().map(|c|&c.0)}),
5038            )
5039            .await?;
5040        optional(&d, "issue", comment_page)
5041    }
5042    async fn add_comment(
5043        &self,
5044        task: &NativeId,
5045        comment: &NewComment,
5046    ) -> Result<Option<Comment>, SourceError> {
5047        // Before anything is sent, because nothing Linear could answer changes it: see the
5048        // ruling on the author in this crate's module documentation.
5049        if let Some(author) = &comment.author {
5050            return Err(SourceError::Refused {
5051                message: format!(
5052                    "source {} cannot post a comment as {author:?}, because Linear records the \
5053                     user whose API key makes the request as the author of every comment; \
5054                     leave --author out to post as that user",
5055                    self.name
5056                ),
5057            });
5058        }
5059        let Some(issue) = self.commented_issue(task).await? else {
5060            return Ok(None);
5061        };
5062        let data = self
5063            .send(
5064                graphql::COMMENT_CREATE,
5065                json!({"input":{"issueId":issue.0,"body":comment.body.as_str()}}),
5066            )
5067            .await?;
5068        written_comment(&data, MutationRoot::CommentCreate).map(Some)
5069    }
5070    async fn edit_comment(
5071        &self,
5072        task: &NativeId,
5073        comment: &NativeId,
5074        body: &CommentBody,
5075    ) -> Result<Option<Comment>, SourceError> {
5076        let Some(held) = self.comment_on(task, comment).await? else {
5077            return Ok(None);
5078        };
5079        // A comment a copy wrote keeps its origin through an edit: its marker is carried over.
5080        let body = CommentOrigin::kept(&held, body)?;
5081        // `body` alone: the id, the author and the time it was written are the comment's
5082        // own, so nothing else is sent that Linear could move.
5083        let data = self
5084            .send(
5085                graphql::COMMENT_UPDATE,
5086                json!({"id":comment.0,"input":{"body":body.as_str()}}),
5087            )
5088            .await?;
5089        written_comment(&data, MutationRoot::CommentUpdate).map(Some)
5090    }
5091    async fn delete_comment(
5092        &self,
5093        task: &NativeId,
5094        comment: &NativeId,
5095    ) -> Result<Option<NativeId>, SourceError> {
5096        if !self.comment_is_on(task, comment).await? {
5097            return Ok(None);
5098        }
5099        let data = self
5100            .send(graphql::COMMENT_DELETE, json!({"id":comment.0}))
5101            .await?;
5102        mutation_payload(&data, MutationRoot::CommentDelete)?;
5103        Ok(Some(comment.clone()))
5104    }
5105    /// Resolved exactly as the write resolves it, through the instance's held vocabulary, so
5106    /// the write that follows sends no read this did not — and a project write the scope
5107    /// refuses is refused here first, before the resolution is read for it.
5108    async fn check_status_write(
5109        &self,
5110        kind: ItemKind,
5111        category: StatusCategory,
5112        target: Option<&NativeId>,
5113    ) -> Result<(), SourceError> {
5114        if kind == ItemKind::Project
5115            && let Some(refused) = self.project_out_of_scope(target)
5116        {
5117            return Err(refused);
5118        }
5119        self.status_id(category, kind).await.map(|_| ())
5120    }
5121    async fn set_task_status(
5122        &self,
5123        id: &NativeId,
5124        category: StatusCategory,
5125    ) -> Result<Option<Status>, SourceError> {
5126        Ok(self
5127            .status_written(id, category)
5128            .await?
5129            .map(|task| task.status))
5130    }
5131    /// One `issueUpdate` and nothing before it — see `status_written` — answering the task
5132    /// its own selection reports.
5133    async fn set_task_status_reading(
5134        &self,
5135        id: &NativeId,
5136        category: StatusCategory,
5137    ) -> Result<Option<Task>, SourceError> {
5138        self.status_written(id, category).await
5139    }
5140    /// One `projectUpdate` carrying only `statusId` — the project status this source's mapping
5141    /// gives the category — and nothing before it but the vocabulary it resolves that status
5142    /// against, answering the status the update's own selection reports.
5143    async fn set_project_status(
5144        &self,
5145        id: &NativeId,
5146        category: StatusCategory,
5147    ) -> Result<Option<Status>, SourceError> {
5148        if let Some(refused) = self.project_out_of_scope(Some(id)) {
5149            return Err(refused);
5150        }
5151        let (status, _) = self.status_id(category, ItemKind::Project).await?;
5152        self.take_written(MetadataRecord::Project, id);
5153        let answered = self
5154            .answer(
5155                graphql::PROJECT_STATUS_UPDATE,
5156                json!({"id":id.0,"input":{"statusId":status.0}}),
5157            )
5158            .await;
5159        let data = match answered {
5160            Ok(Ok(data)) => data,
5161            // A project Linear does not hold is no such project, never a refusal of the write.
5162            Ok(Err(refusal)) if refusal.project_missing() => return Ok(None),
5163            Ok(Err(refusal)) => {
5164                self.forget_vocabulary();
5165                return Err(refusal.into_error());
5166            }
5167            Err(error) => {
5168                self.forget_vocabulary();
5169                return Err(error);
5170            }
5171        };
5172        let project = mutation_payload(&data, MutationRoot::ProjectUpdate)?
5173            .get("project")
5174            .filter(|project| !project.is_null())
5175            .ok_or_else(|| SourceError::Malformed {
5176                message: "missing projectUpdate.project".into(),
5177            })?;
5178        acknowledged(project, id, MutationRoot::ProjectUpdate)?;
5179        mapped_status(
5180            project
5181                .get("status")
5182                .ok_or_else(|| SourceError::Malformed {
5183                    message: "missing projectUpdate.project.status".into(),
5184                })?,
5185            &self.statuses,
5186            ItemKind::Project,
5187        )
5188        .map(Some)
5189    }
5190    async fn set_task_priority(
5191        &self,
5192        id: &NativeId,
5193        priority: Priority,
5194    ) -> Result<Option<Priority>, SourceError> {
5195        // Read first: a trashed issue is not one this source holds, so it is never written
5196        // to, and the read is what tells "no such task" from a refusal here — unlike a status
5197        // write, whose budget the read is not worth.
5198        let Some(task) = self.get_task(id).await? else {
5199            return Ok(None);
5200        };
5201        // `priority` alone: every member of `IssueUpdateInput` is optional and Linear leaves
5202        // an absent one as the issue holds it, so nothing else about the issue can move.
5203        self.take_written(MetadataRecord::Task, &task.id);
5204        let data = self
5205            .send(
5206                graphql::ISSUE_PRIORITY_UPDATE,
5207                json!({"id":task.id.0,"input":{"priority":linear_priority(priority)}}),
5208            )
5209            .await?;
5210        let issue = mutation_payload(&data, MutationRoot::IssueUpdate)?
5211            .get("issue")
5212            .filter(|issue| !issue.is_null())
5213            .ok_or_else(|| SourceError::Malformed {
5214                message: "missing issueUpdate.issue".into(),
5215            })?;
5216        written_is(issue, &task.id)?;
5217        let priority = issue_priority(issue)?;
5218        // The issue as the answer selects it, token and all — a whole issue whose fields do not
5219        // read refused as any read's would be — or, from an answer selecting only the priority,
5220        // the issue as read before with the priority it answered, at no token.
5221        let answered = if issue.get("title").is_some() {
5222            let written = map_task(issue, &self.name, &self.statuses, self.spelling())?;
5223            Answered {
5224                version: written.version.clone(),
5225                task: Some(written),
5226            }
5227        } else {
5228            Answered {
5229                version: None,
5230                task: Some(Task {
5231                    priority,
5232                    version: None,
5233                    ..task.clone()
5234                }),
5235            }
5236        };
5237        self.answered()
5238            .insert((MetadataRecord::Task, task.id.clone()), answered.clone());
5239        if task.id != *id {
5240            self.answered()
5241                .insert((MetadataRecord::Task, id.clone()), answered);
5242        }
5243        Ok(Some(priority))
5244    }
5245    async fn set_task_content(
5246        &self,
5247        id: &NativeId,
5248        content: &str,
5249    ) -> Result<Option<()>, SourceError> {
5250        // The raw description, because the metadata slot lives in that same field and has to
5251        // go back byte for byte: re-encoding it would be a metadata write nobody asked for.
5252        // The whole issue is read as `get_task` reads it first, so an issue this source could
5253        // not read is refused before anything is written rather than overwritten blind.
5254        let Some((task, description)) = self.issue_held(id, Read::ForWrite).await? else {
5255            return Ok(None);
5256        };
5257        let issue = task.id;
5258        // The task's `## Links` section, re-rendered from the links it holds, stays with it.
5259        let (stored, held) = metadata_description(description.clone())?;
5260        let content = &onetaskgraph_plugin_api::relinked(content, stored.as_deref(), &held);
5261        let slot = match description.as_deref() {
5262            Some(description) => metadata_slot(description)?.map(str::to_owned),
5263            None => None,
5264        };
5265        let description = match &slot {
5266            None => content.to_owned(),
5267            Some(slot) if content.is_empty() => slot.clone(),
5268            // The separator `long_form` writes, so a content write and a copy leave one shape.
5269            Some(slot) => format!("{content}\n\n{slot}"),
5270        };
5271        // Checked before anything is sent: content ending in what this source reads as its own
5272        // metadata slot would read back as metadata rather than as the content it was.
5273        if metadata_slot(&description)? != slot.as_deref() {
5274            return Err(SourceError::Refused {
5275                message: format!(
5276                    "this content ends in what source {} reads as its own metadata slot, so part \
5277                     of it would read back as metadata rather than as content; next: remove that \
5278                     trailing block from the content",
5279                    self.name
5280                ),
5281            });
5282        }
5283        // And what a read will report is exactly what was asked for, or nothing is sent.
5284        let (reads, _) = metadata_description(Some(description.clone()))?;
5285        if reads.as_deref().unwrap_or_default() != content {
5286            return Err(SourceError::Refused {
5287                message: format!(
5288                    "this content would read back from source {} as {:?} rather than as itself; \
5289                     next: change how the content ends",
5290                    self.name,
5291                    reads.as_deref().unwrap_or_default()
5292                ),
5293            });
5294        }
5295        // `description` alone, for the reason `set_task_priority` sends `priority` alone.
5296        let data = self
5297            .send(
5298                graphql::ISSUE_UPDATE,
5299                json!({"id":issue.0,"input":{"description":description}}),
5300            )
5301            .await?;
5302        let written = mutation_payload(&data, MutationRoot::IssueUpdate)?
5303            .get("issue")
5304            .filter(|issue| !issue.is_null())
5305            .ok_or_else(|| SourceError::Malformed {
5306                message: "missing issueUpdate.issue".into(),
5307            })?;
5308        written_is(written, &issue)?;
5309        self.hold_stored(MetadataRecord::Task, &issue, written)?;
5310        Ok(Some(()))
5311    }
5312    async fn set_delivered_by(
5313        &self,
5314        id: &NativeId,
5315        delivered_by: &[TaskRef],
5316    ) -> Result<Option<()>, SourceError> {
5317        let entries = TaskRef::listed(
5318            TaskRef::DELIVERED_BY_KEY,
5319            id,
5320            Some(&self.name),
5321            delivered_by.to_vec(),
5322        )
5323        .map_err(|message| SourceError::Refused { message })?;
5324        let Some((task, description)) = self.issue_held(id, Read::ForWrite).await? else {
5325            return Ok(None);
5326        };
5327        let (_, held) = metadata_description(description.clone())?;
5328        let mut slot = held.clone();
5329        set_task_list(&mut slot, TaskRef::DELIVERED_BY_KEY, &entries);
5330        // Compared as JSON rather than as the field's bytes, so a slot already holding the
5331        // list is not rewritten for its spelling alone.
5332        if slot != held {
5333            let rewritten = reslotted(description.as_deref(), &slot)?;
5334            self.write_description_alone(&task.id, rewritten.as_deref())
5335                .await?;
5336        }
5337        Ok(Some(()))
5338    }
5339    /// One read of the issue and, unless the key already holds the value, one `issueUpdate`
5340    /// carrying the description alone, whose metadata slot is the only part that moved —
5341    /// answered with the issue that write's own answer selected, with no read after it.
5342    async fn set_task_metadata(
5343        &self,
5344        id: &NativeId,
5345        key: &MetadataKey,
5346        value: &Value,
5347    ) -> Result<Option<Task>, SourceError> {
5348        let Some((task, description)) = self.issue_held(id, Read::ForWrite).await? else {
5349            return Ok(None);
5350        };
5351        let (_, mut slot) = metadata_description(description.clone())?;
5352        if slot.get(key.as_str()) == Some(value) {
5353            return Ok(Some(task));
5354        }
5355        slot.insert(key.as_str().to_owned(), value.clone());
5356        let rewritten = reslotted(description.as_deref(), &slot)?;
5357        let issue = self
5358            .write_description_alone(&task.id, rewritten.as_deref())
5359            .await?;
5360        // The issue as the write's own answer selected it, which is what a read of it answers:
5361        // nothing is read after the write.
5362        map_task(&issue, &self.name, &self.statuses, self.spelling()).map(Some)
5363    }
5364    /// One metadata key of a project, on the terms of `set_task_metadata`: one read, and one
5365    /// `projectUpdate` carrying the content alone.
5366    async fn set_project_metadata(
5367        &self,
5368        id: &NativeId,
5369        key: &MetadataKey,
5370        value: &Value,
5371    ) -> Result<Option<Project>, SourceError> {
5372        let Some((project, description)) = self.project_held(id, Read::ForWrite).await? else {
5373            return Ok(None);
5374        };
5375        let (_, mut slot) = metadata_description(description.clone())?;
5376        if slot.get(key.as_str()) == Some(value) {
5377            return Ok(Some(project));
5378        }
5379        slot.insert(key.as_str().to_owned(), value.clone());
5380        let rewritten = reslotted(description.as_deref(), &slot)?;
5381        let written = self
5382            .write_project_content(&project.id, rewritten.as_deref())
5383            .await?;
5384        map_project(&written, &self.statuses, self.spelling()).map(Some)
5385    }
5386    /// One metadata key taken off a project or a document, on the terms of its
5387    /// `set_*_metadata`: one read, and — only when the slot holds the key — one update carrying
5388    /// the content alone. A task's goes through `update_task`, its one `issueUpdate`.
5389    async fn remove_record_metadata(
5390        &self,
5391        record: MetadataRecord,
5392        id: &NativeId,
5393        key: &MetadataKey,
5394    ) -> Result<Option<Option<String>>, SourceError> {
5395        match record {
5396            MetadataRecord::Task => {
5397                let mut update = onetaskgraph_plugin_api::TaskUpdate::default();
5398                update.metadata_remove.insert(key.clone());
5399                Ok(self
5400                    .update_task(id, &update)
5401                    .await?
5402                    .map(|outcome| outcome.task.version))
5403            }
5404            MetadataRecord::Project => {
5405                let Some((project, description)) = self.project_held(id, Read::ForWrite).await?
5406                else {
5407                    return Ok(None);
5408                };
5409                let (_, mut slot) = metadata_description(description.clone())?;
5410                if slot.remove(key.as_str()).is_none() {
5411                    return Ok(Some(project.version));
5412                }
5413                let rewritten = reslotted(description.as_deref(), &slot)?;
5414                let written = self
5415                    .write_project_content(&project.id, rewritten.as_deref())
5416                    .await?;
5417                Ok(Some(
5418                    map_project(&written, &self.statuses, self.spelling())?.version,
5419                ))
5420            }
5421            MetadataRecord::Document => {
5422                let Some((document, content)) = self.document_held(id).await? else {
5423                    return Ok(None);
5424                };
5425                let (_, mut slot) = metadata_description(content.clone())?;
5426                if slot.remove(key.as_str()).is_none() {
5427                    return Ok(Some(document.version));
5428                }
5429                let rewritten = reslotted(content.as_deref(), &slot)?;
5430                let written = self
5431                    .write_document_content(&document.id, rewritten.as_deref())
5432                    .await?;
5433                Ok(Some(map_document(&written)?.version))
5434            }
5435        }
5436    }
5437    /// One metadata key of a document, on the terms of `set_task_metadata`: one read, and one
5438    /// `documentUpdate` carrying the content alone.
5439    async fn set_document_metadata(
5440        &self,
5441        id: &NativeId,
5442        key: &MetadataKey,
5443        value: &Value,
5444    ) -> Result<Option<Document>, SourceError> {
5445        let Some((document, content)) = self.document_held(id).await? else {
5446            return Ok(None);
5447        };
5448        let (_, mut slot) = metadata_description(content.clone())?;
5449        if slot.get(key.as_str()) == Some(value) {
5450            return Ok(Some(document));
5451        }
5452        slot.insert(key.as_str().to_owned(), value.clone());
5453        let rewritten = reslotted(content.as_deref(), &slot)?;
5454        let written = self
5455            .write_document_content(&document.id, rewritten.as_deref())
5456            .await?;
5457        map_document(&written).map(Some)
5458    }
5459    /// One read of the issue and one `issueUpdate` carrying the description alone: the new
5460    /// content, and a slot whose `onetaskgraph.template` entry is `provenance` and whose every
5461    /// other entry is as it was. This source keeps no template answers — an issue has no room
5462    /// beside its description that is not the description, and answers written there would
5463    /// repeat what the content already says — so `answers` reaches nothing here.
5464    async fn set_task_rendering(
5465        &self,
5466        id: &NativeId,
5467        content: &str,
5468        provenance: &Value,
5469        _answers: &std::collections::BTreeMap<String, Value>,
5470    ) -> Result<Option<()>, SourceError> {
5471        let Some((task, description)) = self.issue_held(id, Read::ForWrite).await? else {
5472            return Ok(None);
5473        };
5474        let (stored, mut slot) = metadata_description(description.clone())?;
5475        slot.insert(MetadataKey::TEMPLATE_KEY.to_owned(), provenance.clone());
5476        // A rendering keeps the task's `## Links` section, re-rendered from its links.
5477        let content = &onetaskgraph_plugin_api::relinked(content, stored.as_deref(), &slot);
5478        // No read-back check, unlike a content write: this slot is never empty, it is written
5479        // after the content, and a read takes the last slot off first, so the content reads
5480        // back as itself whatever it ends in.
5481        let rewritten = Self::described(Some(content), &slot)?;
5482        if rewritten != description {
5483            self.write_description_alone(&task.id, rewritten.as_deref())
5484                .await?;
5485        }
5486        Ok(Some(()))
5487    }
5488    /// One document's rendering, on the terms of `set_task_rendering`, through one
5489    /// `documentUpdate` carrying the content alone.
5490    async fn set_document_rendering(
5491        &self,
5492        id: &NativeId,
5493        content: &str,
5494        provenance: &Value,
5495        _answers: &std::collections::BTreeMap<String, Value>,
5496    ) -> Result<Option<()>, SourceError> {
5497        let Some((document, held)) = self.document_held(id).await? else {
5498            return Ok(None);
5499        };
5500        let (_, mut slot) = metadata_description(held.clone())?;
5501        slot.insert(MetadataKey::TEMPLATE_KEY.to_owned(), provenance.clone());
5502        let rewritten = Self::described(Some(content), &slot)?;
5503        if rewritten != held {
5504            self.write_document_content(&document.id, rewritten.as_deref())
5505                .await?;
5506        }
5507        Ok(Some(()))
5508    }
5509    async fn set_task_rendering_with_assets(
5510        &self,
5511        id: &NativeId,
5512        content: &str,
5513        provenance: &Value,
5514        _answers: &std::collections::BTreeMap<String, Value>,
5515        assets: &onetaskgraph_plugin_api::AssetWrite,
5516    ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
5517        let Some((item, held)) = self.issue_held(id, Read::ForWrite).await? else {
5518            return Ok(None);
5519        };
5520        let (stored, mut metadata) = metadata_description(held)?;
5521        metadata.insert(MetadataKey::TEMPLATE_KEY.to_owned(), provenance.clone());
5522        let uploads = self.upload_assets(assets).await?;
5523        let content =
5524            onetaskgraph_plugin_api::serve_asset_references(content, &mut metadata, &uploads);
5525        // A rendering keeps the task's `## Links` section, re-rendered from its links.
5526        let relinked = onetaskgraph_plugin_api::relinked(&content, stored.as_deref(), &metadata);
5527        let written = Self::described(Some(&relinked), &metadata)?;
5528        self.write_description_alone(&item.id, written.as_deref())
5529            .await?;
5530        Ok(Some(onetaskgraph_plugin_api::AssetsWritten {
5531            id: item.id,
5532            content: Some(content),
5533        }))
5534    }
5535    async fn set_document_rendering_with_assets(
5536        &self,
5537        id: &NativeId,
5538        content: &str,
5539        provenance: &Value,
5540        _answers: &std::collections::BTreeMap<String, Value>,
5541        assets: &onetaskgraph_plugin_api::AssetWrite,
5542    ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
5543        let Some((item, held)) = self.document_held(id).await? else {
5544            return Ok(None);
5545        };
5546        let (_, mut metadata) = metadata_description(held)?;
5547        metadata.insert(MetadataKey::TEMPLATE_KEY.to_owned(), provenance.clone());
5548        let uploads = self.upload_assets(assets).await?;
5549        let content =
5550            onetaskgraph_plugin_api::serve_asset_references(content, &mut metadata, &uploads);
5551        let written = Self::described(Some(&content), &metadata)?;
5552        self.write_document_content(&item.id, written.as_deref())
5553            .await?;
5554        Ok(Some(onetaskgraph_plugin_api::AssetsWritten {
5555            id: item.id,
5556            content: Some(content),
5557        }))
5558    }
5559    /// One project's rendering, on the terms of `set_task_rendering`, through one
5560    /// `projectUpdate` carrying the content alone.
5561    async fn set_project_rendering(
5562        &self,
5563        id: &NativeId,
5564        content: &str,
5565        provenance: &Value,
5566        _answers: &std::collections::BTreeMap<String, Value>,
5567    ) -> Result<Option<()>, SourceError> {
5568        let Some((project, description)) = self.project_held(id, Read::ForWrite).await? else {
5569            return Ok(None);
5570        };
5571        let (_, mut slot) = metadata_description(description.clone())?;
5572        slot.insert(MetadataKey::TEMPLATE_KEY.to_owned(), provenance.clone());
5573        let rewritten = Self::described(Some(content), &slot)?;
5574        if rewritten != description {
5575            self.write_project_content(&project.id, rewritten.as_deref())
5576                .await?;
5577        }
5578        Ok(Some(()))
5579    }
5580    /// One read of the issue and one `issueUpdate` carrying only what differs; see
5581    /// `targeted_update`.
5582    async fn update_task(
5583        &self,
5584        id: &NativeId,
5585        update: &TaskUpdate,
5586    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
5587        self.targeted_update(id, update).await
5588    }
5589
5590    /// Each issue's parent, children and links, in one aliased relation read.
5591    async fn read_relations(
5592        &self,
5593        ids: &[NativeId],
5594    ) -> Vec<Result<Option<onetaskgraph_plugin_api::Relations>, SourceError>> {
5595        self.relations_read(ids).await
5596    }
5597
5598    async fn set_parents(
5599        &self,
5600        writes: &[onetaskgraph_plugin_api::ParentWrite],
5601    ) -> Vec<Result<onetaskgraph_plugin_api::ParentAnswer, SourceError>> {
5602        self.parents_written(writes).await
5603    }
5604
5605    fn link_types(&self) -> onetaskgraph_plugin_api::LinkTypes {
5606        self.link_types.clone()
5607    }
5608
5609    async fn add_native_links(
5610        &self,
5611        links: &[onetaskgraph_plugin_api::NativeLink],
5612    ) -> Vec<Result<(), SourceError>> {
5613        self.native_links_added(links).await
5614    }
5615
5616    async fn remove_native_links(
5617        &self,
5618        links: &[onetaskgraph_plugin_api::NativeLink],
5619    ) -> Vec<Result<(), SourceError>> {
5620        self.native_links_removed(links).await
5621    }
5622
5623    /// Every issue read in one aliased read and every update that changes something sent in
5624    /// one aliased `issueUpdate` document — see the `batch` module for where one is sent alone.
5625    async fn update_tasks(
5626        &self,
5627        updates: &[onetaskgraph_plugin_api::BatchUpdate],
5628    ) -> Vec<Result<onetaskgraph_plugin_api::BatchAnswer<TaskUpdateOutcome>, SourceError>> {
5629        self.update_batched(updates).await
5630    }
5631    /// Every issue read in one aliased read and every comment created in one aliased
5632    /// `commentCreate` document — see the `batch` module.
5633    async fn add_comments(
5634        &self,
5635        comments: &[onetaskgraph_plugin_api::BatchComment],
5636    ) -> Vec<Result<onetaskgraph_plugin_api::BatchAnswer<Comment>, SourceError>> {
5637        self.comment_batched(comments).await
5638    }
5639    /// The issue as this process last read or wrote it, whole, for the store's cache to keep
5640    /// beside its entry.
5641    fn write_context(&self, id: &NativeId) -> Option<Value> {
5642        self.contexts
5643            .lock()
5644            .unwrap_or_else(std::sync::PoisonError::into_inner)
5645            .get(id)
5646            .cloned()
5647    }
5648    /// The issue the cache kept at the version a write expects, taken as that write's read of it,
5649    /// so a write of what differs sends its `issueUpdate` and nothing before it. A context that
5650    /// does not read as this issue — another issue's included — is not taken.
5651    fn prime_write(&self, id: &NativeId, context: &Value, _board: Option<&Value>) -> bool {
5652        let reads = map_task(context, &self.name, &self.statuses, self.spelling())
5653            .is_ok_and(|task| task.id == *id)
5654            && context.get("description").is_some();
5655        if reads {
5656            self.written
5657                .lock()
5658                .unwrap_or_else(std::sync::PoisonError::into_inner)
5659                .insert((MetadataRecord::Task, id.clone()), context.clone());
5660        }
5661        reads
5662    }
5663    /// Let go of a context `prime_write` took, its write not made.
5664    fn unprime(&self, id: &NativeId) {
5665        self.take_written(MetadataRecord::Task, id);
5666    }
5667    /// As many as one aliased `issueCreate` document carries — see the `batch` module.
5668    fn create_batch_limit(&self) -> usize {
5669        batch::CREATE_BATCH
5670    }
5671    /// Linear answers a batched create with exactly what it stored for each issue, so each may
5672    /// carry the copy's record as a create alone does.
5673    fn records_created_together(&self) -> bool {
5674        true
5675    }
5676    /// Every create in one aliased `issueCreate` document, each answered as a create alone is
5677    /// — see the `batch` module.
5678    async fn write_tasks(&self, writes: &[ItemWrite<Task>]) -> Result<Vec<NativeId>, SourceError> {
5679        self.create_batched(writes).await
5680    }
5681    /// The relations of every issue the copy creates from here on are created together, in
5682    /// [`finish_writes`](Self::finish_writes).
5683    fn begin_deferred_writes(&self) {
5684        self.deferring
5685            .store(true, std::sync::atomic::Ordering::SeqCst);
5686    }
5687    /// Every relation held back since `begin_deferred_writes`, created in one aliased
5688    /// `issueRelationCreate` document — see the `batch` module.
5689    async fn finish_writes(&self) -> Result<(), SourceError> {
5690        self.deferring
5691            .store(false, std::sync::atomic::Ordering::SeqCst);
5692        self.finish_relations().await
5693    }
5694    /// Every task and project with its forward relations, and every document, the copy names
5695    /// read in one mixed aliased read — see the `batch` module.
5696    async fn read_ahead_records_for_copy(
5697        &self,
5698        records: &[(MetadataRecord, NativeId)],
5699    ) -> Result<(), SourceError> {
5700        self.read_ahead_batched(records).await
5701    }
5702    /// Every query not by origin as one aliased `issues` read per round — see the `batch`
5703    /// module.
5704    async fn query_tasks_batch(
5705        &self,
5706        asks: &[(TaskQuery, PageRequest)],
5707    ) -> Vec<Result<Page<Task>, SourceError>> {
5708        self.query_batched(asks).await
5709    }
5710
5711    /// The tokens its dependency walks spelled and the items its writes were answered with, and
5712    /// nothing else: what this source holds across a command is its [`Vocabulary`] — the team's
5713    /// id, its workflow states and the workspace's project statuses — which stays valid in
5714    /// normal use and is read afresh when a name misses. No issue, project, document or search
5715    /// answer outlives the call that read it but what a copy's batched origin read held, and the
5716    /// organization id it carried, which this drops too; and no write's answer outlives the
5717    /// command that wrote it, so the next command already reads each item as a person left it.
5718    async fn end_command(&self) -> Result<(), SourceError> {
5719        self.edges_versions().clear();
5720        self.forget_ahead();
5721        self.forget_origins_ahead(true);
5722        self.written
5723            .lock()
5724            .unwrap_or_else(std::sync::PoisonError::into_inner)
5725            .clear();
5726        self.locations
5727            .lock()
5728            .unwrap_or_else(std::sync::PoisonError::into_inner)
5729            .clear();
5730        self.headings
5731            .lock()
5732            .unwrap_or_else(std::sync::PoisonError::into_inner)
5733            .clear();
5734        // A person may edit an issue between commands, so the whole issue a read answered is
5735        // never a later command's write context.
5736        self.contexts
5737            .lock()
5738            .unwrap_or_else(std::sync::PoisonError::into_inner)
5739            .clear();
5740        self.answered().clear();
5741        Ok(())
5742    }
5743}
5744
5745/// What a whole write's own answer says of the relations its item holds: none for an item it
5746/// created, and for one it rewrote the first page its selection read back.
5747fn held_relations<'a>(
5748    target: Option<&NativeId>,
5749    written: &'a Value,
5750) -> Result<HeldRelations<'a>, SourceError> {
5751    if target.is_none() {
5752        return Ok(HeldRelations::None);
5753    }
5754    written
5755        .get("relations")
5756        .filter(|relations| !relations.is_null())
5757        .map(|_| HeldRelations::Page(written))
5758        .ok_or_else(|| SourceError::Malformed {
5759            message: "a rewrite answered without the relations it was asked for".into(),
5760        })
5761}
5762
5763/// Refuse a narrow project or document write whose payload names another item than the one it
5764/// was sent for, on the terms [`written_is`] refuses an issue's.
5765fn acknowledged(item: &Value, asked: &NativeId, root: MutationRoot) -> Result<(), SourceError> {
5766    let written = backend_id(item, "id")?;
5767    if written == asked.0 {
5768        return Ok(());
5769    }
5770    Err(SourceError::Malformed {
5771        message: format!(
5772            "{} for {asked} answered with the item {written}",
5773            root.as_str()
5774        ),
5775    })
5776}
5777
5778/// Refuse a narrow write's payload naming an issue other than the one it was sent for.
5779///
5780/// An `issueUpdate` answering with another issue is not this write landing, so it is reported
5781/// as the malformed answer it is rather than as the task having been written.
5782fn written_is(issue: &Value, asked: &NativeId) -> Result<(), SourceError> {
5783    let written = backend_id(issue, "id")?;
5784    if written == asked.0 {
5785        return Ok(());
5786    }
5787    Err(SourceError::Malformed {
5788        message: format!("issueUpdate for {asked} answered with the issue {written}"),
5789    })
5790}
5791
5792/// Why a project and a document carry neither [`Task::delivers`] nor [`Task::delivered_by`].
5793///
5794/// Only a task delivers or is delivered, so the two reserved keys name nothing a project or a
5795/// document has. A task keeps both in its description's metadata slot; anything else naming
5796/// one is refused by name rather than written.
5797const NO_DELIVERY: &str = "only a task delivers or is delivered, so neither list has a place \
5798                           on anything else";
5799
5800/// The reserved delivery key `metadata` carries, if it carries one.
5801fn delivery_key_in(metadata: &std::collections::BTreeMap<String, Value>) -> Option<&'static str> {
5802    [TaskRef::DELIVERS_KEY, TaskRef::DELIVERED_BY_KEY]
5803        .into_iter()
5804        .find(|key| metadata.contains_key(*key))
5805}
5806
5807/// A category as the wire spells it — `in-progress`, `queued` — for a message.
5808fn category_word(category: StatusCategory) -> String {
5809    serde_json::to_value(category)
5810        .ok()
5811        .and_then(|value| value.as_str().map(str::to_owned))
5812        .unwrap_or_else(|| format!("{category:?}"))
5813}
5814
5815impl LinearSource {
5816    /// The refusal a write naming `named` — a field or a reserved key — on a `what` gets.
5817    fn undeliverable(&self, named: &str, what: &str) -> SourceError {
5818        SourceError::Refused {
5819            message: format!(
5820                "source {} cannot carry {named} on a {what}: {NO_DELIVERY}; write the {what} \
5821                 without it",
5822                self.name
5823            ),
5824        }
5825    }
5826
5827    /// The backend id of the issue `task` names, or `None` when this source holds no such
5828    /// task — resolved by `get_task` itself, so a comment call and a task read cannot
5829    /// disagree about whether a task is there.
5830    ///
5831    /// The id Linear answers with rather than the one asked for, because `issue(id:)` also
5832    /// takes an identifier such as `ENG-1`, and the comment's own `issue{id}` is compared
5833    /// against — and a comment is created on — the backend id.
5834    async fn commented_issue(&self, task: &NativeId) -> Result<Option<NativeId>, SourceError> {
5835        Ok(self.get_task(task).await?.map(|task| task.id))
5836    }
5837
5838    /// Whether `comment` is a comment on the issue `task` names.
5839    ///
5840    /// Asked before any edit or removal, so an id belonging to another issue — or to no
5841    /// issue, or to nothing — is answered as no such comment without a mutation reaching
5842    /// Linear. `commentUpdate` and `commentDelete` address a comment by its id alone, so
5843    /// without this a task named in error would edit or remove somebody else's comment.
5844    async fn comment_is_on(
5845        &self,
5846        task: &NativeId,
5847        comment: &NativeId,
5848    ) -> Result<bool, SourceError> {
5849        Ok(self.comment_on(task, comment).await?.is_some())
5850    }
5851
5852    /// The body the comment `comment` holds, exactly as Linear holds it, when it is one of
5853    /// `task`'s own — the read [`Self::comment_is_on`] makes, answering with what it selected.
5854    async fn comment_on(
5855        &self,
5856        task: &NativeId,
5857        comment: &NativeId,
5858    ) -> Result<Option<String>, SourceError> {
5859        let Some(issue) = self.commented_issue(task).await? else {
5860            return Ok(None);
5861        };
5862        let data = self.send(graphql::COMMENT, json!({"id":comment.0})).await?;
5863        let held = optional(&data, "comment", |v| {
5864            Ok((comment_issue(v)?, str_at(v, "body")?.to_owned()))
5865        })?;
5866        Ok(held
5867            .filter(|(on, _)| on.as_ref() == Some(&issue))
5868            .map(|(_, body)| body))
5869    }
5870}
5871
5872impl LinearSource {
5873    /// The spelling this source's tokens take: [`change_token::Spelling::Attached`] while the
5874    /// store's cache stands in front of it.
5875    fn spelling(&self) -> change_token::Spelling {
5876        if self.attached() {
5877            change_token::Spelling::Attached
5878        } else {
5879            change_token::Spelling::Plain
5880        }
5881    }
5882
5883    /// Whether the store's cache stands in front of this source.
5884    fn attached(&self) -> bool {
5885        self.attached.load(std::sync::atomic::Ordering::Relaxed)
5886    }
5887
5888    /// The document a read sends: `plain`, or — while the cache stands in front of this source
5889    /// — its counterpart carrying what a `lin1` token's parts are read from.
5890    fn read_document(&self, plain: &'static str) -> &'static str {
5891        if !self.attached() {
5892            return plain;
5893        }
5894        match plain {
5895            ISSUES => graphql::ISSUES_CACHED,
5896            ISSUE => graphql::ISSUE_CACHED,
5897            graphql::ISSUE_DETAIL => graphql::ISSUE_DETAIL_CACHED,
5898            ISSUE_RELATIONS | graphql::ISSUE_DEPENDS_ON | graphql::ISSUE_DEPENDED_ON_BY => {
5899                graphql::ISSUE_RELATIONS_CACHED
5900            }
5901            PROJECTS => graphql::PROJECTS_CACHED,
5902            graphql::COUNTERPART_LOOKUPS => graphql::COUNTERPART_LOOKUPS_CACHED,
5903            PROJECT => graphql::PROJECT_CACHED,
5904            PROJECT_RELATIONS | graphql::PROJECT_DEPENDS_ON | graphql::PROJECT_DEPENDED_ON_BY => {
5905                graphql::PROJECT_RELATIONS_CACHED
5906            }
5907            other => other,
5908        }
5909    }
5910
5911    /// The most rows a projects listing asks for: [`PROJECTS_CACHED_PAGE`] while the cache
5912    /// stands in front of this source, whose relations page prices each row higher, and
5913    /// [`MAX_PAGE_SIZE`] otherwise.
5914    fn projects_page(&self) -> u32 {
5915        if self.attached() {
5916            PROJECTS_CACHED_PAGE
5917        } else {
5918            MAX_PAGE_SIZE
5919        }
5920    }
5921
5922    /// [`Coverage::Covered`](onetaskgraph_plugin_api::Coverage::Covered) while the cache stands
5923    /// in front of this source, and uncovered for `reason` otherwise.
5924    fn attached_coverage(&self, reason: &str) -> onetaskgraph_plugin_api::Coverage {
5925        if self.attached() {
5926            onetaskgraph_plugin_api::Coverage::Covered
5927        } else {
5928            onetaskgraph_plugin_api::Coverage::Uncovered {
5929                reason: reason.to_owned(),
5930            }
5931        }
5932    }
5933
5934    /// Hold what `payload` — a long-form write's own answer — says Linear now stores as the
5935    /// content of `record` `id`, its slot taken off exactly as a read takes it off.
5936    ///
5937    /// # Errors
5938    ///
5939    /// [`SourceError::Malformed`] naming the field when the answer leaves out the long form the
5940    /// write selected, gives it as anything but a string or a null, or ends it in a slot no read
5941    /// could take a content out of: the write landed, and what it stored cannot be vouched for.
5942    fn hold_stored(
5943        &self,
5944        record: MetadataRecord,
5945        id: &NativeId,
5946        payload: &Value,
5947    ) -> Result<(), SourceError> {
5948        let field = match record {
5949            MetadataRecord::Task => "description",
5950            MetadataRecord::Project | MetadataRecord::Document => "content",
5951        };
5952        let malformed = |problem: &str| SourceError::Malformed {
5953            message: format!(
5954                "the answer to a write of {} {} {problem} `{field}`",
5955                record.noun(),
5956                id.0
5957            ),
5958        };
5959        let long_form = match payload.get(field) {
5960            Some(Value::String(long_form)) => Some(long_form.clone()),
5961            Some(Value::Null) => None,
5962            Some(_) => return Err(malformed("gave a non-string")),
5963            None => return Err(malformed("left out the selected")),
5964        };
5965        let (content, _) = metadata_description(long_form)?;
5966        self.stored
5967            .lock()
5968            .unwrap_or_else(std::sync::PoisonError::into_inner)
5969            .insert((record, id.clone()), content.unwrap_or_default());
5970        if let Some(url) = payload.get("url").and_then(Value::as_str) {
5971            self.locations
5972                .lock()
5973                .unwrap_or_else(std::sync::PoisonError::into_inner)
5974                .insert((record, id.clone()), url.to_owned());
5975        }
5976        // Held whole only where the answer selected what a read maps.
5977        let whole = match record {
5978            MetadataRecord::Task | MetadataRecord::Document => payload.get("title").is_some(),
5979            MetadataRecord::Project => payload.get("name").is_some(),
5980        };
5981        self.note_answered(record, id, whole.then_some(payload));
5982        let mut written = self
5983            .written
5984            .lock()
5985            .unwrap_or_else(std::sync::PoisonError::into_inner);
5986        if whole {
5987            written.insert((record, id.clone()), payload.clone());
5988        } else {
5989            written.remove(&(record, id.clone()));
5990        }
5991        Ok(())
5992    }
5993
5994    fn answered(
5995        &self,
5996    ) -> std::sync::MutexGuard<'_, std::collections::HashMap<(MetadataRecord, NativeId), Answered>>
5997    {
5998        // A memo of what responses said: one a panic left behind is read as it stands.
5999        self.answered
6000            .lock()
6001            .unwrap_or_else(std::sync::PoisonError::into_inner)
6002    }
6003
6004    /// Note what a long-form write of the `record` `id` was answered with — the whole item
6005    /// when its selection carried one, and nothing it can vouch for otherwise.
6006    fn note_answered(&self, record: MetadataRecord, id: &NativeId, payload: Option<&Value>) {
6007        let answered = payload.map(|payload| match record {
6008            MetadataRecord::Task => {
6009                let task = map_task(payload, &self.name, &self.statuses, self.spelling()).ok();
6010                Answered {
6011                    version: task.as_ref().and_then(|task| task.version.clone()),
6012                    task,
6013                }
6014            }
6015            MetadataRecord::Project => Answered {
6016                version: map_project(payload, &self.statuses, self.spelling())
6017                    .ok()
6018                    .and_then(|project| project.version),
6019                task: None,
6020            },
6021            MetadataRecord::Document => Answered {
6022                version: map_document(payload)
6023                    .ok()
6024                    .and_then(|document| document.version),
6025                task: None,
6026            },
6027        });
6028        let mut held = self.answered();
6029        match answered {
6030            Some(answered) => {
6031                held.insert((record, id.clone()), answered);
6032            }
6033            None => {
6034                held.remove(&(record, id.clone()));
6035            }
6036        }
6037    }
6038
6039    /// Forget the token an earlier answer gave `id`: a later write of its relations moves what
6040    /// a read would spell, and Linear's answer to that write does not say what.
6041    fn unknown_version(&self, id: &NativeId) {
6042        for answered in self
6043            .answered()
6044            .iter_mut()
6045            .filter(|((_, held), _)| held == id)
6046            .map(|(_, answered)| answered)
6047        {
6048            answered.version = None;
6049            if let Some(task) = answered.task.as_mut() {
6050                task.version = None;
6051            }
6052        }
6053    }
6054
6055    /// What the copy's read ahead read of the `record` `id`, taken.
6056    fn take_ahead(&self, record: MetadataRecord, id: &NativeId) -> Option<Value> {
6057        self.ahead
6058            .lock()
6059            .unwrap_or_else(std::sync::PoisonError::into_inner)
6060            .remove(&(record, id.clone()))
6061    }
6062
6063    /// The forward relations page the copy's read ahead read beside the item `id` of `root`,
6064    /// taken, as the data a relations read of it answers.
6065    fn take_edges_ahead(&self, root: DependencyRoot, id: &NativeId) -> Option<Value> {
6066        let (record, field) = match root {
6067            DependencyRoot::Issue => (MetadataRecord::Task, "issue"),
6068            DependencyRoot::Project => (MetadataRecord::Project, "project"),
6069        };
6070        self.edges_ahead
6071            .lock()
6072            .unwrap_or_else(std::sync::PoisonError::into_inner)
6073            .remove(&(record, id.clone()))
6074            .map(|value| json!({ field: value }))
6075    }
6076
6077    /// Let go of everything the copy's read ahead holds.
6078    fn forget_ahead(&self) {
6079        self.ahead
6080            .lock()
6081            .unwrap_or_else(std::sync::PoisonError::into_inner)
6082            .clear();
6083        self.edges_ahead
6084            .lock()
6085            .unwrap_or_else(std::sync::PoisonError::into_inner)
6086            .clear();
6087    }
6088
6089    /// The whole item the latest long-form write of the `record` `id` was answered with,
6090    /// taken; see [`Self::written`].
6091    fn take_written(&self, record: MetadataRecord, id: &NativeId) -> Option<Value> {
6092        self.written
6093            .lock()
6094            .unwrap_or_else(std::sync::PoisonError::into_inner)
6095            .remove(&(record, id.clone()))
6096    }
6097
6098    fn edges_versions(
6099        &self,
6100    ) -> std::sync::MutexGuard<'_, std::collections::HashMap<EdgesRead, String>> {
6101        // A memo of what responses spelled: one a panic left behind is read as it stands.
6102        self.edges_versions
6103            .lock()
6104            .unwrap_or_else(std::sync::PoisonError::into_inner)
6105    }
6106
6107    /// Note what one page of a dependency walk of the `root` item `id` in `direction` answered,
6108    /// `data` being the response: its token, for the walk's first page; and, for a later one,
6109    /// whether it still agrees with the token the first page spelled — the recorded far ends'
6110    /// page, read from a long form a change of which moves the time the token carries, keeps it
6111    /// only while the rest of the token before its relations part is the same, and a page of
6112    /// relations past the first ends it.
6113    fn note_edges_version(
6114        &self,
6115        root: DependencyRoot,
6116        direction: Direction,
6117        id: &NativeId,
6118        data: &Value,
6119        page: WalkPage,
6120    ) {
6121        if !self.attached() {
6122            return;
6123        }
6124        let item = data.get(root.as_str()).unwrap_or(&Value::Null);
6125        let (whole, before_relations) = match root {
6126            DependencyRoot::Issue => (
6127                change_token::task(item, change_token::Spelling::Attached),
6128                change_token::task_before_relations(item),
6129            ),
6130            DependencyRoot::Project => (
6131                change_token::project_token(item, change_token::Spelling::Attached),
6132                change_token::project_before_relations(item),
6133            ),
6134        };
6135        let read = (root, direction, id.clone());
6136        let mut versions = self.edges_versions();
6137        match page {
6138            WalkPage::First => match whole {
6139                Some(token) => {
6140                    versions.insert(read, token);
6141                }
6142                None => {
6143                    versions.remove(&read);
6144                }
6145            },
6146            WalkPage::Recorded => {
6147                let agrees = versions.get(&read).is_some_and(|held| {
6148                    before_relations.as_deref() == Some(change_token::without_relations(held))
6149                });
6150                if !agrees {
6151                    versions.remove(&read);
6152                }
6153            }
6154            WalkPage::Later => {
6155                versions.remove(&read);
6156            }
6157        }
6158    }
6159}
6160
6161/// What a write's own answer said one item holds, for [`TaskSource::written_task`] and
6162/// [`TaskSource::written_version`].
6163#[derive(Clone)]
6164struct Answered {
6165    /// The item's token after the write, when the answer vouched for one.
6166    version: Option<String>,
6167    /// The task, for a task whose answer carried it whole.
6168    task: Option<Task>,
6169}
6170
6171/// What one read of an item by id is for, which decides whether an attached cache widens it.
6172#[derive(Clone, Copy)]
6173enum Read {
6174    /// A load a caller asked for, whose answer the cache fills an entry from.
6175    Load,
6176    /// A write's own read of its target, which fills nothing.
6177    ForWrite,
6178}
6179
6180/// Which page of a forward-edge walk a response answered.
6181#[derive(Clone, Copy)]
6182enum WalkPage {
6183    /// The first, with the first page of relations.
6184    First,
6185    /// The recorded far ends, after every relation.
6186    Recorded,
6187    /// A page of relations past the first.
6188    Later,
6189}
6190
6191impl LinearSource {
6192    /// One issue as this source reads it, beside its raw `description` — or `None` for an
6193    /// issue Linear does not hold, has trashed, or that is outside the project this source is
6194    /// scoped to.
6195    ///
6196    /// Every read of one issue goes through here, so a status, a content, a metadata and a
6197    /// rendering write all answer "no such task" on exactly the terms `get_task` does. Only a
6198    /// [`Read::Load`] sends the document an attached cache widens: a write's own read of its
6199    /// target fills no entry, so the token's parts would only add complexity, and the task it
6200    /// answers carries no version while the cache is attached.
6201    async fn issue_held(
6202        &self,
6203        id: &NativeId,
6204        read: Read,
6205    ) -> Result<Option<(Task, Option<String>)>, SourceError> {
6206        if let Some(issue) = self.take_ahead(MetadataRecord::Task, id) {
6207            return Ok(optional(&json!({"issue": issue}), "issue", |v| {
6208                Ok((
6209                    map_task(v, &self.name, &self.statuses, self.spelling())?,
6210                    optional_string(v, "description")?,
6211                ))
6212            })?
6213            .filter(|(task, _)| self.in_scope(task.project.as_ref())));
6214        }
6215        let document = match read {
6216            Read::Load => self.read_document(ISSUE),
6217            Read::ForWrite => {
6218                if let Some(issue) = self.take_written(MetadataRecord::Task, id) {
6219                    return Ok(Some((
6220                        map_task(&issue, &self.name, &self.statuses, self.spelling())?,
6221                        optional_string(&issue, "description")?,
6222                    ))
6223                    .filter(|(task, _)| self.in_scope(task.project.as_ref())));
6224                }
6225                ISSUE
6226            }
6227        };
6228        let Some(data) = self
6229            .send_to_read(document, json!({"id":id.0}), Refusal::entity_missing)
6230            .await?
6231        else {
6232            return Ok(None);
6233        };
6234        if let Some(issue) = data.get("issue").filter(|issue| !issue.is_null()) {
6235            self.remember_context(id, issue);
6236        }
6237        Ok(optional(&data, "issue", |v| {
6238            Ok((
6239                map_task(v, &self.name, &self.statuses, self.spelling())?,
6240                optional_string(v, "description")?,
6241            ))
6242        })?
6243        .filter(|(task, _)| self.in_scope(task.project.as_ref())))
6244    }
6245
6246    /// Keep `issue`, as a read or a write of `id` answered it whole, for `write_context`.
6247    fn remember_context(&self, id: &NativeId, issue: &Value) {
6248        if issue.get("description").is_some() && issue.get("state").is_some() {
6249            self.contexts
6250                .lock()
6251                .unwrap_or_else(std::sync::PoisonError::into_inner)
6252                .insert(id.clone(), issue.clone());
6253        }
6254    }
6255
6256    /// [`Self::issue_held`] for a write, with the resolution a status write needs read in the
6257    /// same request — [`graphql::ISSUE_RESOLVED`] — and held as [`Self::vocabulary`] holds it,
6258    /// only when it read completely. A source with no team configured reads the issue alone,
6259    /// and its status write is refused as it always was.
6260    async fn issue_resolving(
6261        &self,
6262        id: &NativeId,
6263    ) -> Result<Option<(Task, Option<String>)>, SourceError> {
6264        let Some(team) = self.team.as_ref() else {
6265            return self.issue_held(id, Read::ForWrite).await;
6266        };
6267        let Some(data) = self
6268            .send_to_read(
6269                graphql::ISSUE_RESOLVED,
6270                json!({"id":id.0,"key":team.0}),
6271                Refusal::entity_missing,
6272            )
6273            .await?
6274        else {
6275            return Ok(None);
6276        };
6277        let read = std::sync::Arc::new(Vocabulary::read(&data, &self.name, &team.0)?);
6278        if let Some(key) = self.shared_key() {
6279            shared::vocabularies().insert(key, read.clone());
6280        }
6281        *self
6282            .vocabulary
6283            .lock()
6284            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(read);
6285        Ok(optional(&data, "issue", |v| {
6286            Ok((
6287                map_task(v, &self.name, &self.statuses, self.spelling())?,
6288                optional_string(v, "description")?,
6289            ))
6290        })?
6291        .filter(|(task, _)| self.in_scope(task.project.as_ref())))
6292    }
6293
6294    /// One issue and the page of its comments `page` names, in one request, on the terms of
6295    /// [`Self::issue_held`] and [`TaskSource::task_comments`] both.
6296    async fn issue_detail(
6297        &self,
6298        id: &NativeId,
6299        page: &PageRequest,
6300    ) -> Result<Option<TaskDetailRead>, SourceError> {
6301        if page.limit == 0 {
6302            return Err(SourceError::Config {
6303                message: "a page limit of 0 is not a page; ask for at least 1 comment".to_owned(),
6304            });
6305        }
6306        let Some(data) = self
6307            .send_to_read(
6308                self.read_document(graphql::ISSUE_DETAIL),
6309                json!({"id":id.0,"last":page.limit.min(MAX_PAGE_SIZE),"before":page.cursor.as_ref().map(|c|&c.0)}),
6310                Refusal::entity_missing,
6311            )
6312            .await?
6313        else {
6314            return Ok(None);
6315        };
6316        Ok(optional(&data, "issue", |v| {
6317            let mut task = map_task(v, &self.name, &self.statuses, self.spelling())?;
6318            // A page resumed from a cursor is not the whole of the comments, so with the cache
6319            // attached — whose token carries their digest — it vouches for no version.
6320            if self.attached() && page.cursor.is_some() {
6321                task.version = None;
6322            }
6323            Ok((task, comment_page(v)?))
6324        })?
6325        .filter(|(task, _)| self.in_scope(task.project.as_ref()))
6326        .map(|(task, comments)| TaskDetailRead {
6327            task,
6328            comments: Some(Ok(Some(comments))),
6329        }))
6330    }
6331
6332    /// One project and its raw `content`, on the terms of [`Self::issue_held`]: a source
6333    /// scoped to one project holds that one alone.
6334    async fn project_held(
6335        &self,
6336        id: &NativeId,
6337        read: Read,
6338    ) -> Result<Option<(Project, Option<String>)>, SourceError> {
6339        if let Some(project) = self.take_ahead(MetadataRecord::Project, id) {
6340            return Ok(optional(&json!({"project": project}), "project", |v| {
6341                Ok((
6342                    map_project(v, &self.statuses, self.spelling())?,
6343                    optional_string(v, "content")?,
6344                ))
6345            })?
6346            .filter(|(project, _)| self.in_scope(Some(&project.id))));
6347        }
6348        let document = match read {
6349            Read::Load => self.read_document(PROJECT),
6350            Read::ForWrite => {
6351                if let Some(project) = self.take_written(MetadataRecord::Project, id) {
6352                    return Ok(Some((
6353                        map_project(&project, &self.statuses, self.spelling())?,
6354                        optional_string(&project, "content")?,
6355                    ))
6356                    .filter(|(project, _)| self.in_scope(Some(&project.id))));
6357                }
6358                PROJECT
6359            }
6360        };
6361        let Some(data) = self
6362            .send_to_read(document, json!({"id":id.0}), Refusal::project_missing)
6363            .await?
6364        else {
6365            return Ok(None);
6366        };
6367        Ok(optional(&data, "project", |v| {
6368            Ok((
6369                map_project(v, &self.statuses, self.spelling())?,
6370                optional_string(v, "content")?,
6371            ))
6372        })?
6373        .filter(|(project, _)| self.in_scope(Some(&project.id))))
6374    }
6375
6376    /// One document and its raw `content`, on the terms of [`Self::issue_held`].
6377    async fn document_held(
6378        &self,
6379        id: &NativeId,
6380    ) -> Result<Option<(Document, Option<String>)>, SourceError> {
6381        // Read as an optional although the pinned `document(id:)` returns `Document!`, for
6382        // the reason `delete_task` records: Linear answers an id naming nothing with an
6383        // errored response rather than a null, and reading the null defensively is what
6384        // keeps a responder that does answer one from being a malformed-response failure.
6385        if let Some(document) = self
6386            .take_written(MetadataRecord::Document, id)
6387            .or_else(|| self.take_ahead(MetadataRecord::Document, id))
6388        {
6389            return Ok(Some((
6390                map_document(&document)?,
6391                optional_string(&document, "content")?,
6392            ))
6393            .filter(|(document, _)| self.in_scope(document.project.as_ref())));
6394        }
6395        let Some(data) = self
6396            .send_to_read(DOCUMENT, json!({"id":id.0}), Refusal::document_missing)
6397            .await?
6398        else {
6399            return Ok(None);
6400        };
6401        Ok(optional(&data, "document", |v| {
6402            Ok((map_document(v)?, optional_string(v, "content")?))
6403        })?
6404        .filter(|(document, _)| self.in_scope(document.project.as_ref())))
6405    }
6406
6407    /// Send one issue's new `description` alone, and nothing else about it, answering the issue
6408    /// as the write's own answer selected it.
6409    async fn write_description_alone(
6410        &self,
6411        id: &NativeId,
6412        description: Option<&str>,
6413    ) -> Result<Value, SourceError> {
6414        let data = self
6415            .send(
6416                graphql::ISSUE_UPDATE,
6417                json!({"id":id.0,"input":{"description":description}}),
6418            )
6419            .await?;
6420        let issue = mutation_payload(&data, MutationRoot::IssueUpdate)?
6421            .get("issue")
6422            .filter(|issue| !issue.is_null())
6423            .ok_or_else(|| SourceError::Malformed {
6424                message: "missing issueUpdate.issue".into(),
6425            })?;
6426        written_is(issue, id)?;
6427        self.hold_stored(MetadataRecord::Task, id, issue)?;
6428        Ok(issue.clone())
6429    }
6430
6431    /// Send one project's new `content` alone, answering the project as the write's own answer
6432    /// selected it.
6433    async fn write_project_content(
6434        &self,
6435        id: &NativeId,
6436        content: Option<&str>,
6437    ) -> Result<Value, SourceError> {
6438        let data = self
6439            .send(
6440                graphql::PROJECT_UPDATE,
6441                json!({"id":id.0,"input":{"content":content}}),
6442            )
6443            .await?;
6444        let project = mutation_payload(&data, MutationRoot::ProjectUpdate)?
6445            .get("project")
6446            .filter(|project| !project.is_null())
6447            .ok_or_else(|| SourceError::Malformed {
6448                message: "missing projectUpdate.project".into(),
6449            })?;
6450        acknowledged(project, id, MutationRoot::ProjectUpdate)?;
6451        self.hold_stored(MetadataRecord::Project, id, project)?;
6452        Ok(project.clone())
6453    }
6454
6455    /// Send one document's new `content` alone, answering the document as the write's own
6456    /// answer selected it.
6457    async fn write_document_content(
6458        &self,
6459        id: &NativeId,
6460        content: Option<&str>,
6461    ) -> Result<Value, SourceError> {
6462        let data = self
6463            .send(
6464                graphql::DOCUMENT_UPDATE,
6465                json!({"id":id.0,"input":{"content":content}}),
6466            )
6467            .await?;
6468        let document = mutation_payload(&data, MutationRoot::DocumentUpdate)?
6469            .get("document")
6470            .filter(|document| !document.is_null())
6471            .ok_or_else(|| SourceError::Malformed {
6472                message: "missing documentUpdate.document".into(),
6473            })?;
6474        acknowledged(document, id, MutationRoot::DocumentUpdate)?;
6475        self.hold_stored(MetadataRecord::Document, id, document)?;
6476        Ok(document.clone())
6477    }
6478
6479    /// What `sources fields` reports — and, with `apply`, does first: every name the mapping
6480    /// gives each kind, checked against that kind's vocabulary, each missing one created when
6481    /// `apply` asks.
6482    ///
6483    /// Created one at a time, tasks' then projects', each in category order, so a create Linear
6484    /// refuses stops the run with every name before it created and reported so. A name present
6485    /// under another type is reported with its type and left exactly as it is: nothing here
6486    /// renames, retypes or deletes.
6487    async fn status_names(&self, apply: bool) -> Result<StatusNamesReport, SourceError> {
6488        let team = self.team.clone().ok_or_else(|| SourceError::Refused {
6489            message: format!(
6490                "source {} needs config.team to report its status names",
6491                self.name
6492            ),
6493        })?;
6494        let (mut vocabulary, _) = self.vocabulary(false).await?;
6495        let mut names = Vec::new();
6496        let mut refused = None;
6497        for kind in [ItemKind::Task, ItemKind::Project] {
6498            for (category, name) in self.statuses.names(kind) {
6499                let found = vocabulary
6500                    .find(kind, name.as_str(), &self.name)?
6501                    .map(|held| held.kind.clone());
6502                let mut mapped = MappedStatusName {
6503                    kind,
6504                    category,
6505                    name: name.clone(),
6506                    found: found.map_or(Found::Missing, Found::Present),
6507                };
6508                if apply && refused.is_none() && mapped.found == Found::Missing {
6509                    match self
6510                        .create_status_name(kind, category, name.as_str(), &vocabulary)
6511                        .await
6512                    {
6513                        Ok(created) => {
6514                            mapped.found = Found::Created(created.held().kind.clone());
6515                            self.remember(&created);
6516                            // Here too, so the next project status goes after this one even
6517                            // when nothing is held.
6518                            std::sync::Arc::make_mut(&mut vocabulary).add(created);
6519                        }
6520                        Err(error) => {
6521                            refused = Some(RefusedCreate {
6522                                kind,
6523                                name: name.clone(),
6524                                message: error.to_string(),
6525                            });
6526                        }
6527                    }
6528                }
6529                names.push(mapped);
6530            }
6531        }
6532        Ok(StatusNamesReport {
6533            source: self.name.clone(),
6534            team,
6535            names,
6536            refused,
6537        })
6538    }
6539
6540    /// Create one name of `kind` — a workflow state on the vocabulary's team, or a project
6541    /// status of the workspace placed after its last — of the type its category derives, in
6542    /// the fixed colour every created name takes.
6543    async fn create_status_name(
6544        &self,
6545        kind: ItemKind,
6546        category: StatusCategory,
6547        name: &str,
6548        vocabulary: &Vocabulary,
6549    ) -> Result<Created, SourceError> {
6550        let kind_of = created_type(category, kind);
6551        let (query, input, root, payload) = match kind {
6552            ItemKind::Task => (
6553                graphql::WORKFLOW_STATE_CREATE,
6554                json!({"teamId": vocabulary.team.0, "name": name, "type": kind_of,
6555                       "color": CREATED_COLOR}),
6556                MutationRoot::WorkflowStateCreate,
6557                "workflowState",
6558            ),
6559            ItemKind::Project => (
6560                graphql::PROJECT_STATUS_CREATE,
6561                json!({"name": name, "type": kind_of, "color": CREATED_COLOR,
6562                       "position": vocabulary.last_position + 1.0}),
6563                MutationRoot::ProjectStatusCreate,
6564                "status",
6565            ),
6566        };
6567        let data = self.send(query, json!({ "input": input })).await?;
6568        let created = mutation_payload(&data, root)?
6569            .get(payload)
6570            .filter(|created| !created.is_null())
6571            .ok_or_else(|| SourceError::Malformed {
6572                message: format!("missing {}.{payload}", root.as_str()),
6573            })?;
6574        let held = Held::read(created)?;
6575        // Held only as what was asked for: an answer naming another name or type would be
6576        // remembered as this mapping's name, and reported created, when it is not.
6577        if held.name.as_str() != name || held.kind != kind_of {
6578            return Err(SourceError::Malformed {
6579                message: format!(
6580                    "Linear answered the create of {} {name:?} of type {kind_of} with {:?} of \
6581                     type {}",
6582                    vocabulary_word(kind),
6583                    held.name.as_str(),
6584                    held.kind
6585                ),
6586            });
6587        }
6588        Ok(match kind {
6589            ItemKind::Task => Created::State(held),
6590            // Placed where Linear says it put it, so the next one goes after.
6591            ItemKind::Project => Created::Status {
6592                position: position_of(created)?,
6593                held,
6594            },
6595        })
6596    }
6597}
6598
6599/// `held` with its trailing metadata slot replaced by one holding exactly `slot`, and every
6600/// byte above the slot exactly as it was — or with a slot appended after one blank line where
6601/// it had none, and the slot taken off, with the one blank line that set it off, where `slot`
6602/// is empty.
6603///
6604/// The one place a narrow metadata write composes a long-form field, so a metadata set, a
6605/// `delivered_by` write and a copy-link record move nothing a person wrote.
6606fn reslotted(
6607    held: Option<&str>,
6608    slot: &std::collections::BTreeMap<String, Value>,
6609) -> Result<Option<String>, SourceError> {
6610    let held = held.unwrap_or_default();
6611    let Some((start, _, _)) = slot_bounds(held)? else {
6612        return LinearSource::described((!held.is_empty()).then_some(held), slot);
6613    };
6614    let above = &held[..start];
6615    if slot.is_empty() {
6616        let visible = content_above(above);
6617        return Ok((!visible.is_empty()).then(|| visible.to_owned()));
6618    }
6619    Ok(Some(format!("{above}{}", slot_text(slot)?)))
6620}
6621
6622/// The address a new upload's URL is spelled at before it is uploaded, as long as the one
6623/// `fileUpload` answers: three UUIDs under Linear's file storage host.
6624const PREDICTED_UPLOAD_URL: &str = "https://uploads.linear.app/00000000-0000-0000-0000-000000000000/00000000-0000-0000-0000-000000000000/00000000-0000-0000-0000-000000000000";
6625
6626/// `content` and `metadata` as a write carrying `assets` sends them: every reference rewritten
6627/// to its recorded URL, or to one as long as an upload's for an asset not uploaded yet.
6628fn served(
6629    content: Option<&str>,
6630    metadata: &std::collections::BTreeMap<String, Value>,
6631    assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
6632) -> (Option<String>, std::collections::BTreeMap<String, Value>) {
6633    let mut metadata = metadata.clone();
6634    let Some(assets) = assets else {
6635        return (content.map(str::to_owned), metadata);
6636    };
6637    let mut uploads = onetaskgraph_plugin_api::AssetUploads::default();
6638    for asset in &assets.assets {
6639        let url = assets
6640            .recorded_assets
6641            .as_ref()
6642            .and_then(|recorded| recorded.reusable(&asset.name, &asset.sha256))
6643            .unwrap_or(PREDICTED_UPLOAD_URL)
6644            .to_owned();
6645        uploads.0.insert(
6646            asset.name.clone(),
6647            onetaskgraph_plugin_api::AssetUpload {
6648                sha256: asset.sha256.clone(),
6649                url,
6650            },
6651        );
6652    }
6653    let served = onetaskgraph_plugin_api::serve_asset_references(
6654        content.unwrap_or_default(),
6655        &mut metadata,
6656        &uploads,
6657    );
6658    (content.map(|_| served), metadata)
6659}
6660
6661/// The size of a composed long form, in characters, and no limit: Linear states none for an
6662/// issue's description, a project's content or a document's.
6663fn body_size(
6664    composed: Result<Option<String>, SourceError>,
6665) -> Option<onetaskgraph_plugin_api::BodySize> {
6666    let size = composed.ok()?.map_or(0, |body| body.chars().count());
6667    Some(onetaskgraph_plugin_api::BodySize {
6668        size: u64::try_from(size).unwrap_or(u64::MAX),
6669        limit: None,
6670    })
6671}
6672
6673/// Hold `entries` under `key` in one slot's metadata, or no such key when there are none.
6674fn set_task_list(
6675    metadata: &mut std::collections::BTreeMap<String, Value>,
6676    key: &str,
6677    entries: &[TaskRef],
6678) {
6679    if entries.is_empty() {
6680        metadata.remove(key);
6681    } else {
6682        metadata.insert(
6683            key.to_owned(),
6684            Value::Array(
6685                entries
6686                    .iter()
6687                    .map(|entry| Value::String(entry.as_str().to_owned()))
6688                    .collect(),
6689            ),
6690        );
6691    }
6692}
6693
6694/// One page of an issue's comments, oldest first.
6695///
6696/// Linear answered newest first, walking backwards from `before`, so the page is reversed
6697/// and the next cursor is the one *behind* it; see the ruling on comments in this crate's
6698/// module documentation for why the walk runs that way.
6699fn comment_page(v: &Value) -> Result<Page<Comment>, SourceError> {
6700    let c = v.get("comments").ok_or_else(|| SourceError::Malformed {
6701        message: "missing comments connection".into(),
6702    })?;
6703    let mut items = c
6704        .get("nodes")
6705        .and_then(Value::as_array)
6706        .ok_or_else(|| SourceError::Malformed {
6707            message: "missing comment nodes".into(),
6708        })?
6709        .iter()
6710        .map(map_comment)
6711        .collect::<Result<Vec<_>, _>>()?;
6712    items.reverse();
6713    let info = c.get("pageInfo").ok_or_else(|| SourceError::Malformed {
6714        message: "missing pageInfo".into(),
6715    })?;
6716    let older = info
6717        .get("hasPreviousPage")
6718        .and_then(Value::as_bool)
6719        .ok_or_else(|| SourceError::Malformed {
6720            message: "missing boolean pageInfo.hasPreviousPage".into(),
6721        })?;
6722    let next = if older {
6723        Some(Cursor(str_at(info, "startCursor")?.into()))
6724    } else {
6725        None
6726    };
6727    Ok(Page { items, next })
6728}
6729
6730fn map_comment(v: &Value) -> Result<Comment, SourceError> {
6731    let author = match v.get("user") {
6732        None => {
6733            return Err(SourceError::Malformed {
6734                message: "missing comment user field".into(),
6735            });
6736        }
6737        // An integration or a bot: Linear names no user, and this source invents none.
6738        Some(Value::Null) => None,
6739        Some(user) => Some(str_at(user, "displayName")?.to_owned()),
6740    };
6741    // A comment a copy wrote here carries its origin as the hidden marker at the end of its
6742    // body — Linear sets every comment's author and times itself — and is read back with the
6743    // marker taken out and reported as its origin.
6744    Ok(Comment {
6745        origin: None,
6746        id: NativeId(backend_id(v, "id")?.into()),
6747        author,
6748        created_at: time(v, "createdAt")?,
6749        updated_at: time(v, "updatedAt")?,
6750        body: str_at(v, "body")?.into(),
6751        url: optional_string(v, "url")?,
6752    }
6753    .unmarked())
6754}
6755
6756/// The comment a `commentCreate` or `commentUpdate` answered with, as Linear now holds it.
6757fn written_comment(data: &Value, root: MutationRoot) -> Result<Comment, SourceError> {
6758    let comment = mutation_payload(data, root)?
6759        .get("comment")
6760        .ok_or_else(|| SourceError::Malformed {
6761            message: format!("missing {}.comment", root.as_str()),
6762        })?;
6763    map_comment(comment)
6764}
6765
6766/// The issue a comment is on, or `None` for a comment on something else — a project, a
6767/// document, an update — which is a comment no task of this source has.
6768fn comment_issue(v: &Value) -> Result<Option<NativeId>, SourceError> {
6769    match v.get("issue") {
6770        None => Err(SourceError::Malformed {
6771            message: "missing comment issue field".into(),
6772        }),
6773        Some(Value::Null) => Ok(None),
6774        Some(issue) => Ok(Some(NativeId(backend_id(issue, "id")?.into()))),
6775    }
6776}
6777
6778/// Linear relates one Linear item to another and nothing else, so an edge whose far end
6779/// is in a different source is the one edge no `relations` entry can hold. Those edges
6780/// are read from the near item's own [`DependencyEdge::RECORDED_KEY`] metadata, and they
6781/// are served *after* the native relations are spent: a page under this cursor is the
6782/// recorded tail of the same walk, which keeps the native pages exactly what they were.
6783const RECORDED_CURSOR: &str = "onetaskgraph.depends_on:";
6784
6785impl LinearSource {
6786    async fn dependencies(
6787        &self,
6788        query: &str,
6789        root: DependencyRoot,
6790        id: &NativeId,
6791        direction: Direction,
6792        page: &PageRequest,
6793    ) -> Result<Page<DependencyEdge>, SourceError> {
6794        // A cached document's token vouches only for a first page of at most
6795        // `change_token::PAGE` rows, and Linear prices a relations connection by the rows it is
6796        // asked for, so a cached read asks for that many: a wider page buys the cache nothing.
6797        // An item with more takes another request per page, which the hour budget counts.
6798        let ceiling = if matches!(
6799            query,
6800            graphql::ISSUE_RELATIONS_CACHED | graphql::PROJECT_RELATIONS_CACHED
6801        ) {
6802            u32::try_from(change_token::PAGE).unwrap_or(MAX_PAGE_SIZE)
6803        } else {
6804            MAX_PAGE_SIZE
6805        };
6806        let limit = page.limit.min(ceiling);
6807        let cursor = page.cursor.as_ref().map(|c| c.0.as_str());
6808        if let Some(offset) = cursor.and_then(|c| c.strip_prefix(RECORDED_CURSOR)) {
6809            // This cursor resumes the *forward* tail and only a forward walk ever issues
6810            // one, so a reverse read carrying it is resuming a walk it did not come from.
6811            // Serving it would answer a reverse read with forward edges, which is the one
6812            // thing a recorded edge must never do — its reverse is derived from the far
6813            // end and is never written down here.
6814            if direction != Direction::DependsOn {
6815                return Err(SourceError::Malformed {
6816                    message: format!(
6817                        "{RECORDED_CURSOR}{offset} resumes recorded forward edges, which a                          reverse dependency read never issues; resume it in the direction                          that reported it"
6818                    ),
6819                });
6820            }
6821            let offset: usize = offset.parse().map_err(|_| SourceError::Malformed {
6822                message: format!("{RECORDED_CURSOR}{offset} is not a recorded-edge cursor"),
6823            })?;
6824            let d = self
6825                .send(query, json!({"id":id.0,"first":1,"after":null}))
6826                .await?;
6827            self.note_edges_version(root, direction, id, &d, WalkPage::Recorded);
6828            return Ok(recorded_page(
6829                recorded(&d, root, id, &self.name)?,
6830                offset,
6831                limit as usize,
6832            ));
6833        }
6834        let ahead = (cursor.is_none()
6835            && direction == Direction::DependsOn
6836            && limit == MAX_PAGE_SIZE
6837            && matches!(
6838                query,
6839                graphql::ISSUE_DEPENDS_ON | graphql::PROJECT_DEPENDS_ON
6840            ))
6841        .then(|| self.take_edges_ahead(root, id))
6842        .flatten();
6843        let d = match ahead {
6844            Some(d) => d,
6845            None => {
6846                self.send(query, json!({"id":id.0,"first":limit,"after":cursor}))
6847                    .await?
6848            }
6849        };
6850        let walked = if cursor.is_none() {
6851            WalkPage::First
6852        } else {
6853            WalkPage::Later
6854        };
6855        self.note_edges_version(root, direction, id, &d, walked);
6856        let mut answered = relation_page(&d, root, id, direction)?;
6857        // A `related` relation mirroring a link the issue holds is the link's, not a dependency.
6858        if matches!(root, DependencyRoot::Issue) {
6859            let mirrors =
6860                self.mirrored_in(d.pointer("/issue/description").and_then(Value::as_str))?;
6861            if !mirrors.is_empty() {
6862                answered.items.retain(|edge| {
6863                    let far = if direction == Direction::DependsOn {
6864                        edge.to.id()
6865                    } else {
6866                        edge.from.id()
6867                    };
6868                    edge.kind != DependencyKind::Related || !mirrors.contains(far)
6869                });
6870            }
6871        }
6872        // Only forwards: the reverse of a recorded edge is derived from the far end, never
6873        // written down on the near item. They ride on the last page of relations, which read
6874        // the long form they are recorded in, as far as the page has room — so they cost no
6875        // request of their own — and only what does not fit is resumed by a cursor. With the
6876        // store's cache attached they keep a page of their own, because that walk is kept only
6877        // when each page of it reads at one token, and a hit on it costs no request at all.
6878        if answered.next.is_none() && direction == Direction::DependsOn {
6879            let recorded = recorded(&d, root, id, &self.name)?;
6880            let room = if self.attached() {
6881                0
6882            } else {
6883                (limit as usize).saturating_sub(answered.items.len())
6884            };
6885            let total = recorded.len();
6886            answered.items.extend(recorded.into_iter().take(room));
6887            if total > room {
6888                answered.next = Some(Cursor(format!("{RECORDED_CURSOR}{room}")));
6889            }
6890        }
6891        Ok(answered)
6892    }
6893}
6894
6895fn recorded(
6896    d: &Value,
6897    root: DependencyRoot,
6898    id: &NativeId,
6899    name: &SourceName,
6900) -> Result<Vec<DependencyEdge>, SourceError> {
6901    let item = d.get(root.as_str()).ok_or_else(|| SourceError::Malformed {
6902        message: format!("missing {}", root.as_str()),
6903    })?;
6904    let (_, metadata) = metadata_description(optional_string(item, root.long_form())?)?;
6905    // `relations` on an issue holds issues and on a project holds projects, both of this
6906    // workspace — so a same-kind far end in this same source is one Linear itself was
6907    // supposed to hold, and the key is refused rather than quietly read, whether the entry
6908    // left the source out or spelled this one.
6909    DependencyEdge::recorded(
6910        &metadata,
6911        id,
6912        root.item_kind(),
6913        name,
6914        Some(root.item_kind()),
6915    )
6916    .map_err(|message| SourceError::Malformed { message })
6917}
6918
6919fn recorded_page(edges: Vec<DependencyEdge>, offset: usize, limit: usize) -> Page<DependencyEdge> {
6920    let total = edges.len();
6921    let items: Vec<DependencyEdge> = edges.into_iter().skip(offset).take(limit.max(1)).collect();
6922    let end = offset.saturating_add(items.len());
6923    Page {
6924        items,
6925        next: (end < total).then(|| Cursor(format!("{RECORDED_CURSOR}{end}"))),
6926    }
6927}
6928
6929/// The status an issue's workflow state or a project's project status reads as, through this
6930/// instance's `status_mapping` for that kind.
6931///
6932/// A name the kind's mapping names reads as that category, under the name Linear holds — which
6933/// is what lets two states of one type, `Todo` and `Queued`, read as two categories. Every
6934/// other name reads as `unknown` under its own name, whatever its type: Linear has no built-in
6935/// names, so a type is not a category, and reading one as if it were would report a category
6936/// no write of this source could have put it at.
6937fn mapped_status(
6938    v: &Value,
6939    statuses: &StatusMapping,
6940    kind: ItemKind,
6941) -> Result<Status, SourceError> {
6942    let name = str_at(v, "name")?;
6943    Ok(Status {
6944        category: statuses
6945            .category_of(kind, name)
6946            .unwrap_or(StatusCategory::Unknown),
6947        name: name.to_owned(),
6948    })
6949}
6950fn str_at<'a>(v: &'a Value, k: &str) -> Result<&'a str, SourceError> {
6951    v.get(k)
6952        .and_then(Value::as_str)
6953        .ok_or_else(|| SourceError::Malformed {
6954            message: format!("missing string field {k}"),
6955        })
6956}
6957fn map_label(v: &Value) -> Result<Label, SourceError> {
6958    Ok(Label {
6959        id: NativeId(str_at(v, "id")?.into()),
6960        name: str_at(v, "name")?.into(),
6961        color: optional_string(v, "color")?,
6962    })
6963}
6964fn labels_of(v: &Value) -> Result<Vec<Label>, SourceError> {
6965    v.get("nodes")
6966        .and_then(Value::as_array)
6967        .ok_or_else(|| SourceError::Malformed {
6968            message: "missing label nodes".into(),
6969        })?
6970        .iter()
6971        .map(map_label)
6972        .collect()
6973}
6974fn time(v: &Value, k: &str) -> Result<Option<DateTime<Utc>>, SourceError> {
6975    optional_str(v, k)?
6976        .map(|s| {
6977            s.parse().map_err(|e| SourceError::Malformed {
6978                message: format!("invalid {k}: {e}"),
6979            })
6980        })
6981        .transpose()
6982}
6983/// One issue as a task, `source` being this source's configured name.
6984///
6985/// The name is what lets [`TaskRef::listed`] tell `work:I-1` on the issue `I-1` of the
6986/// source `work` apart as that issue itself, rather than recognising only the bare spelling.
6987///
6988/// Its version is the issue's `lin1` token — see [`change_token`] — spelled with the relations part
6989/// when `attached`, and absent when the response does not carry every part whole.
6990fn map_task(
6991    v: &Value,
6992    source: &SourceName,
6993    statuses: &StatusMapping,
6994    spelling: change_token::Spelling,
6995) -> Result<Task, SourceError> {
6996    let (content, mut metadata) = metadata_description(optional_string(v, "description")?)?;
6997    let repositories = Repository::from_metadata(&metadata)
6998        .map_err(|message| SourceError::Malformed { message })?;
6999    let classification = classification_of(&mut metadata)?;
7000    let url = optional_string(v, "url")?;
7001    let id = NativeId(str_at(v, "id")?.into());
7002    // Taken out of the caller's metadata as they are read: a reserved key is this product's,
7003    // and reporting it there as well would hand a consumer two spellings of one list.
7004    let delivers = delivery_list(&mut metadata, TaskRef::DELIVERS_KEY, &id, source)?;
7005    let delivered_by = delivery_list(&mut metadata, TaskRef::DELIVERED_BY_KEY, &id, source)?;
7006    // The `## Links` section the store renders beside an issue's links is not its content.
7007    let content = onetaskgraph_plugin_api::read_content(content, &metadata);
7008    Ok(Task {
7009        version: change_token::task(v, spelling),
7010        id,
7011        // `Issue.identifier` is `String!` and every read of an issue selects it, so a
7012        // response without one is a response this source cannot read rather than an issue
7013        // with no handle — Linear gives every issue one.
7014        key: Some(str_at(v, "identifier")?.into()),
7015        title: str_at(v, "title")?.into(),
7016        content,
7017        status: mapped_status(
7018            v.get("state").ok_or_else(|| SourceError::Malformed {
7019                message: "missing state".into(),
7020            })?,
7021            statuses,
7022            ItemKind::Task,
7023        )?,
7024        priority: issue_priority(v)?,
7025        labels: labels_of(v.get("labels").ok_or_else(|| SourceError::Malformed {
7026            message: "missing labels".into(),
7027        })?)?,
7028        project: filed_under(v)?,
7029        location: web_address(url.as_deref()),
7030        url,
7031        created_at: time(v, "createdAt")?,
7032        updated_at: time(v, "updatedAt")?,
7033        metadata,
7034        repositories,
7035        delivers,
7036        delivered_by,
7037        classification,
7038    })
7039}
7040/// A priority as Linear's `Issue.priority` and its two input members spell it.
7041///
7042/// Linear's own scale, as its published schema describes the field: `0` is no priority,
7043/// `1` urgent, `2` high, `3` normal and `4` low. Normal is this contract's `medium`.
7044const fn linear_priority(priority: Priority) -> u8 {
7045    match priority {
7046        Priority::None => 0,
7047        Priority::Urgent => 1,
7048        Priority::High => 2,
7049        Priority::Medium => 3,
7050        Priority::Low => 4,
7051    }
7052}
7053
7054/// The priority an issue carries, read from `Issue.priority`.
7055///
7056/// Linear declares that field `Float!` while its inputs take an `Int`, so `2` and `2.0` are
7057/// the same answer. Anything else — absent, null, fractional, or outside `0` to `4` — is a
7058/// response this source cannot read, never a guess at the nearest level: a priority reported
7059/// that a filter for it could not find is capability rule 1 broken.
7060fn issue_priority(v: &Value) -> Result<Priority, SourceError> {
7061    let raw = v.get("priority").ok_or_else(|| SourceError::Malformed {
7062        message: "missing number field priority".into(),
7063    })?;
7064    let level = raw.as_f64().filter(|level| level.fract() == 0.0);
7065    Priority::ALL
7066        .into_iter()
7067        .find(|priority| level == Some(f64::from(linear_priority(*priority))))
7068        .ok_or_else(|| SourceError::Malformed {
7069            message: format!(
7070                "field priority is {raw}, which is none of Linear's priorities 0 (none), \
7071                 1 (urgent), 2 (high), 3 (normal) and 4 (low)"
7072            ),
7073        })
7074}
7075
7076/// One delivery list read out of an issue's metadata slot, and removed from it.
7077///
7078/// An entry that is not a task id, that names the issue itself, or that repeats is a
7079/// malformed response naming the task and the entry, never a list quietly shortened.
7080fn delivery_list(
7081    metadata: &mut std::collections::BTreeMap<String, Value>,
7082    key: &str,
7083    task: &NativeId,
7084    source: &SourceName,
7085) -> Result<Vec<TaskRef>, SourceError> {
7086    let held = metadata.remove(key);
7087    TaskRef::from_value(key, task, Some(source), held.as_ref())
7088        .map_err(|message| SourceError::Malformed { message })
7089}
7090/// Remove the two delivery keys from a project's or a document's metadata.
7091///
7092/// Neither is work that delivers anything, so a key there names nothing this contract has,
7093/// and it is not the caller's free metadata either: it is this product's reserved spelling.
7094fn strip_delivery_keys(metadata: &mut std::collections::BTreeMap<String, Value>) {
7095    metadata.remove(TaskRef::DELIVERS_KEY);
7096    metadata.remove(TaskRef::DELIVERED_BY_KEY);
7097}
7098/// Its version is the project's `lin1` token in `spelling`, absent when the response does not
7099/// carry every part whole.
7100fn map_project(
7101    v: &Value,
7102    statuses: &StatusMapping,
7103    spelling: change_token::Spelling,
7104) -> Result<Project, SourceError> {
7105    let (content, mut metadata) = metadata_description(optional_string(v, "content")?)?;
7106    strip_delivery_keys(&mut metadata);
7107    let repositories = Repository::from_metadata(&metadata)
7108        .map_err(|message| SourceError::Malformed { message })?;
7109    let classification = classification_of(&mut metadata)?;
7110    let url = optional_string(v, "url")?;
7111    Ok(Project {
7112        version: change_token::project_token(v, spelling),
7113        id: NativeId(str_at(v, "id")?.into()),
7114        title: str_at(v, "name")?.into(),
7115        content,
7116        status: mapped_status(
7117            v.get("status").ok_or_else(|| SourceError::Malformed {
7118                message: "missing status".into(),
7119            })?,
7120            statuses,
7121            ItemKind::Project,
7122        )?,
7123        labels: labels_of(v.get("labels").ok_or_else(|| SourceError::Malformed {
7124            message: "missing project labels".into(),
7125        })?)?,
7126        location: web_address(url.as_deref()),
7127        url,
7128        created_at: time(v, "createdAt")?,
7129        updated_at: time(v, "updatedAt")?,
7130        metadata,
7131        repositories,
7132        classification,
7133    })
7134}
7135
7136/// Where a Linear entity is: the web address Linear itself reports for it, as a link.
7137///
7138/// Every issue, project and document of a Linear workspace has a page a person can open,
7139/// so this source says so for all three — the counterpart of a folder of Markdown
7140/// reporting the path of the file behind an item. A source that reported nothing here is
7141/// what leaves a reader holding an opaque id, and `None` is reserved for the case Linear
7142/// really did not say, which is not the same as saying the entity is nowhere.
7143fn web_address(url: Option<&str>) -> Option<Location> {
7144    url.map(|url| Location::Url(url.to_owned()))
7145}
7146
7147/// The project a Linear item is filed under, or `None` for one filed under nothing.
7148///
7149/// One reader for issues and documents alike, because the field is the same field: an
7150/// absent `project` key is a malformed response, a null one is an orphan.
7151fn filed_under(v: &Value) -> Result<Option<NativeId>, SourceError> {
7152    match v.get("project") {
7153        None => Err(SourceError::Malformed {
7154            message: "missing project field".into(),
7155        }),
7156        Some(Value::Null) => Ok(None),
7157        Some(project) => Ok(Some(NativeId(str_at(project, "id")?.into()))),
7158    }
7159}
7160
7161/// The classification an item's slot records, taken out of the caller's metadata as it is
7162/// read: the key is this product's, and the item reports it as its own field.
7163fn classification_of(
7164    metadata: &mut std::collections::BTreeMap<String, Value>,
7165) -> Result<Classification, SourceError> {
7166    let classification = Classification::from_metadata(metadata)
7167        .map_err(|message| SourceError::Malformed { message })?;
7168    metadata.remove(Classification::METADATA_KEY);
7169    Ok(classification)
7170}
7171
7172/// `answered`, the id a create's answer gives, held to the id a keyed create sent: Linear's
7173/// published schema takes a caller's `id` as the item's own, so an answer naming another is one
7174/// this source cannot vouch for — and it says so rather than answer an id a retry's lookup by key
7175/// would never find. A refusal is all it is: the item stands where Linear put it, and a later
7176/// retry looking it up by the id sent will not find it there.
7177fn created_as(
7178    answered: NativeId,
7179    sent: Option<&NativeId>,
7180    kind: &str,
7181) -> Result<NativeId, SourceError> {
7182    let Some(sent) = sent else {
7183        return Ok(answered);
7184    };
7185    if answered == *sent {
7186        Ok(answered)
7187    } else {
7188        Err(SourceError::Malformed {
7189            message: format!(
7190                "Linear answered a {kind} create sent with id {} as {}, not the id it was sent; \
7191                 next: inspect that {kind} before copying again, since a retry looks for the id \
7192                 that was sent",
7193                sent.0, answered.0
7194            ),
7195        })
7196    }
7197}
7198
7199/// The create key a create of a new item carries, which it sends as the item's own id.
7200fn create_key_of(
7201    metadata: &std::collections::BTreeMap<String, Value>,
7202    target: Option<&NativeId>,
7203) -> Option<String> {
7204    metadata
7205        .get(MetadataKey::CREATE_KEY)
7206        .and_then(|key| key.as_str().map(str::to_owned))
7207        .filter(|_| target.is_none())
7208}
7209
7210/// The ids a create is sent under, as [`LinearSource::create_id`] chooses them.
7211#[derive(Debug, Clone, PartialEq, Eq)]
7212enum CreateId {
7213    /// None: Linear chooses the id — an update, or a create carrying neither a key nor an
7214    /// origin.
7215    Unchosen,
7216    /// Each generation of the create key the item carries.
7217    Keyed(uuid::Uuid),
7218    /// Each generation of the key [`LinearSource::origin_key`] derives for `origin`: a copy's
7219    /// create that carries an origin and no key of its own.
7220    Origin {
7221        key: uuid::Uuid,
7222        /// The origin the item records, which a record already holding one of those ids is
7223        /// confirmed against.
7224        origin: String,
7225    },
7226}
7227
7228fn record_noun(record: MetadataRecord) -> &'static str {
7229    match record {
7230        MetadataRecord::Task => "issue",
7231        MetadataRecord::Project => "project",
7232        MetadataRecord::Document => "document",
7233    }
7234}
7235
7236/// The id a create carrying `key` is sent to Linear under: the key — a version-5 UUID — with its
7237/// version nibble set to 4 and its RFC 4122 variant kept, because Linear's published schema
7238/// (`IssueCreateInput.id`, `ProjectCreateInput.id` and `DocumentCreateInput.id` in
7239/// linear/linear's `packages/sdk/src/schema.graphql`) documents the id as "in UUID v4 format".
7240/// Deterministic, so every attempt at one create sends, and looks up, the same id; the key itself
7241/// stays verbatim in the item's slot at `onetaskgraph.create_key`.
7242///
7243/// # Errors
7244///
7245/// [`SourceError::Malformed`] for a key that is not a hyphenated RFC 4122 UUID.
7246pub fn linear_id_of_key(key: &str) -> Result<String, SourceError> {
7247    let shaped = key.len() == 36
7248        && key.char_indices().all(|(at, character)| match at {
7249            8 | 13 | 18 | 23 => character == '-',
7250            _ => character.is_ascii_hexdigit(),
7251        });
7252    if !shaped {
7253        return Err(SourceError::Malformed {
7254            message: format!("create key {key:?} is not a hyphenated UUID"),
7255        });
7256    }
7257    // The variant is kept, so it has to be RFC 4122's already for the id to be a v4 UUID.
7258    let mut id = key.to_ascii_lowercase();
7259    if !matches!(id.as_bytes()[19], b'8' | b'9' | b'a' | b'b') {
7260        return Err(SourceError::Malformed {
7261            message: format!("create key {key:?} is not an RFC 4122 UUID"),
7262        });
7263    }
7264    id.replace_range(14..15, "4");
7265    Ok(id)
7266}
7267
7268/// Every id a create carrying `key` is sent under, in the order it is tried: [`linear_id_of_key`]
7269/// first — the one id every release before this one sent, so an item written under it still
7270/// reads back — and then [`CREATE_ID_GENERATIONS`] − 1 more, each that id with its last octet
7271/// XORed with the generation's number, so still a v4 UUID of RFC 4122's variant.
7272///
7273/// More than one because Linear lets an id name one record ever: a create whose key derived an
7274/// id a since-deleted record held — a copy's undo of an earlier attempt removes what it made —
7275/// or one of another workspace holds is refused, and only another id lets that create land.
7276/// Deterministic, so every attempt at one create sends, and looks up, the same ids.
7277///
7278/// # Errors
7279///
7280/// [`SourceError::Malformed`] for a key that is not a hyphenated RFC 4122 UUID.
7281pub fn linear_ids_of_key(key: &str) -> Result<Vec<String>, SourceError> {
7282    let first = linear_id_of_key(key)?;
7283    let (head, last) = first.split_at(34);
7284    let octet = u8::from_str_radix(last, 16).map_err(|_| SourceError::Malformed {
7285        message: format!("create key {key:?} is not a hyphenated UUID"),
7286    })?;
7287    Ok((0..CREATE_ID_GENERATIONS)
7288        .map(|generation| format!("{head}{:02x}", octet ^ generation))
7289        .collect())
7290}
7291
7292fn map_document(v: &Value) -> Result<Document, SourceError> {
7293    let (content, mut metadata) = metadata_description(optional_string(v, "content")?)?;
7294    strip_delivery_keys(&mut metadata);
7295    let repositories = Repository::from_metadata(&metadata)
7296        .map_err(|message| SourceError::Malformed { message })?;
7297    let classification = classification_of(&mut metadata)?;
7298    let url = optional_string(v, "url")?;
7299    Ok(Document {
7300        version: change_token::document_token(v),
7301        id: NativeId(str_at(v, "id")?.into()),
7302        title: str_at(v, "title")?.into(),
7303        content,
7304        project: filed_under(v)?,
7305        // Linear's `Document` carries no labels, and that is the published schema rather
7306        // than a gap here: the types of it that carry `labels` are `Issue`, `Project`,
7307        // `Team`, `Initiative` and `Organization`. Reporting none is what a source with no
7308        // native slot owes; standing one up beside a first-class type is what this source
7309        // exists not to do, and `write_document` refuses a label by name for the same
7310        // reason rather than dropping it.
7311        labels: Vec::new(),
7312        location: web_address(url.as_deref()),
7313        url,
7314        created_at: time(v, "createdAt")?,
7315        updated_at: time(v, "updatedAt")?,
7316        metadata,
7317        repositories,
7318        classification,
7319    })
7320}
7321
7322/// Whether this document satisfies the predicates this source applies to a fetched page.
7323///
7324/// Two of them reach a page rather than the `documents(filter:)` variables, and each for a
7325/// reason of Linear's own. `DocumentFilter.project` is a `ProjectFilter` where
7326/// `IssueFilter.project` is a `NullableProjectFilter`, so only the issue side can be asked
7327/// for the items belonging to no project. And a Linear document carries no label at all,
7328/// so a query demanding one keeps nothing and a query excluding one keeps everything —
7329/// which is this source *applying* the predicate it declares native, over the labels the
7330/// document really has, rather than ignoring it.
7331fn document_matches(document: &Document, project: &ProjectFilter, labels: &LabelFilter) -> bool {
7332    let carries = |name: &String| {
7333        document
7334            .labels
7335            .iter()
7336            .any(|label| label.name.eq_ignore_ascii_case(name))
7337    };
7338    let filed = match project {
7339        ProjectFilter::Any => true,
7340        ProjectFilter::Orphans => document.project.is_none(),
7341        ProjectFilter::Is(id) => document.project.as_ref() == Some(id),
7342    };
7343    filed
7344        && (labels.any_of.is_empty() || labels.any_of.iter().any(&carries))
7345        && labels.all_of.iter().all(&carries)
7346        && !labels.none_of.iter().any(&carries)
7347}
7348
7349fn optional<T>(
7350    d: &Value,
7351    k: &str,
7352    f: impl Fn(&Value) -> Result<T, SourceError>,
7353) -> Result<Option<T>, SourceError> {
7354    match d.get(k) {
7355        None => Err(SourceError::Malformed {
7356            message: format!("missing {k}"),
7357        }),
7358        Some(Value::Null) => Ok(None),
7359        // An item Linear no longer shows is not an item this source holds, and Linear says
7360        // so with `archivedAt` rather than by answering null.
7361        //
7362        // **None of Linear's three `delete` verbs removes anything.** `issueDelete`,
7363        // `projectDelete` and `documentDelete` move the item to the trash: observed on
7364        // 2026-09-04, each answered `success: true` and the item still read back by id,
7365        // carrying `archivedAt` and `trashed: true`. Its separate *archive* verb is a third
7366        // state — `archivedAt` set, `trashed` null — and Linear excludes both from every
7367        // connection, so `issues`, `projects` and `documents` had already stopped returning
7368        // them while a read by id still did.
7369        //
7370        // `archivedAt` rather than `trashed` for exactly that reason: it is the marker both
7371        // states share, so a read by id answers what a listing answers, and a delete means
7372        // what a copy's undo needs it to mean — the item this run created is gone.
7373        Some(value) if !matches!(value.get("archivedAt"), None | Some(Value::Null)) => Ok(None),
7374        Some(value) => f(value).map(Some),
7375    }
7376}
7377fn connection<T>(
7378    d: &Value,
7379    k: &str,
7380    f: impl Fn(&Value) -> Result<T, SourceError>,
7381) -> Result<Page<T>, SourceError> {
7382    let c = d.get(k).ok_or_else(|| SourceError::Malformed {
7383        message: format!("missing {k} connection"),
7384    })?;
7385    let items = c
7386        .get("nodes")
7387        .and_then(Value::as_array)
7388        .ok_or_else(|| SourceError::Malformed {
7389            message: "missing nodes".into(),
7390        })?
7391        .iter()
7392        .map(f)
7393        .collect::<Result<_, _>>()?;
7394    let next = page_next(c)?;
7395    Ok(Page { items, next })
7396}
7397#[derive(Clone, Copy, PartialEq, Eq, Hash)]
7398enum DependencyRoot {
7399    Issue,
7400    Project,
7401}
7402impl DependencyRoot {
7403    const fn item_kind(self) -> ItemKind {
7404        match self {
7405            Self::Issue => ItemKind::Task,
7406            Self::Project => ItemKind::Project,
7407        }
7408    }
7409    const fn as_str(self) -> &'static str {
7410        match self {
7411            Self::Issue => "issue",
7412            Self::Project => "project",
7413        }
7414    }
7415    /// The field holding the item's long form and its metadata slot: an issue's
7416    /// `description`, a project's `content`.
7417    const fn long_form(self) -> &'static str {
7418        match self {
7419            Self::Issue => "description",
7420            Self::Project => "content",
7421        }
7422    }
7423}
7424fn relation_page(
7425    d: &Value,
7426    root: DependencyRoot,
7427    id: &NativeId,
7428    direction: Direction,
7429) -> Result<Page<DependencyEdge>, SourceError> {
7430    let key = if direction == Direction::DependsOn {
7431        "relations"
7432    } else {
7433        "inverseRelations"
7434    };
7435    let c = d
7436        .get(root.as_str())
7437        .and_then(|v| v.get(key))
7438        .ok_or_else(|| SourceError::Malformed {
7439            message: format!("missing {key}"),
7440        })?;
7441    let nodes = c
7442        .get("nodes")
7443        .and_then(Value::as_array)
7444        .ok_or_else(|| SourceError::Malformed {
7445            message: "missing relation nodes".into(),
7446        })?;
7447    let mut items = Vec::new();
7448    for n in nodes {
7449        let other = n
7450            .get(if direction == Direction::DependsOn {
7451                "relatedIssue"
7452            } else {
7453                "issue"
7454            })
7455            .or_else(|| {
7456                n.get(if direction == Direction::DependsOn {
7457                    "relatedProject"
7458                } else {
7459                    "project"
7460                })
7461            })
7462            .and_then(|v| v.get("id"))
7463            .and_then(Value::as_str)
7464            .ok_or_else(|| SourceError::Malformed {
7465                message: "missing related id".into(),
7466            })?;
7467        let (from, to) = if direction == Direction::DependsOn {
7468            (id.clone(), NativeId(other.into()))
7469        } else {
7470            (NativeId(other.into()), id.clone())
7471        };
7472        // llmlint: ignore-block[contracts_have_one_source_or_a_drift_gate] Linear publishes relation type as a string in the accepted 2026-08-24 schema; this boundary deliberately rejects every undocumented value, and real-HTTP tests prove both accepted values and rejection.
7473        let relation_type =
7474            n.get("type")
7475                .and_then(Value::as_str)
7476                .ok_or_else(|| SourceError::Malformed {
7477                    message: "missing relation type".into(),
7478                })?;
7479        // An issue relation and a project relation do not share a vocabulary. Linear
7480        // spells a project dependency `dependency`, where an issue's is `blocks`; the
7481        // write side sends exactly that pair and says why. So each root reads only its
7482        // own, and a value the other root would have accepted is refused here rather than
7483        // read as an edge this source could not have written.
7484        //
7485        // `related` is one of those values, and only an issue relation has it. Linear's
7486        // validator enumerates a project relation's `type` as `dependency` alone — see
7487        // the write side, which had `related` refused by the real API on 2026-09-04 — so
7488        // a project relation typed `related` is not a relation this workspace can hold.
7489        let kind = match (root, relation_type) {
7490            (DependencyRoot::Issue, "blocks") | (DependencyRoot::Project, "dependency") => {
7491                DependencyKind::Blocks
7492            }
7493            (DependencyRoot::Issue, "related") => DependencyKind::Related,
7494            _ => {
7495                return Err(SourceError::Malformed {
7496                    message: format!(
7497                        "invalid relation type: {relation_type} on a {} relation",
7498                        root.as_str()
7499                    ),
7500                });
7501            }
7502        };
7503        // llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate]
7504        let item_kind = root.item_kind();
7505        items.push(DependencyEdge {
7506            from: DependencyEndpoint::from_native(from, item_kind),
7507            to: DependencyEndpoint::from_native(to, item_kind),
7508            kind,
7509        });
7510    }
7511    let next = page_next(c)?;
7512    Ok(Page { items, next })
7513}
7514
7515fn optional_str<'a>(v: &'a Value, k: &str) -> Result<Option<&'a str>, SourceError> {
7516    match v.get(k) {
7517        None => Err(SourceError::Malformed {
7518            message: format!("missing field {k}"),
7519        }),
7520        Some(Value::Null) => Ok(None),
7521        Some(value) => value
7522            .as_str()
7523            .map(Some)
7524            .ok_or_else(|| SourceError::Malformed {
7525                message: format!("field {k} is not a string"),
7526            }),
7527    }
7528}
7529
7530/// Linear has no caller-defined fields. The source owns an unobtrusive Markdown comment at the
7531/// end of the long-form field, and writes it on one line with the canonical JSON inside a code
7532/// span: ``<!-- onetaskgraph.metadata `{…}` -->``. The code span is the one spelling Linear keeps
7533/// byte for byte in a description or a document — see the module documentation's ruling on what
7534/// Linear does to an HTML comment — and [`slot_json`] escapes the three characters that could
7535/// end it early.
7536const METADATA_PREFIX: &str = "<!-- onetaskgraph.metadata";
7537/// The opening of the slot this source writes.
7538const METADATA_OPEN_SPAN: &str = "<!-- onetaskgraph.metadata `";
7539/// The close of the slot this source writes.
7540const METADATA_CLOSE_SPAN: &str = "` -->";
7541/// The opening of the multi-line slot this source wrote before the code span, still read: an
7542/// item written then keeps its metadata. Linear normalized its JSON, so a key or a value
7543/// Linear rewrote reads back as Linear left it — or, for an array Linear escaped, as a
7544/// malformed slot naming itself — and the next write of that item writes the code span.
7545const METADATA_OPEN: &str = "<!-- onetaskgraph.metadata\n";
7546const METADATA_CLOSE: &str = "\n-->";
7547/// The same close as Linear hands that multi-line slot back: it escapes a line opening
7548/// `-->`, so the slot reads back with a backslash before its close (observed from the real API
7549/// on 2026-09-14 for a document and on 2026-10-02 for an issue's description too).
7550const METADATA_CLOSE_ESCAPED: &str = "\n\\-->";
7551
7552/// One JSON value in the encoding the slot holds it in: compact canonical JSON with `<`, `>`
7553/// and `` ` `` escaped as `\u003c`, `\u003e` and `\u0060`.
7554///
7555/// All three only ever occur inside a JSON string, where the escape means the same character,
7556/// so the value parses back exactly; and with them escaped no value can close the code span or
7557/// the HTML comment around it. A search phrase is not built with this: `slot_phrase` sends only
7558/// a value none of whose characters any encoder escapes, which this leaves as written.
7559fn slot_json(value: &impl serde::Serialize) -> Result<String, SourceError> {
7560    let encoded = serde_json::to_string(value).map_err(|error| SourceError::Malformed {
7561        message: error.to_string(),
7562    })?;
7563    Ok(encoded
7564        .replace('<', "\\u003c")
7565        .replace('>', "\\u003e")
7566        .replace('`', "\\u0060"))
7567}
7568
7569/// The slot holding exactly `metadata`, as this source writes it.
7570fn slot_text(metadata: &std::collections::BTreeMap<String, Value>) -> Result<String, SourceError> {
7571    Ok(format!(
7572        "{METADATA_OPEN_SPAN}{}{METADATA_CLOSE_SPAN}",
7573        slot_json(metadata)?
7574    ))
7575}
7576
7577/// The members a body travels under in a request's variables and an answer's data: an issue's
7578/// `description`, a project's and a document's `content`, and a comment's `body`.
7579const BODY_MEMBERS: [&str; 3] = ["description", "content", "body"];
7580
7581/// `value` with `apply` applied to every string held under one of [`BODY_MEMBERS`], at any depth.
7582/// A member holding anything but a string — a filter on a description, say — is walked into and
7583/// otherwise left as it is.
7584fn marked(value: Value, apply: &dyn Fn(&str) -> String) -> Value {
7585    match value {
7586        Value::Object(object) => Value::Object(
7587            object
7588                .into_iter()
7589                .map(|(key, held)| {
7590                    let held = match held {
7591                        Value::String(body) if BODY_MEMBERS.contains(&key.as_str()) => {
7592                            Value::String(apply(&body))
7593                        }
7594                        other => marked(other, apply),
7595                    };
7596                    (key, held)
7597                })
7598                .collect(),
7599        ),
7600        Value::Array(items) => {
7601            Value::Array(items.into_iter().map(|item| marked(item, apply)).collect())
7602        }
7603        other => other,
7604    }
7605}
7606
7607/// Where the trailing metadata slot of `description` is: the byte its opening marker starts
7608/// at, and the span of the encoded JSON inside it — or `None` when it ends in no slot.
7609///
7610/// The one place the slot is recognised, in either spelling, so what [`metadata_description`]
7611/// reads out and what [`metadata_slot`] keeps for a content write are the same bytes.
7612fn slot_bounds(description: &str) -> Result<Option<(usize, usize, usize)>, SourceError> {
7613    let Some(start) = description.rfind(METADATA_PREFIX) else {
7614        return Ok(None);
7615    };
7616    let rest = &description[start..];
7617    let (encoded_start, close) = if rest.starts_with(METADATA_OPEN_SPAN) {
7618        let encoded_start = start + METADATA_OPEN_SPAN.len();
7619        (
7620            encoded_start,
7621            description[encoded_start..]
7622                .rfind(METADATA_CLOSE_SPAN)
7623                .map(|at| (at, METADATA_CLOSE_SPAN.len())),
7624        )
7625    } else if rest.starts_with(METADATA_OPEN) {
7626        let encoded_start = start + METADATA_OPEN.len();
7627        (
7628            encoded_start,
7629            [METADATA_CLOSE, METADATA_CLOSE_ESCAPED]
7630                .into_iter()
7631                .filter_map(|close| {
7632                    description[encoded_start..]
7633                        .find(close)
7634                        .map(|at| (at, close.len()))
7635                })
7636                .min(),
7637        )
7638    } else {
7639        return Ok(None);
7640    };
7641    let Some((relative_end, close_len)) = close else {
7642        return Err(SourceError::Malformed {
7643            message: "unterminated onetaskgraph metadata slot in Linear description".into(),
7644        });
7645    };
7646    let encoded_end = encoded_start + relative_end;
7647    if !description[encoded_end + close_len..].trim().is_empty() {
7648        return Ok(None);
7649    }
7650    Ok(Some((start, encoded_start, encoded_end)))
7651}
7652
7653/// The metadata slot `description` ends in, exactly as it is stored, or `None`.
7654fn metadata_slot(description: &str) -> Result<Option<&str>, SourceError> {
7655    Ok(slot_bounds(description)?.map(|(start, _, _)| &description[start..]))
7656}
7657
7658fn metadata_description(
7659    description: Option<String>,
7660) -> Result<(Option<String>, std::collections::BTreeMap<String, Value>), SourceError> {
7661    let Some(description) = description else {
7662        return Ok((None, Default::default()));
7663    };
7664    let Some((start, encoded_start, encoded_end)) = slot_bounds(&description)? else {
7665        return Ok((Some(description), Default::default()));
7666    };
7667    let metadata =
7668        serde_json::from_str(&description[encoded_start..encoded_end]).map_err(|error| {
7669            SourceError::Malformed {
7670                message: format!(
7671                    "invalid canonical JSON in Linear onetaskgraph metadata slot: {error}"
7672                ),
7673            }
7674        })?;
7675    let visible = content_above(&description[..start]);
7676    Ok(((!visible.is_empty()).then(|| visible.to_owned()), metadata))
7677}
7678
7679/// The content of a long-form field whose text above its metadata slot is `above`: that text
7680/// less the separator [`LinearSource::described`] sets the slot off by, and never a byte of the
7681/// content itself.
7682///
7683/// The separator is one blank line, so content whose own end is whitespace reads back as
7684/// itself. One shape Linear stores in its own way, and spike `spike-linear-stored-content`
7685/// measured it on an issue and a document alike: content S ending in a table row ends with that
7686/// row's line break, as Linear stores a table, and `S + "\n\n" + slot` is then stored as
7687/// `S + "\n" + slot` — one blank line between the table and the slot rather than two. So text
7688/// above the slot ending in a table row and one blank line is S with its own last line break
7689/// kept, and only the blank line is the separator; text ending in two blank lines after a row,
7690/// as a store keeping every byte holds it, is S and the whole separator, so the two read alike.
7691/// A field edited in Linear down to a single line break before the slot loses just that one.
7692fn content_above(above: &str) -> &str {
7693    let Some(visible) = above.strip_suffix("\n\n") else {
7694        return above.strip_suffix('\n').unwrap_or(above);
7695    };
7696    let last = visible.rsplit('\n').next().unwrap_or_default().trim();
7697    if last.len() > 1 && last.starts_with('|') && last.ends_with('|') {
7698        &above[..above.len() - 1]
7699    } else {
7700        visible
7701    }
7702}
7703
7704/// The narrowing that asks Linear for the issues whose description holds `"<value>"` — a
7705/// string `value` as any JSON encoder writes it, quotes included — or `None` when `value` holds
7706/// a character an encoder may write another way, and only the confirmation decides.
7707///
7708/// A candidate set rather than the answer: the phrase can sit in the visible prose, or under
7709/// another key, and both are kept out by the confirmation over the parsed slot that follows
7710/// every read. What it cannot do is miss an issue whose slot holds the value — in the code span
7711/// this source writes, in the multi-line slot it wrote before, or in one a person spaced or
7712/// re-encoded by hand — which is what makes sending it sound. So it names the value alone, never
7713/// the key beside it, whose spacing a slot is free to vary; and only a value of printable ASCII
7714/// none of whose characters any encoder escapes — not `"`, `\`, `/`, `<`, `>`, `&`, `'` or a
7715/// backtick — because one that is escaped would be spelled in a stored slot otherwise than here.
7716fn slot_phrase(value: &str) -> Option<Value> {
7717    let verbatim = value.chars().all(|character| {
7718        (character.is_ascii_graphic() && !"\"\\/<>&'`".contains(character)) || character == ' '
7719    });
7720    verbatim.then(|| json!({"description": {"contains": format!("\"{value}\"")}}))
7721}
7722
7723/// Whether `title`/`content` satisfies `query`, case-insensitively — the contract's own rule,
7724/// which the engine applies for a source that does not search, so the two cannot answer one
7725/// workspace differently.
7726fn text_holds(title: &str, content: Option<&str>, query: &TextQuery) -> bool {
7727    let terms = query.terms.to_lowercase();
7728    let in_title = title.to_lowercase().contains(&terms);
7729    let in_content = content.is_some_and(|body| body.to_lowercase().contains(&terms));
7730    match query.fields {
7731        TextFields::Title => in_title,
7732        TextFields::Content => in_content,
7733        TextFields::TitleOrContent => in_title || in_content,
7734    }
7735}
7736
7737fn optional_string(v: &Value, k: &str) -> Result<Option<String>, SourceError> {
7738    Ok(optional_str(v, k)?.map(Into::into))
7739}
7740fn backend_id<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
7741    let id = str_at(value, field)?;
7742    (!id.is_empty())
7743        .then_some(id)
7744        .ok_or_else(|| SourceError::Malformed {
7745            message: format!("field {field} is an empty backend id"),
7746        })
7747}
7748fn mutation_payload(data: &Value, root: MutationRoot) -> Result<&Value, SourceError> {
7749    let root = root.as_str();
7750    let payload = data.get(root).ok_or_else(|| SourceError::Malformed {
7751        message: format!("missing {root}"),
7752    })?;
7753    match payload.get("success").and_then(Value::as_bool) {
7754        Some(true) => Ok(payload),
7755        Some(false) => Err(SourceError::Refused {
7756            message: format!("Linear reported {root} was unsuccessful"),
7757        }),
7758        None => Err(SourceError::Malformed {
7759            message: format!("missing boolean {root}.success"),
7760        }),
7761    }
7762}
7763fn page_next(c: &Value) -> Result<Option<Cursor>, SourceError> {
7764    let info = c.get("pageInfo").ok_or_else(|| SourceError::Malformed {
7765        message: "missing pageInfo".into(),
7766    })?;
7767    let more = info
7768        .get("hasNextPage")
7769        .and_then(Value::as_bool)
7770        .ok_or_else(|| SourceError::Malformed {
7771            message: "missing boolean pageInfo.hasNextPage".into(),
7772        })?;
7773    if !more {
7774        return Ok(None);
7775    }
7776    let cursor = str_at(info, "endCursor")?;
7777    Ok(Some(Cursor(cursor.into())))
7778}
7779
7780// llmlint: ignore-block[contracts_have_one_source_or_a_drift_gate] https://linear.app/developers/rate-limiting documents these headers and epoch milliseconds, but Linear publishes no machine-readable definition of its codes and headers. One shared parser serves GraphQL and asset HTTP requests; the loopback rate-limit journeys and live asset journey hold the documented response contract.
7781fn reset_wait(headers: &reqwest::header::HeaderMap) -> Option<std::time::Duration> {
7782    use std::time::Duration;
7783    let reset = [
7784        "x-ratelimit-endpoint-requests-reset",
7785        "x-ratelimit-requests-reset",
7786        "x-ratelimit-complexity-reset",
7787    ]
7788    .iter()
7789    .filter_map(|name| headers.get(*name)?.to_str().ok()?.parse::<u64>().ok())
7790    .max();
7791    reset
7792        .map(|reset| {
7793            Duration::from_millis(reset.saturating_sub(
7794                u64::try_from(chrono::Utc::now().timestamp_millis()).unwrap_or_default(),
7795            ))
7796        })
7797        .or_else(|| {
7798            headers
7799                .get("retry-after")?
7800                .to_str()
7801                .ok()?
7802                .parse::<u64>()
7803                .ok()
7804                .map(Duration::from_secs)
7805        })
7806}
7807// llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate]