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