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