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