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