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