Skip to main content

onetaskgraph_linear/
lib.rs

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