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