Skip to main content

onetaskgraph_plugin_api/
work.rs

1//! The work items every source is normalised into.
2
3use chrono::{DateTime, Utc};
4use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use std::collections::BTreeMap;
8
9use crate::{NativeId, SourceName};
10
11/// One unit of work as a source reports it.
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
13pub struct Task {
14    /// The source's own opaque identifier.
15    pub id: NativeId,
16    /// The short handle the backend shows people, beside [`id`](Self::id) and never
17    /// instead of it — a Linear issue's `ENG-123`, a GitHub issue's `1043`.
18    ///
19    /// **It is human-facing and it may change.** A Linear issue moved between teams gets a
20    /// new identifier and a GitHub issue transferred between repositories gets a new
21    /// number, so nothing stores this in place of [`id`](Self::id) and nothing matches on
22    /// it: `id` is what everything stores and matches on, and this is what a person says
23    /// out loud.
24    ///
25    /// Absent by default, so a source that predates this field — and every source with no
26    /// separate handle of its own — reads as `None`, which means *this backend has no
27    /// short handle for this task* rather than *the handle is the id*. A source never
28    /// copies [`id`](Self::id) here.
29    ///
30    /// **Read-only.** A source derives it on a read and never stores one it is handed: a
31    /// task arriving on an [`ItemWrite`](crate::ItemWrite) may still hold its source's key,
32    /// and a destination ignores it.
33    // llmlint: ignore[invalid_states_unrepresentable] The answer `Task::url` and `Project::url` below already record: this crate's field types are the contract itself, and the contract approving this field states its shape as `Option<String>`. A backend's handle is also the one value this product never parses, matches on or resolves by — `id` does all three — so the confusion a newtype prevents is confusion no code here can act on.
34    #[serde(default)]
35    pub key: Option<String>,
36    /// The one-line summary a user recognises the task by.
37    pub title: String,
38    /// The long-form body, when the source has one.
39    pub content: Option<String>,
40    /// The source's status, normalised and preserved.
41    pub status: Status,
42    /// The task's priority; `none` means none is set, and a source that cannot hold one
43    /// reports `none`.
44    ///
45    /// Defaulted when a document omits it, so a task written before this field existed —
46    /// and every task of a plugin that predates it — reads as [`Priority::None`]. Always
47    /// written, so a reader never has to tell an absent member from a `none` one. Whether a
48    /// source can hold one at all is [`Capabilities::priority`](crate::Capabilities::priority),
49    /// and the engine never hands a source declaring it cannot a priority other than `none`.
50    #[serde(default)]
51    pub priority: Priority,
52    /// Inline rather than by id: a source returning a task already knows them.
53    pub labels: Vec<Label>,
54    /// `None` is a first-class case — an orphan task — not an edge case.
55    pub project: Option<NativeId>,
56    /// Where a human can open this task.
57    // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this restates at a new site the justification already recorded at `Capabilities.max_page_size` (capability.rs) and `PageRequest.limit` (query.rs), and in AGENTS.md's "The plugin contract": this crate's field types ARE the approved contract, six undispatched nodes compile against `Option<String>` here, and only the contract's owner may narrow one. No code change is available that clears this without editing that frozen surface.
58    // llmlint: ignore[boundary_inputs_validated] parsing this into a URL type would narrow the same frozen surface, and would add a URL dependency to the crate AGENTS.md says to keep still ("Keep the api crate still" — every change here re-tests every plugin). A plugin that returns a string this interface cannot represent is what `SourceError::Malformed` is for. Contract owner's call; recorded in AGENTS.md, "The plugin contract".
59    pub url: Option<String>,
60    /// Where this task is, when the source says (see [`Location`]).
61    ///
62    /// Absent by default, so a source that predates this field — and every source that
63    /// simply does not say — reads as `None`, which means *the source did not say where
64    /// this is* rather than *this is nowhere*. It neither replaces nor derives from
65    /// [`url`](Self::url), which goes on meaning exactly what it always did.
66    #[serde(default)]
67    pub location: Option<Location>,
68    /// When the source says the task was created.
69    pub created_at: Option<DateTime<Utc>>,
70    /// When the source says the task last changed.
71    pub updated_at: Option<DateTime<Utc>>,
72    /// Caller-defined attributes, preserving their JSON types.
73    ///
74    /// Keys are free-form, with two reserved prefixes: `onetaskgraph.` belongs to this
75    /// product — [`Repository::METADATA_KEY`] and [`DependencyEdge::RECORDED_KEY`] are
76    /// the two every source honours, and [`ItemKind::METADATA_KEY`] is one plugin's —
77    /// and `onepipeline.` belongs to that consumer. Every other key is the caller's, and
78    /// a source returns it exactly as it holds it.
79    #[serde(default)]
80    pub metadata: BTreeMap<String, Value>,
81    /// Normalized repository origins this task concerns, in source order and without
82    /// repeats.
83    #[serde(default, deserialize_with = "unique_repositories")]
84    pub repositories: Vec<Repository>,
85    /// The tasks this one delivers: finishing this task finishes them.
86    ///
87    /// Each entry is a [`TaskRef`] — `<source>:<native>` names a task of any source, and a
88    /// bare native id names a task of the source holding this one — with no repeats and
89    /// never this task itself. Empty by default, and left out of the wire when empty, so a
90    /// reader written before the field existed reads exactly what it read before.
91    #[serde(default, skip_serializing_if = "Vec::is_empty")]
92    #[schemars(!skip_serializing_if)]
93    pub delivers: Vec<TaskRef>,
94    /// Every task that delivers this one, by qualified id: the reverse of [`Self::delivers`].
95    ///
96    /// **Owned by the store, not by a source record and not by a copy.** The engine keeps it
97    /// in step whenever it writes a task's `delivers`, through
98    /// [`TaskSource::set_delivered_by`](crate::TaskSource::set_delivered_by); a source holds
99    /// and reports it, and a copy keeps the destination's own rather than taking the
100    /// source's. Empty by default and left out of the wire when empty, as `delivers` is.
101    #[serde(default, skip_serializing_if = "Vec::is_empty")]
102    #[schemars(!skip_serializing_if)]
103    pub delivered_by: Vec<TaskRef>,
104    /// The task's change token: an opaque value its source gives so a reader can tell whether
105    /// the task changed without reading it whole.
106    ///
107    /// **Two equal versions of one task from one source mean nothing in it has changed** — its
108    /// title, body, status, priority, labels, project fields, metadata, edges and comments,
109    /// comments added, edited and deleted included. A source that cannot promise all of that
110    /// for a task leaves this absent, which means *always read it*. What each plugin keys its
111    /// token on, and which change kinds it covers, is stated per plugin in
112    /// `docs/plugin-protocol.md` §4.13d.
113    ///
114    /// Opaque to every caller: nothing compares one but for equality, and the one reader that
115    /// looks inside is the source that gave it, through
116    /// [`TaskSource::order_versions`](crate::TaskSource::order_versions). Absent by default and left out of the wire when absent, so a source written
117    /// before it existed is read as giving none.
118    ///
119    /// **Read-only.** A source derives it on a read and never stores one it is handed: a task
120    /// arriving on an [`ItemWrite`](crate::ItemWrite) may still hold its source's token, and a
121    /// destination ignores it.
122    // llmlint: ignore[invalid_states_unrepresentable] The contract this lands states the token as an opaque string so the next node's cache and both SDKs carry it unread; a typed token would make every plugin's format part of this crate, which AGENTS.md asks to keep still. The one reader that parses it, its own source's `TaskSource::order_versions`, answers `None` for any value it cannot parse.
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub version: Option<String>,
125    /// Who may read this task, as it was declared (see [`Classification`]).
126    ///
127    /// Defaulted and left out of the wire while `public`, so a task written before this
128    /// field existed reads as public and a reader written before it reads what it always
129    /// read. It is the *declared* classification: the engine tightens it by the task's
130    /// repositories and its project before it decides where the task may be written, and
131    /// nothing written here can loosen either.
132    #[serde(default, skip_serializing_if = "Classification::is_public")]
133    #[schemars(!skip_serializing_if)]
134    pub classification: Classification,
135}
136
137/// A grouping of tasks, shaped like a [`Task`] without a parent of its own.
138#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
139pub struct Project {
140    /// The source's own opaque identifier.
141    pub id: NativeId,
142    /// The one-line summary a user recognises the project by.
143    pub title: String,
144    /// The long-form body, when the source has one.
145    pub content: Option<String>,
146    /// The source's status, normalised and preserved.
147    pub status: Status,
148    /// Inline rather than by id, for the same reason as on [`Task`].
149    pub labels: Vec<Label>,
150    /// Where a human can open this project.
151    // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this restates at a new site the justification already recorded at `Capabilities.max_page_size` (capability.rs) and `PageRequest.limit` (query.rs), and in AGENTS.md's "The plugin contract": this crate's field types ARE the approved contract, six undispatched nodes compile against `Option<String>` here, and only the contract's owner may narrow one. No code change is available that clears this without editing that frozen surface.
152    // llmlint: ignore[boundary_inputs_validated] parsing this into a URL type would narrow the same frozen surface, and would add a URL dependency to the crate AGENTS.md says to keep still ("Keep the api crate still" — every change here re-tests every plugin). A plugin that returns a string this interface cannot represent is what `SourceError::Malformed` is for. Contract owner's call; recorded in AGENTS.md, "The plugin contract".
153    pub url: Option<String>,
154    /// Where this project is, on exactly the terms of [`Task::location`].
155    #[serde(default)]
156    pub location: Option<Location>,
157    /// When the source says the project was created.
158    pub created_at: Option<DateTime<Utc>>,
159    /// When the source says the project last changed.
160    pub updated_at: Option<DateTime<Utc>>,
161    /// Caller-defined attributes, preserving their JSON types, on the same terms as
162    /// [`Task::metadata`].
163    #[serde(default)]
164    pub metadata: BTreeMap<String, Value>,
165    /// Normalized repository origins this project concerns, in source order and without
166    /// repeats.
167    #[serde(default, deserialize_with = "unique_repositories")]
168    pub repositories: Vec<Repository>,
169    /// The project's change token, on exactly the terms of [`Task::version`]: two equal
170    /// versions of one project from one source mean nothing its source's
171    /// [`ProjectVersionCoverage`](crate::ProjectVersionCoverage) covers has changed, and a
172    /// source that cannot promise that leaves it absent, which means *always read it*.
173    /// Absent by default and left out of the wire when absent.
174    // llmlint: ignore[invalid_states_unrepresentable] As `Task::version`: the token is opaque to every caller, so the cache and both SDKs carry it unread, and the one reader that parses it — its own source's `TaskSource::order_versions` — answers `None` for any value it cannot parse.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub version: Option<String>,
177    /// Who may read this project, as it was declared, on the terms of
178    /// [`Task::classification`]. A project holding a private task or document is private
179    /// however this reads, and the engine records it so when it writes the project.
180    #[serde(default, skip_serializing_if = "Classification::is_public")]
181    #[schemars(!skip_serializing_if)]
182    pub classification: Classification,
183}
184
185/// One piece of information that lives in a project and is not work.
186///
187/// A document carries **no status** and **no dependencies**, and both omissions are the
188/// contract rather than an oversight: a document is not work, so it has no place in a
189/// status filter and no place in a dependency graph. [`ItemKind`] therefore gains no
190/// document variant — that enum names what a dependency endpoint points at, and nothing
191/// may point at a document.
192///
193/// A source says whether it has documents at all through
194/// [`Capabilities::documents`](crate::Capabilities::documents), and one that says it has
195/// none is never asked for one.
196#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
197pub struct Document {
198    /// The source's own opaque identifier.
199    pub id: NativeId,
200    /// The one-line summary a person recognises it by.
201    pub title: String,
202    /// The long-form body, when the source has one.
203    pub content: Option<String>,
204    /// The project it lives in; `None` is an orphan document, exactly as it is on a
205    /// [`Task`].
206    pub project: Option<NativeId>,
207    /// Inline, on the same terms as a [`Task`]'s.
208    pub labels: Vec<Label>,
209    /// Where a person can open it, on the same terms as a [`Task`]'s.
210    // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this restates at a new site the justification already recorded at `Task::url` and `Project::url` in this module, at `Capabilities.max_page_size` (capability.rs) and `PageRequest.limit` (query.rs), and in AGENTS.md's "The plugin contract": this crate's field types ARE the approved contract, this field is `Option<String>` because a task's and a project's are, and only the contract's owner may narrow one. Narrowing it here alone would leave the three entities describing the same thing in two different types.
211    // llmlint: ignore[boundary_inputs_validated] parsing this into a URL type would narrow the same frozen surface, and would add a URL dependency to the crate AGENTS.md says to keep still ("Keep the api crate still" — every change here re-tests every plugin). A plugin that returns a string this interface cannot represent is what `SourceError::Malformed` is for. Contract owner's call; recorded in AGENTS.md, "The plugin contract".
212    pub url: Option<String>,
213    /// Where it is, when the source says (see [`Location`]).
214    #[serde(default)]
215    pub location: Option<Location>,
216    /// When the source says it was created.
217    pub created_at: Option<DateTime<Utc>>,
218    /// When the source says it last changed.
219    pub updated_at: Option<DateTime<Utc>>,
220    /// Caller-defined attributes, preserving their JSON types, with the same reserved
221    /// prefixes [`Task::metadata`] carries.
222    #[serde(default)]
223    pub metadata: BTreeMap<String, Value>,
224    /// Normalized repository origins this document concerns, in source order and without
225    /// repeats, as a [`Task`]'s.
226    #[serde(default, deserialize_with = "unique_repositories")]
227    pub repositories: Vec<Repository>,
228    /// The document's change token, on exactly the terms of [`Task::version`] and of what its
229    /// source's [`DocumentVersionCoverage`](crate::DocumentVersionCoverage) covers. Absent by
230    /// default and left out of the wire when absent.
231    // llmlint: ignore[invalid_states_unrepresentable] As `Task::version`: the token is opaque to every caller, so the cache and both SDKs carry it unread, and the one reader that parses it — its own source's `TaskSource::order_versions` — answers `None` for any value it cannot parse.
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub version: Option<String>,
234    /// Who may read this document, as it was declared, on the terms of
235    /// [`Task::classification`].
236    #[serde(default, skip_serializing_if = "Classification::is_public")]
237    #[schemars(!skip_serializing_if)]
238    pub classification: Classification,
239}
240
241/// Who may read an item: anybody, or only those who may read where it is kept.
242///
243/// Two values, ordered so the stricter is the greater: [`strictest`](Self::strictest) of
244/// any two is the one an item they both describe carries. Nothing combines them any other
245/// way, which is what makes an explicit `public` unable to loosen a private repository or a
246/// private project — a classification only ever tightens.
247///
248/// It is recorded on the item and travels with it. A source whose backend has no notion of
249/// its own records it under [`Self::METADATA_KEY`], exactly as it records
250/// [`Repository::METADATA_KEY`], and only while it is `private`: an item without it is
251/// public, so every item written before this existed reads as it did.
252#[derive(
253    Debug,
254    Clone,
255    Copy,
256    Default,
257    PartialEq,
258    Eq,
259    PartialOrd,
260    Ord,
261    Hash,
262    Serialize,
263    Deserialize,
264    JsonSchema,
265)]
266#[serde(rename_all = "kebab-case")]
267pub enum Classification {
268    /// Anybody who may read the destination may read it.
269    #[default]
270    Public,
271    /// It may be written only to a destination verified private, and nothing of it may
272    /// reach a public one.
273    Private,
274}
275
276impl Classification {
277    /// The reserved metadata key a source records a private classification under when its
278    /// backend has no notion of its own.
279    ///
280    /// Spelled once, here, for the reason [`Repository::METADATA_KEY`] is.
281    pub const METADATA_KEY: &'static str = "onetaskgraph.classification";
282
283    /// Whether this is [`Public`](Self::Public) — the value left out of the wire.
284    #[must_use]
285    // serde's `skip_serializing_if` calls its predicate with a reference to the field, so this
286    // takes `&self` although the type is `Copy`.
287    #[allow(clippy::trivially_copy_pass_by_ref)]
288    pub fn is_public(&self) -> bool {
289        *self == Self::Public
290    }
291
292    /// The stricter of the two.
293    #[must_use]
294    pub fn strictest(self, other: Self) -> Self {
295        self.max(other)
296    }
297
298    /// The value as the wire spells it: `public` or `private`.
299    #[must_use]
300    pub const fn as_str(self) -> &'static str {
301        match self {
302            Self::Public => "public",
303            Self::Private => "private",
304        }
305    }
306
307    /// The classification a source records under [`Self::METADATA_KEY`], or `public` when
308    /// it records none.
309    ///
310    /// # Errors
311    ///
312    /// Returns a message when the key holds anything but one of the two spellings.
313    pub fn from_metadata(metadata: &BTreeMap<String, Value>) -> Result<Self, String> {
314        match metadata.get(Self::METADATA_KEY) {
315            None => Ok(Self::Public),
316            Some(value) => serde_json::from_value(value.clone()).map_err(|_| {
317                format!(
318                    "{} is {value}; it accepts only \"public\" or \"private\"",
319                    Self::METADATA_KEY
320                )
321            }),
322        }
323    }
324
325    /// Record this classification in `metadata` under [`Self::METADATA_KEY`]: present while
326    /// private, absent while public.
327    pub fn record(self, metadata: &mut BTreeMap<String, Value>) {
328        if self.is_public() {
329            metadata.remove(Self::METADATA_KEY);
330        } else {
331            metadata.insert(Self::METADATA_KEY.to_owned(), Value::from(self.as_str()));
332        }
333    }
334}
335
336impl std::fmt::Display for Classification {
337    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
338        formatter.write_str(self.as_str())
339    }
340}
341
342impl std::str::FromStr for Classification {
343    type Err = String;
344
345    fn from_str(value: &str) -> Result<Self, Self::Err> {
346        match value {
347            "public" => Ok(Self::Public),
348            "private" => Ok(Self::Private),
349            _ => Err(format!(
350                "{value:?} is not a classification; a classification is public or private"
351            )),
352        }
353    }
354}
355
356/// Where an entity is, in the one form a consumer can act on without knowing the backend.
357///
358/// Externally tagged with exactly two variants, so the JSON is `{"url": "https://…"}` or
359/// `{"path": "/home/…"}` and a consumer tells them apart by which key is present. A reader
360/// handed one of these knows what to *do* with it — open a link, or print a path and read
361/// the file out — which is what a bare string could not have said.
362///
363/// It carries no third case on purpose. `None` on the field is the third case, and it
364/// means the source did not say where the entity is, which is not the same as saying it is
365/// nowhere.
366///
367/// This does **not** redefine, replace or derive from the `url` field of [`Task`],
368/// [`Project`] or [`Document`]: a source that reports a web URL there goes on reporting
369/// it, and every existing consumer sees exactly what it saw.
370#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
371#[serde(rename_all = "kebab-case")]
372pub enum Location {
373    /// The entity lives at an external website, and this is a link a reader can open.
374    // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this restates at a new site the justification already recorded at `Task::url` and `Project::url` in this module, at `Capabilities.max_page_size` (capability.rs) and `PageRequest.limit` (query.rs): this crate's field types ARE the approved contract, and this variant is a `String` because the `url` field it sits beside is one. Narrowing it here alone would leave two members describing a web address in two different types, which is worse than the state it would remove.
375    // llmlint: ignore[boundary_inputs_validated] parsing this into a URL type would add a URL dependency to the crate AGENTS.md says to keep still ("Keep the api crate still" — every change here rebuilds and re-tests every plugin), and would narrow a frozen surface only the contract's owner may narrow. A plugin returning a string this interface cannot represent is what `SourceError::Malformed` is for, exactly as it is for `Task::url`.
376    Url(String),
377    /// The entity is a file on the machine the source runs on, and this is that file's
378    /// absolute path, so a reader can print the path or read the contents out.
379    // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — the reason the variant above carries, plus one of this variant's own: a typed path here would be `std::path::PathBuf`, whose parsing is the *reading* platform's while this string is the *source's*. A plugin on Linux reporting an absolute path to an engine on Windows must have that path survive byte for byte, so the type that would make a relative path unrepresentable is the type that would corrupt a correct one.
380    // llmlint: ignore[boundary_inputs_validated] validating absoluteness here would answer the question with the wrong machine's rules, for the reason above — this side cannot know what "absolute" means on the host the plugin runs on. The absoluteness this documents is an obligation on the source, and a source that breaks it is `SourceError::Malformed` to the reader that acts on the path.
381    Path(String),
382}
383
384/// A repository identified by its normalized origin, without a URL scheme or `.git` suffix.
385#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
386#[serde(try_from = "String", into = "String")]
387pub struct Repository(String);
388
389impl Repository {
390    /// The reserved metadata key a source reads these origins from when its backend has
391    /// no notion of its own.
392    ///
393    /// The key is spelled once, here, because every plugin has to agree on it: a source
394    /// that invented its own spelling would hold work nothing else could read.
395    pub const METADATA_KEY: &'static str = "onetaskgraph.repositories";
396
397    /// The normalized `host/owner/name` origin.
398    #[must_use]
399    pub fn as_str(&self) -> &str {
400        &self.0
401    }
402
403    /// The origins a source records under [`Self::METADATA_KEY`], or none.
404    ///
405    /// # Errors
406    ///
407    /// Returns a message when the key holds something other than a duplicate-free list
408    /// of normalized origins.
409    pub fn from_metadata(metadata: &BTreeMap<String, Value>) -> Result<Vec<Self>, String> {
410        let Some(value) = metadata.get(Self::METADATA_KEY) else {
411            return Ok(Vec::new());
412        };
413        let origins: Vec<Self> = serde_json::from_value(value.clone()).map_err(|error| {
414            format!(
415                "{} is not a list of repository origins: {error}",
416                Self::METADATA_KEY
417            )
418        })?;
419        Self::unique(origins)
420    }
421
422    /// The same origins, in the order given, once it is established none repeats.
423    ///
424    /// # Errors
425    ///
426    /// Returns a message naming the first origin that appears twice.
427    pub fn unique(origins: Vec<Self>) -> Result<Vec<Self>, String> {
428        let mut seen = std::collections::BTreeSet::new();
429        for origin in &origins {
430            if !seen.insert(origin.as_str()) {
431                return Err(format!(
432                    "{:?} is listed twice; a repository list names each origin once",
433                    origin.as_str()
434                ));
435            }
436        }
437        Ok(origins)
438    }
439}
440
441fn unique_repositories<'de, D>(deserializer: D) -> Result<Vec<Repository>, D::Error>
442where
443    D: serde::Deserializer<'de>,
444{
445    Repository::unique(Vec::<Repository>::deserialize(deserializer)?)
446        .map_err(serde::de::Error::custom)
447}
448
449impl TryFrom<String> for Repository {
450    type Error = String;
451
452    fn try_from(origin: String) -> Result<Self, Self::Error> {
453        let valid = !origin.is_empty()
454            && !origin.contains("://")
455            && !origin.ends_with(".git")
456            && !origin.chars().any(char::is_whitespace)
457            && origin.split('/').count() >= 3
458            && origin
459                .split('/')
460                .all(|part| !part.is_empty() && part != "." && part != "..");
461        valid.then_some(Self(origin.clone())).ok_or_else(|| format!(
462            "{origin:?} is not a normalized repository origin; use host/owner/name without a scheme or .git suffix"
463        ))
464    }
465}
466
467impl From<Repository> for String {
468    fn from(repository: Repository) -> Self {
469        repository.0
470    }
471}
472
473/// One task named by another task's [`Task::delivers`] or [`Task::delivered_by`].
474///
475/// A string with one of two spellings, decided the way a [`DependencyEndpoint`] decides it:
476/// one holding a colon is `<source>:<native>` and names a task of any source, and one
477/// without is a bare native id naming a task of the source that holds the list. So a
478/// native id holding a colon cannot be named bare, exactly as it cannot in
479/// `onetaskgraph.depends_on`.
480#[derive(
481    Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
482)]
483#[serde(try_from = "String", into = "String")]
484pub struct TaskRef(String);
485
486impl TaskRef {
487    /// The reserved metadata key a source records [`Task::delivers`] under when its backend
488    /// has no notion of its own.
489    ///
490    /// Spelled once, here, for the reason [`Repository::METADATA_KEY`] is.
491    pub const DELIVERS_KEY: &'static str = "onetaskgraph.delivers";
492
493    /// The reserved metadata key a source records [`Task::delivered_by`] under when its
494    /// backend has no notion of its own.
495    pub const DELIVERED_BY_KEY: &'static str = "onetaskgraph.delivered_by";
496
497    /// One entry, once it is established it is a task id.
498    ///
499    /// # Errors
500    ///
501    /// Returns a message saying why when the id is empty, or when it is qualified with a
502    /// source name that breaks the pattern or with no native id after the colon.
503    pub fn new(id: impl Into<String>) -> Result<Self, String> {
504        let id = id.into();
505        if id.is_empty() {
506            return Err("an empty string names no task".to_owned());
507        }
508        if let Some((source, native)) = id.split_once(':') {
509            SourceName::new(source).map_err(|error| error.to_string())?;
510            if native.is_empty() {
511                return Err(format!("{id:?} names a source and no task in it"));
512            }
513        }
514        Ok(Self(id))
515    }
516
517    /// The qualified entry naming `native` in `source`.
518    #[must_use]
519    pub fn qualified(source: &SourceName, native: &NativeId) -> Self {
520        Self(format!("{source}:{native}"))
521    }
522
523    /// The entry as it is spelled.
524    #[must_use]
525    pub fn as_str(&self) -> &str {
526        &self.0
527    }
528
529    /// Whether the entry names its source in writing.
530    #[must_use]
531    pub fn is_qualified(&self) -> bool {
532        self.0.contains(':')
533    }
534
535    /// The source and the native id this entry names, reading a bare entry as naming a task
536    /// of `near_source`.
537    #[must_use]
538    pub fn parts<'a>(&'a self, near_source: &'a str) -> (&'a str, &'a str) {
539        self.0
540            .split_once(':')
541            .unwrap_or((near_source, self.0.as_str()))
542    }
543
544    /// This entry qualified, reading a bare one as naming a task of `near_source`.
545    #[must_use]
546    pub fn in_source(&self, near_source: &SourceName) -> Self {
547        if self.is_qualified() {
548            return self.clone();
549        }
550        Self(format!("{near_source}:{}", self.0))
551    }
552
553    /// The entries of one task's list, once it is established that none names the task
554    /// itself and none repeats.
555    ///
556    /// `field` is what the list is called where it is stored, for the message. `near` is the
557    /// task holding the list and `near_source` the configured name of the source holding it,
558    /// which is what tells `T-1` and `work:T-1` apart as the same task. A source that does
559    /// not know its own name passes `None`, and then only a bare entry can be recognised as
560    /// naming this task or one of the other entries.
561    ///
562    /// # Errors
563    ///
564    /// Returns a message naming the task and the entry.
565    pub fn listed(
566        field: &str,
567        near: &NativeId,
568        near_source: Option<&SourceName>,
569        entries: Vec<Self>,
570    ) -> Result<Vec<Self>, String> {
571        let normal = |entry: &Self| match near_source {
572            Some(source) => entry.in_source(source).0,
573            None => entry.0.clone(),
574        };
575        let this = match near_source {
576            Some(source) => Self::qualified(source, near).0,
577            None => near.0.clone(),
578        };
579        let mut seen: Vec<(String, &Self)> = Vec::with_capacity(entries.len());
580        for entry in &entries {
581            let named = normal(entry);
582            if named == this {
583                return Err(format!(
584                    "{field} on task {near} names {entry}, which is that task itself; a task \
585                     cannot be listed in its own {field}"
586                ));
587            }
588            if let Some((_, first)) = seen.iter().find(|(held, _)| *held == named) {
589                return Err(format!(
590                    "{field} on task {near} names {entry} more than once (as {first} and \
591                     {entry}); name each task once"
592                ));
593            }
594            seen.push((named, entry));
595        }
596        Ok(entries)
597    }
598
599    /// The entries one task's list holds, read out of the JSON a source stores it as.
600    ///
601    /// `value` is `None` when the source holds no list at all, which is the empty one.
602    ///
603    /// # Errors
604    ///
605    /// Returns a message naming the task and the entry when the value is not a list, when an
606    /// entry is not a task id, or when [`Self::listed`] refuses the list.
607    pub fn from_value(
608        field: &str,
609        near: &NativeId,
610        near_source: Option<&SourceName>,
611        value: Option<&Value>,
612    ) -> Result<Vec<Self>, String> {
613        let Some(value) = value else {
614            return Ok(Vec::new());
615        };
616        let Some(held) = value.as_array() else {
617            return Err(format!(
618                "{field} on task {near} is {value}, which is not a list of task ids"
619            ));
620        };
621        let entries = held
622            .iter()
623            .map(|entry| {
624                entry
625                    .as_str()
626                    .ok_or_else(|| "it is not a string".to_owned())
627                    .and_then(Self::new)
628                    .map_err(|why| {
629                        format!(
630                            "{field} on task {near} holds {entry}, which is not a task id: {why}"
631                        )
632                    })
633            })
634            .collect::<Result<Vec<_>, _>>()?;
635        Self::listed(field, near, near_source, entries)
636    }
637}
638
639impl TryFrom<String> for TaskRef {
640    type Error = String;
641
642    fn try_from(id: String) -> Result<Self, Self::Error> {
643        Self::new(id)
644    }
645}
646
647impl From<TaskRef> for String {
648    fn from(entry: TaskRef) -> Self {
649        entry.0
650    }
651}
652
653impl std::fmt::Display for TaskRef {
654    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
655        self.0.fmt(formatter)
656    }
657}
658
659/// A tag a source attaches to work.
660#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
661pub struct Label {
662    /// The source's own opaque identifier.
663    pub id: NativeId,
664    /// What a user filtering across sources actually types.
665    pub name: String,
666    /// The source's own colour for the label, when it has one.
667    pub color: Option<String>,
668}
669
670/// A source's status, kept in both normalised and original form.
671///
672/// `category` is what every filter compares against; `name` is the source's own
673/// wording, preserved so display never flattens "In Review" into "In Progress".
674#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
675pub struct Status {
676    /// The normalised value filters compare against.
677    pub category: StatusCategory,
678    /// The source's own label for this status.
679    pub name: String,
680}
681
682/// The normalised status vocabulary shared across every source.
683#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
684#[serde(rename_all = "kebab-case")]
685pub enum StatusCategory {
686    /// Written down but not yet committed to as work.
687    Draft,
688    /// Known about, not yet accepted as ready to work.
689    Backlog,
690    /// Accepted and ready to be picked up, and nothing has claimed it.
691    Todo,
692    /// Claimed by work that will do it, and not yet started.
693    Queued,
694    /// Being worked on.
695    InProgress,
696    /// Finished.
697    Done,
698    /// Abandoned.
699    Cancelled,
700    /// The source reported a status this vocabulary cannot place.
701    Unknown,
702}
703
704/// How much a task matters, in the one vocabulary every source is normalised into.
705///
706/// Five values, most pressing first after [`None`](Self::None): Linear's own priority has
707/// exactly these, and a source whose backend has none of its own maps its representation
708/// onto them. `none` is a value rather than an absent field, because "no priority is set" is
709/// something a person sets — writing `none` clears a priority — and a reader tells it apart
710/// from nothing by the value alone.
711#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize, JsonSchema)]
712#[serde(rename_all = "kebab-case")]
713pub enum Priority {
714    /// No priority is set.
715    #[default]
716    None,
717    /// Drop everything for it.
718    Urgent,
719    /// Next, before the rest.
720    High,
721    /// In its turn.
722    Medium,
723    /// When there is nothing more pressing.
724    Low,
725}
726
727impl Priority {
728    /// Every value, in the order the vocabulary lists them.
729    pub const ALL: [Self; 5] = [
730        Self::None,
731        Self::Urgent,
732        Self::High,
733        Self::Medium,
734        Self::Low,
735    ];
736
737    /// The value as the wire spells it: `none`, `urgent`, `high`, `medium` or `low`.
738    #[must_use]
739    pub const fn as_str(self) -> &'static str {
740        match self {
741            Self::None => "none",
742            Self::Urgent => "urgent",
743            Self::High => "high",
744            Self::Medium => "medium",
745            Self::Low => "low",
746        }
747    }
748}
749
750impl std::fmt::Display for Priority {
751    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
752        formatter.write_str(self.as_str())
753    }
754}
755
756impl std::str::FromStr for Priority {
757    type Err = String;
758
759    fn from_str(value: &str) -> Result<Self, Self::Err> {
760        Self::ALL
761            .into_iter()
762            .find(|priority| priority.as_str() == value)
763            .ok_or_else(|| {
764                format!(
765                    "{value:?} is not a priority; a priority is one of none, urgent, high, \
766                     medium or low"
767                )
768            })
769    }
770}
771
772/// A dependency between two work items.
773///
774/// An endpoint may name another source. Keeping that far id on the near item is work data
775/// owned by its plugin, not an engine-side index or mirror; the engine reports it without
776/// resolving or fetching the far item.
777///
778/// A source uses its backend's own relationship wherever that relationship can name the
779/// far end, so the backend knows the graph and its own interface draws it. Where it
780/// cannot — a far end in another source, which no backend relates — the source reads
781/// [`Self::recorded`] from the near item instead. Only the forward direction is ever
782/// recorded; the reverse of a recorded edge is derived, exactly as a
783/// [`ForwardOnly`](crate::DependencySupport::ForwardOnly) source's reverse is.
784#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
785pub struct DependencyEdge {
786    /// The item the edge starts at, and the one that **depends on** the other.
787    ///
788    /// This is the orientation every source reports in, whichever way its own backend
789    /// spells the relationship: a GitHub `blockedBy` connection read for `ENG-1` yields
790    /// `from: ENG-1`, because `ENG-1` is what depends.
791    pub from: DependencyEndpoint,
792    /// The item the edge points at, and the one that must finish first.
793    pub to: DependencyEndpoint,
794    /// What the edge means.
795    pub kind: DependencyKind,
796}
797
798impl DependencyEdge {
799    /// The reserved metadata key a near item records a far end under.
800    ///
801    /// Spelled once, here, for the reason [`Repository::METADATA_KEY`] is: a plugin that
802    /// invented its own spelling would record a plan nothing else could read.
803    pub const RECORDED_KEY: &'static str = "onetaskgraph.depends_on";
804
805    /// The forward edges `near` records under [`Self::RECORDED_KEY`], or none.
806    ///
807    /// The key holds a list of endpoints — a bare string is a native id naming a task,
808    /// and `{"id": "<source>:<native>", "kind": "project"}` names any item of any source.
809    /// Each becomes one `blocks` edge from `near` to that endpoint.
810    ///
811    /// `natively_names` is the kind of item the near item's **own backend** can relate it
812    /// to — `Some(ItemKind::Task)` for a GitHub issue, whose `blockedBy` connection holds
813    /// issues; `None` for a GitHub draft, which has no such connection at all. An endpoint
814    /// of that kind naming an item of `near_source` is refused, because it names an item
815    /// the backend itself could hold, and the rule this key exists to serve is the
816    /// backend's own relationship first. Naming one's own source is what an unqualified id
817    /// does implicitly and what `<near_source>:<native>` does in writing, so both are
818    /// refused: which of the two spellings a plan happened to use says nothing about where
819    /// the edge belongs.
820    ///
821    /// An endpoint qualified to a *different* source is never refused. That is the whole
822    /// case this key is for: no backend relates an id in a system it knows nothing about.
823    ///
824    /// # Errors
825    ///
826    /// Returns a message when the key holds anything other than a list of endpoints, or
827    /// holds one the near item's own backend was supposed to name.
828    pub fn recorded(
829        metadata: &BTreeMap<String, Value>,
830        near: &NativeId,
831        near_kind: ItemKind,
832        near_source: &SourceName,
833        natively_names: Option<ItemKind>,
834    ) -> Result<Vec<Self>, String> {
835        let Some(value) = metadata.get(Self::RECORDED_KEY) else {
836            return Ok(Vec::new());
837        };
838        let far: Vec<DependencyEndpoint> =
839            serde_json::from_value(value.clone()).map_err(|error| {
840                format!(
841                    "{} is not a list of dependency endpoints: {error}",
842                    Self::RECORDED_KEY
843                )
844            })?;
845        far.into_iter()
846            .map(|to| {
847                let names_this_source = to
848                    .source()
849                    .is_none_or(|source| source == near_source.as_str());
850                if names_this_source && natively_names == Some(to.kind) {
851                    return Err(format!(
852                        "{key} on {near} records {to}, which this source can relate \
853                         natively; record it as this backend's own dependency and keep \
854                         {key} for a far end no relationship here can name",
855                        key = Self::RECORDED_KEY
856                    ));
857                }
858                Ok(Self {
859                    from: DependencyEndpoint::from_native(near.clone(), near_kind),
860                    to,
861                    kind: DependencyKind::Blocks,
862                })
863            })
864            .collect()
865    }
866}
867
868/// One endpoint of a dependency edge.
869#[derive(Debug, Clone, PartialEq, Eq, Hash)]
870pub struct DependencyEndpoint {
871    /// A qualified `<source>:<native>` id, or a legacy native id which the engine
872    /// qualifies to the source reporting the edge.
873    id: EndpointIdentity,
874    /// Whether the endpoint names a task or a project.
875    pub kind: ItemKind,
876}
877
878#[derive(Debug, Clone, PartialEq, Eq, Hash)]
879enum EndpointIdentity {
880    Native(String),
881    Qualified(String),
882}
883
884impl EndpointIdentity {
885    fn as_str(&self) -> &str {
886        match self {
887            Self::Native(id) | Self::Qualified(id) => id,
888        }
889    }
890
891    fn into_string(self) -> String {
892        match self {
893            Self::Native(id) | Self::Qualified(id) => id,
894        }
895    }
896}
897
898impl Serialize for DependencyEndpoint {
899    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
900    where
901        S: serde::Serializer,
902    {
903        #[derive(Serialize)]
904        struct Wire<'a> {
905            id: &'a str,
906            kind: ItemKind,
907        }
908        Wire {
909            id: self.id(),
910            kind: self.kind,
911        }
912        .serialize(serializer)
913    }
914}
915
916impl JsonSchema for DependencyEndpoint {
917    fn schema_name() -> std::borrow::Cow<'static, str> {
918        "DependencyEndpoint".into()
919    }
920
921    fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
922        json_schema!({
923            "description": "A dependency endpoint. A bare string is a native id of the source reporting it, and this decoding reads one as a task; a reader that knows the level it was written at — a source's own configuration, say — may read it at that level instead.",
924            "oneOf": [
925                {"type": "string", "minLength": 1},
926                {
927                    "type": "object",
928                    "additionalProperties": false,
929                    "required": ["id", "kind"],
930                    "properties": {
931                        "id": {"type": "string", "minLength": 1},
932                        "kind": {"type": "string", "enum": ["task", "project"]}
933                    }
934                }
935            ]
936        })
937    }
938}
939
940impl DependencyEndpoint {
941    /// Builds an endpoint from a serialized id, validating a qualified id when present.
942    ///
943    /// # Errors
944    ///
945    /// Returns an error for an empty id or a malformed `<source>:<native>` id.
946    pub fn new(id: String, kind: ItemKind) -> Result<Self, String> {
947        let is_qualified = id.contains(':');
948        let id = valid_endpoint_id(id)?;
949        Ok(Self {
950            id: if is_qualified {
951                EndpointIdentity::Qualified(id)
952            } else {
953                EndpointIdentity::Native(id)
954            },
955            kind,
956        })
957    }
958
959    /// Builds an endpoint from a source-native id, whose contents are deliberately opaque.
960    #[must_use]
961    pub fn from_native(id: NativeId, kind: ItemKind) -> Self {
962        Self {
963            id: EndpointIdentity::Native(id.0),
964            kind,
965        }
966    }
967
968    /// The serialized native or qualified id.
969    #[must_use]
970    pub fn id(&self) -> &str {
971        self.id.as_str()
972    }
973
974    /// Consumes the endpoint and returns its serialized id.
975    #[must_use]
976    pub fn into_id(self) -> String {
977        self.id.into_string()
978    }
979
980    /// Whether the id was explicitly supplied as a qualified endpoint.
981    #[must_use]
982    pub fn is_qualified(&self) -> bool {
983        matches!(self.id, EndpointIdentity::Qualified(_))
984    }
985
986    /// The source segment of a qualified id, or `None` for a native one.
987    ///
988    /// A native id belongs to whichever source reports it, so `None` reads as "this
989    /// source" rather than "no source".
990    #[must_use]
991    pub fn source(&self) -> Option<&str> {
992        match &self.id {
993            EndpointIdentity::Qualified(id) => id.split_once(':').map(|(source, _)| source),
994            EndpointIdentity::Native(_) => None,
995        }
996    }
997}
998
999impl<'de> Deserialize<'de> for DependencyEndpoint {
1000    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1001    where
1002        D: serde::Deserializer<'de>,
1003    {
1004        #[derive(Deserialize)]
1005        #[serde(untagged)]
1006        enum Wire {
1007            Legacy(String),
1008            Endpoint { id: String, kind: ItemKind },
1009        }
1010        match Wire::deserialize(deserializer)? {
1011            Wire::Legacy(id) => {
1012                if id.is_empty() {
1013                    return Err(serde::de::Error::custom(
1014                        "a dependency endpoint id cannot be empty",
1015                    ));
1016                }
1017                Ok(Self::from_native(NativeId(id), ItemKind::Task))
1018            }
1019            Wire::Endpoint { id, kind } => Self::new(id, kind).map_err(serde::de::Error::custom),
1020        }
1021    }
1022}
1023
1024fn valid_endpoint_id(id: String) -> Result<String, String> {
1025    if id.is_empty() {
1026        return Err("a dependency endpoint id cannot be empty".into());
1027    }
1028    if let Some((source, native)) = id.split_once(':') {
1029        crate::SourceName::new(source).map_err(|error| error.to_string())?;
1030        if native.is_empty() {
1031            return Err("a qualified dependency endpoint must name a native id".into());
1032        }
1033    }
1034    Ok(id)
1035}
1036
1037impl std::fmt::Display for DependencyEndpoint {
1038    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1039        self.id().fmt(formatter)
1040    }
1041}
1042
1043impl PartialEq<NativeId> for DependencyEndpoint {
1044    fn eq(&self, other: &NativeId) -> bool {
1045        self.id() == other.0
1046    }
1047}
1048
1049/// The kind of work item named by a dependency endpoint.
1050#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1051#[serde(rename_all = "kebab-case")]
1052pub enum ItemKind {
1053    /// A task.
1054    Task,
1055    /// A project.
1056    Project,
1057}
1058
1059impl ItemKind {
1060    /// The reserved metadata key an item is marked with when its backend cannot say
1061    /// which kind it is.
1062    ///
1063    /// Spelled once, here, for the reason [`Repository::METADATA_KEY`] is: a key under
1064    /// this product's prefix belongs to the product, and a plugin inventing its own
1065    /// spelling would collide with the next one to want it.
1066    ///
1067    /// Unlike the other two reserved keys, this one obliges **no** source. A backend that
1068    /// knows its own kinds — folders, native projects — never reads or writes it, and
1069    /// passes it through as ordinary caller metadata with its JSON type intact, exactly
1070    /// as it passes through every other key it does not own. `github-projects` is the one
1071    /// source that needs it, because a GitHub Projects board holds only issues and an
1072    /// empty project is indistinguishable from a task without it.
1073    pub const METADATA_KEY: &'static str = "onetaskgraph.item_kind";
1074
1075    /// The value this kind is marked with under [`Self::METADATA_KEY`].
1076    #[must_use]
1077    pub const fn marker(self) -> &'static str {
1078        match self {
1079            Self::Task => "task",
1080            Self::Project => "project",
1081        }
1082    }
1083
1084    /// The kind `metadata` marks, or `None` when it carries no marker at all.
1085    ///
1086    /// # Errors
1087    ///
1088    /// Returns a message when [`Self::METADATA_KEY`] holds anything other than the two
1089    /// markers [`Self::marker`] spells.
1090    pub fn from_metadata(metadata: &BTreeMap<String, Value>) -> Result<Option<Self>, String> {
1091        let Some(value) = metadata.get(Self::METADATA_KEY) else {
1092            return Ok(None);
1093        };
1094        match value.as_str() {
1095            Some(marker) if marker == Self::Task.marker() => Ok(Some(Self::Task)),
1096            Some(marker) if marker == Self::Project.marker() => Ok(Some(Self::Project)),
1097            _ => Err(format!(
1098                "{} is {value}; it accepts only {:?} or {:?}",
1099                Self::METADATA_KEY,
1100                Self::Project.marker(),
1101                Self::Task.marker()
1102            )),
1103        }
1104    }
1105}
1106
1107/// What a [`DependencyEdge`] means.
1108///
1109/// Both variants are read in the one direction [`DependencyEdge::from`] fixes: `from`
1110/// depends on `to`. This enum said the opposite of that until the orientation was settled,
1111/// which is why it is spelled out twice rather than once.
1112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1113#[serde(rename_all = "kebab-case")]
1114pub enum DependencyKind {
1115    /// `from` depends on `to`, and `to` must finish before `from` can.
1116    // llmlint: ignore[names_match_behavior] `"blocks"` is the approved serialized value, spelled in docs/plugin-protocol.md §4.8 and both generated SDKs; the variant names the kind of dependency, and `from`/`to` carry the direction. Renaming it is a wire change and the contract owner's call.
1117    Blocks,
1118    /// `from` and `to` are linked without an ordering.
1119    Related,
1120}
1121
1122/// Which way a dependency query walks the graph.
1123#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1124#[serde(rename_all = "kebab-case")]
1125pub enum Direction {
1126    /// What this item depends on — the forward edges every source can report.
1127    DependsOn,
1128    /// What depends on this item — emulated by the engine for a
1129    /// [`ForwardOnly`](crate::DependencySupport::ForwardOnly) source.
1130    DependedOnBy,
1131}