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