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