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