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 /// `{"id": "<source>:<native>", "kind": "project"}` names any item of any source, and
809 /// `{"designator": "<plugin>/<hex>", "id": "<native>", "kind": "task"}` names an item of
810 /// whichever tracker that designator is, conveying nothing about it.
811 /// Each becomes one `blocks` edge from `near` to that endpoint.
812 ///
813 /// `natively_names` is the kind of item the near item's **own backend** can relate it
814 /// to — `Some(ItemKind::Task)` for a GitHub issue, whose `blockedBy` connection holds
815 /// issues; `None` for a GitHub draft, which has no such connection at all. An endpoint
816 /// of that kind naming an item of `near_source` is refused, because it names an item
817 /// the backend itself could hold, and the rule this key exists to serve is the
818 /// backend's own relationship first. Naming one's own source is what an unqualified id
819 /// does implicitly and what `<near_source>:<native>` does in writing, so both are
820 /// refused: which of the two spellings a plan happened to use says nothing about where
821 /// the edge belongs.
822 ///
823 /// An endpoint qualified to a *different* source is never refused. That is the whole
824 /// case this key is for: no backend relates an id in a system it knows nothing about.
825 ///
826 /// # Errors
827 ///
828 /// Returns a message when the key holds anything other than a list of endpoints, or
829 /// holds one the near item's own backend was supposed to name.
830 pub fn recorded(
831 metadata: &BTreeMap<String, Value>,
832 near: &NativeId,
833 near_kind: ItemKind,
834 near_source: &SourceName,
835 natively_names: Option<ItemKind>,
836 ) -> Result<Vec<Self>, String> {
837 let Some(value) = metadata.get(Self::RECORDED_KEY) else {
838 return Ok(Vec::new());
839 };
840 let far: Vec<DependencyEndpoint> =
841 serde_json::from_value(value.clone()).map_err(|error| {
842 format!(
843 "{} is not a list of dependency endpoints: {error}",
844 Self::RECORDED_KEY
845 )
846 })?;
847 far.into_iter()
848 .map(|to| {
849 // An opaque far end names a tracker rather than a source, which is never one
850 // this backend relates.
851 let names_this_source = to.designator().is_none()
852 && to
853 .source()
854 .is_none_or(|source| source == near_source.as_str());
855 if names_this_source && natively_names == Some(to.kind) {
856 return Err(format!(
857 "{key} on {near} records {to}, which this source can relate \
858 natively; record it as this backend's own dependency and keep \
859 {key} for a far end no relationship here can name",
860 key = Self::RECORDED_KEY
861 ));
862 }
863 Ok(Self {
864 from: DependencyEndpoint::from_native(near.clone(), near_kind),
865 to,
866 kind: DependencyKind::Blocks,
867 })
868 })
869 .collect()
870 }
871}
872
873/// One endpoint of a dependency edge.
874///
875/// Three forms: a native id of the source reporting it, a qualified `<source>:<native>` id,
876/// and the **opaque** form — a [`Designator`] naming the tracker that holds the item and the
877/// item's native id there, which names a private item from a public one while conveying
878/// nothing about it.
879#[derive(Debug, Clone, PartialEq, Eq, Hash)]
880pub struct DependencyEndpoint {
881 /// A qualified `<source>:<native>` id, a legacy native id which the engine qualifies to
882 /// the source reporting the edge, or a designator with a native id.
883 id: EndpointIdentity,
884 /// Whether the endpoint names a task or a project.
885 pub kind: ItemKind,
886}
887
888#[derive(Debug, Clone, PartialEq, Eq, Hash)]
889enum EndpointIdentity {
890 Native(String),
891 Qualified(String),
892 Opaque { designator: Designator, id: String },
893}
894
895impl EndpointIdentity {
896 fn as_str(&self) -> &str {
897 match self {
898 Self::Native(id) | Self::Qualified(id) | Self::Opaque { id, .. } => id,
899 }
900 }
901
902 fn into_string(self) -> String {
903 match self {
904 Self::Native(id) | Self::Qualified(id) | Self::Opaque { id, .. } => id,
905 }
906 }
907}
908
909/// The keys the opaque form of a [`DependencyEndpoint`] holds, and the only ones.
910pub(crate) const OPAQUE_ENDPOINT_KEYS: [&str; 3] = ["designator", "id", "kind"];
911
912/// Names a tracker without conveying anything about it: `<plugin>/<64 lowercase hex>`, the
913/// SHA-256 of `<plugin>\n<identifier>` over the backend's own opaque identifier of itself —
914/// a Linear workspace's organization id, a GitHub Project's node id — or, for a plugin whose
915/// backend has none, `alias/<public_alias>`, the alias every host's configuration of that
916/// tracker declares identically.
917///
918/// The one spelling, validated wherever one is built or read, so a stored opaque edge cannot
919/// carry anything a designator does not.
920#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
921#[serde(transparent)]
922pub struct Designator(String);
923
924/// The pattern every [`Designator`] matches, as the schema publishes it. What
925/// [`Designator::try_from`] accepts is reconciled with it by `tests/designator_pattern.rs` in
926/// `onetaskgraph-core`, over the schema the bundle emits.
927pub(crate) const DESIGNATOR_PATTERN: &str =
928 "^(alias/[A-Za-z0-9_-]{16,64}|[a-z0-9][a-z0-9-]*/[0-9a-f]{64})$";
929
930impl JsonSchema for Designator {
931 fn schema_name() -> std::borrow::Cow<'static, str> {
932 "Designator".into()
933 }
934
935 fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
936 json_schema!({
937 "description": "A tracker, named without conveying anything about it: `<plugin>/` and the hex SHA-256 of `<plugin>\n<backend identifier>`, or `alias/<public_alias>`.",
938 "type": "string",
939 "pattern": DESIGNATOR_PATTERN
940 })
941 }
942}
943
944impl Designator {
945 /// The prefix of a designator built from a configured `public_alias`.
946 pub const ALIAS_PREFIX: &'static str = "alias";
947
948 /// The designator of a backend `plugin` identifies by `identifier`, its own opaque
949 /// identifier of itself.
950 ///
951 /// # Errors
952 ///
953 /// A message when `plugin` is not a plugin kind's spelling — the pattern a source name
954 /// matches — or is [`Self::ALIAS_PREFIX`], which an alias designator's prefix is.
955 pub fn of_backend(plugin: &str, identifier: &str) -> Result<Self, String> {
956 use sha2::{Digest, Sha256};
957 use std::fmt::Write as _;
958 if plugin == Self::ALIAS_PREFIX || SourceName::new(plugin).is_err() {
959 return Err(format!(
960 "{plugin:?} cannot prefix a designator: a plugin kind is lower-case letters, \
961 digits and dashes, and not {:?}",
962 Self::ALIAS_PREFIX
963 ));
964 }
965 let mut hex = String::with_capacity(64);
966 for byte in Sha256::digest(format!("{plugin}\n{identifier}").as_bytes()) {
967 write!(hex, "{byte:02x}").expect("writing to a String cannot fail");
968 }
969 Ok(Self(format!("{plugin}/{hex}")))
970 }
971
972 /// The designator of a tracker whose configuration declares `alias` as its
973 /// `public_alias`.
974 ///
975 /// # Errors
976 ///
977 /// A message naming the pattern when `alias` is not one.
978 pub fn of_alias(alias: &str) -> Result<Self, String> {
979 if Self::is_public_alias(alias) {
980 Ok(Self(format!("{}/{alias}", Self::ALIAS_PREFIX)))
981 } else {
982 Err(format!(
983 "a public_alias is 16 to 64 of A-Z, a-z, 0-9, `_` and `-` \
984 (^[A-Za-z0-9_-]{{16,64}}$), and this one is {} characters of something else",
985 alias.chars().count()
986 ))
987 }
988 }
989
990 /// Whether `alias` is a valid `public_alias`: `^[A-Za-z0-9_-]{16,64}$`.
991 #[must_use]
992 pub fn is_public_alias(alias: &str) -> bool {
993 (16..=64).contains(&alias.len())
994 && alias
995 .bytes()
996 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
997 }
998
999 /// The designator as it is spelled.
1000 #[must_use]
1001 pub fn as_str(&self) -> &str {
1002 &self.0
1003 }
1004
1005 /// What comes before the `/`: the plugin whose backend it digests, or
1006 /// [`Self::ALIAS_PREFIX`].
1007 #[must_use]
1008 pub fn prefix(&self) -> &str {
1009 self.0.split_once('/').map_or("", |(prefix, _)| prefix)
1010 }
1011
1012 /// Whether it was built from a configured `public_alias`.
1013 #[must_use]
1014 pub fn is_alias(&self) -> bool {
1015 self.prefix() == Self::ALIAS_PREFIX
1016 }
1017}
1018
1019impl TryFrom<String> for Designator {
1020 type Error = String;
1021
1022 fn try_from(value: String) -> Result<Self, Self::Error> {
1023 let refused =
1024 || "a designator is `<plugin>/<64 lowercase hex>` or `alias/<public_alias>`".to_owned();
1025 let (prefix, rest) = value.split_once('/').ok_or_else(refused)?;
1026 if prefix == Self::ALIAS_PREFIX {
1027 return Self::of_alias(rest);
1028 }
1029 let plugin = SourceName::new(prefix).is_ok();
1030 let digest = rest.len() == 64
1031 && rest
1032 .bytes()
1033 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
1034 if plugin && digest {
1035 Ok(Self(value))
1036 } else {
1037 Err(refused())
1038 }
1039 }
1040}
1041
1042impl<'de> Deserialize<'de> for Designator {
1043 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1044 where
1045 D: serde::Deserializer<'de>,
1046 {
1047 Self::try_from(String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
1048 }
1049}
1050
1051impl std::fmt::Display for Designator {
1052 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1053 formatter.write_str(&self.0)
1054 }
1055}
1056
1057impl Serialize for DependencyEndpoint {
1058 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1059 where
1060 S: serde::Serializer,
1061 {
1062 #[derive(Serialize)]
1063 struct Wire<'a> {
1064 #[serde(skip_serializing_if = "Option::is_none")]
1065 designator: Option<&'a Designator>,
1066 id: &'a str,
1067 kind: ItemKind,
1068 }
1069 Wire {
1070 designator: self.designator(),
1071 id: self.id(),
1072 kind: self.kind,
1073 }
1074 .serialize(serializer)
1075 }
1076}
1077
1078impl JsonSchema for DependencyEndpoint {
1079 fn schema_name() -> std::borrow::Cow<'static, str> {
1080 "DependencyEndpoint".into()
1081 }
1082
1083 fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
1084 json_schema!({
1085 "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. An object with a `designator` is the opaque form: the item's native id in the tracker the designator names, which a reader resolves to whichever configured source that tracker is.",
1086 "oneOf": [
1087 {"type": "string", "minLength": 1},
1088 {
1089 "type": "object",
1090 "additionalProperties": false,
1091 "required": ["id", "kind"],
1092 "properties": {
1093 "id": {"type": "string", "minLength": 1},
1094 "kind": {"type": "string", "enum": ["task", "project"]}
1095 }
1096 },
1097 {
1098 "type": "object",
1099 "additionalProperties": false,
1100 "required": ["designator", "id", "kind"],
1101 "properties": {
1102 "designator": {"type": "string", "pattern": DESIGNATOR_PATTERN},
1103 "id": {"type": "string", "minLength": 1},
1104 "kind": {"type": "string", "enum": ["task", "project"]}
1105 }
1106 }
1107 ]
1108 })
1109 }
1110}
1111
1112impl DependencyEndpoint {
1113 /// Builds an endpoint from a serialized id, validating a qualified id when present.
1114 ///
1115 /// # Errors
1116 ///
1117 /// Returns an error for an empty id or a malformed `<source>:<native>` id.
1118 pub fn new(id: String, kind: ItemKind) -> Result<Self, String> {
1119 let is_qualified = id.contains(':');
1120 let id = valid_endpoint_id(id)?;
1121 Ok(Self {
1122 id: if is_qualified {
1123 EndpointIdentity::Qualified(id)
1124 } else {
1125 EndpointIdentity::Native(id)
1126 },
1127 kind,
1128 })
1129 }
1130
1131 /// The opaque endpoint naming `id`, an item's native id in the tracker `designator` names.
1132 ///
1133 /// # Errors
1134 ///
1135 /// Returns an error for an empty id.
1136 pub fn opaque(designator: Designator, id: String, kind: ItemKind) -> Result<Self, String> {
1137 if id.is_empty() {
1138 return Err("a dependency endpoint id cannot be empty".into());
1139 }
1140 Ok(Self {
1141 id: EndpointIdentity::Opaque { designator, id },
1142 kind,
1143 })
1144 }
1145
1146 /// Reads an endpoint from any of its three JSON forms, naming what about an object
1147 /// makes it none of them.
1148 ///
1149 /// Unlike deserialization, which reads what a store already holds, this is for what a
1150 /// caller asks to be written: an object carrying a key beyond `designator`, `id` and `kind` —
1151 /// a title, a team, a URL — is refused with [`EndpointRefusal::Key`] naming that key, and
1152 /// never its value.
1153 ///
1154 /// # Errors
1155 ///
1156 /// [`EndpointRefusal`].
1157 pub fn from_value(value: &Value) -> Result<Self, EndpointRefusal> {
1158 if let Value::Object(entries) = value
1159 && let Some(key) = entries
1160 .keys()
1161 .find(|key| !OPAQUE_ENDPOINT_KEYS.contains(&key.as_str()))
1162 {
1163 return Err(EndpointRefusal::Key(key.clone()));
1164 }
1165 // Serde's diagnostic can repeat what it was given — an unknown `kind`, an id — so it is
1166 // not carried.
1167 serde_json::from_value(value.clone()).map_err(|_| EndpointRefusal::Malformed)
1168 }
1169
1170 /// Builds an endpoint from a source-native id, whose contents are deliberately opaque.
1171 #[must_use]
1172 pub fn from_native(id: NativeId, kind: ItemKind) -> Self {
1173 Self {
1174 id: EndpointIdentity::Native(id.0),
1175 kind,
1176 }
1177 }
1178
1179 /// The serialized native or qualified id — for the opaque form, the native id in the
1180 /// tracker [`Self::designator`] names.
1181 #[must_use]
1182 pub fn id(&self) -> &str {
1183 self.id.as_str()
1184 }
1185
1186 /// Consumes the endpoint and returns its serialized id.
1187 #[must_use]
1188 pub fn into_id(self) -> String {
1189 self.id.into_string()
1190 }
1191
1192 /// Whether the id was explicitly supplied as a qualified endpoint.
1193 #[must_use]
1194 pub fn is_qualified(&self) -> bool {
1195 matches!(self.id, EndpointIdentity::Qualified(_))
1196 }
1197
1198 /// The source segment of a qualified id, or `None` for a native or an opaque one.
1199 ///
1200 /// A native id belongs to whichever source reports it, so `None` reads as "this
1201 /// source" rather than "no source" — ask [`Self::is_native`] before reading it that way,
1202 /// because an opaque endpoint names no source of this configuration either.
1203 #[must_use]
1204 pub fn source(&self) -> Option<&str> {
1205 match &self.id {
1206 EndpointIdentity::Qualified(id) => id.split_once(':').map(|(source, _)| source),
1207 EndpointIdentity::Native(_) | EndpointIdentity::Opaque { .. } => None,
1208 }
1209 }
1210
1211 /// Whether the id is a native id of the source reporting it: neither qualified nor
1212 /// opaque.
1213 #[must_use]
1214 pub fn is_native(&self) -> bool {
1215 matches!(self.id, EndpointIdentity::Native(_))
1216 }
1217
1218 /// The tracker an opaque endpoint names, or `None` for the other two forms.
1219 #[must_use]
1220 pub fn designator(&self) -> Option<&Designator> {
1221 match &self.id {
1222 EndpointIdentity::Opaque { designator, .. } => Some(designator),
1223 EndpointIdentity::Native(_) | EndpointIdentity::Qualified(_) => None,
1224 }
1225 }
1226}
1227
1228impl<'de> Deserialize<'de> for DependencyEndpoint {
1229 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1230 where
1231 D: serde::Deserializer<'de>,
1232 {
1233 #[derive(Deserialize)]
1234 #[serde(deny_unknown_fields)]
1235 struct Opaque {
1236 designator: Designator,
1237 id: String,
1238 kind: ItemKind,
1239 }
1240 #[derive(Deserialize)]
1241 #[serde(untagged)]
1242 enum Wire {
1243 Legacy(String),
1244 Endpoint { id: String, kind: ItemKind },
1245 }
1246 let value = Value::deserialize(deserializer)?;
1247 // An object naming a designator is the opaque form and nothing else, so a malformed
1248 // one is refused rather than read as the qualified form with a key ignored.
1249 if value.get("designator").is_some() {
1250 let Opaque {
1251 designator,
1252 id,
1253 kind,
1254 } = serde_json::from_value(value).map_err(serde::de::Error::custom)?;
1255 return Self::opaque(designator, id, kind).map_err(serde::de::Error::custom);
1256 }
1257 match Wire::deserialize(value).map_err(serde::de::Error::custom)? {
1258 Wire::Legacy(id) => {
1259 if id.is_empty() {
1260 return Err(serde::de::Error::custom(
1261 "a dependency endpoint id cannot be empty",
1262 ));
1263 }
1264 Ok(Self::from_native(NativeId(id), ItemKind::Task))
1265 }
1266 Wire::Endpoint { id, kind } => Self::new(id, kind).map_err(serde::de::Error::custom),
1267 }
1268 }
1269}
1270
1271fn valid_endpoint_id(id: String) -> Result<String, String> {
1272 if id.is_empty() {
1273 return Err("a dependency endpoint id cannot be empty".into());
1274 }
1275 if let Some((source, native)) = id.split_once(':') {
1276 crate::SourceName::new(source).map_err(|error| error.to_string())?;
1277 if native.is_empty() {
1278 return Err("a qualified dependency endpoint must name a native id".into());
1279 }
1280 }
1281 Ok(id)
1282}
1283
1284/// Why [`DependencyEndpoint::from_value`] refused what a caller asked to be written. Neither
1285/// variant carries a value the caller gave, so a refusal can be printed anywhere.
1286#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1287pub enum EndpointRefusal {
1288 /// The object carries this key beyond `designator`, `id` and `kind`.
1289 #[error(
1290 "a dependency endpoint object carries `{0}`; it holds only `designator`, `id` and `kind`"
1291 )]
1292 Key(String),
1293 /// It is none of the three forms.
1294 #[error(
1295 "not a dependency endpoint: give a native id, a qualified `<source>:<native id>`, or an \
1296 object of `designator`, `id` and `kind`"
1297 )]
1298 Malformed,
1299}
1300
1301impl std::fmt::Display for DependencyEndpoint {
1302 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1303 match &self.id {
1304 EndpointIdentity::Opaque { designator, id } => write!(formatter, "{designator}:{id}"),
1305 EndpointIdentity::Native(id) | EndpointIdentity::Qualified(id) => id.fmt(formatter),
1306 }
1307 }
1308}
1309
1310/// An opaque endpoint names an item of another tracker, so it never equals a native id of the
1311/// source comparing it, whatever id it holds.
1312impl PartialEq<NativeId> for DependencyEndpoint {
1313 fn eq(&self, other: &NativeId) -> bool {
1314 self.designator().is_none() && self.id() == other.0
1315 }
1316}
1317
1318/// The kind of work item named by a dependency endpoint.
1319#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1320#[serde(rename_all = "kebab-case")]
1321pub enum ItemKind {
1322 /// A task.
1323 Task,
1324 /// A project.
1325 Project,
1326}
1327
1328impl ItemKind {
1329 /// The reserved metadata key an item is marked with when its backend cannot say
1330 /// which kind it is.
1331 ///
1332 /// Spelled once, here, for the reason [`Repository::METADATA_KEY`] is: a key under
1333 /// this product's prefix belongs to the product, and a plugin inventing its own
1334 /// spelling would collide with the next one to want it.
1335 ///
1336 /// Unlike the other two reserved keys, this one obliges **no** source. A backend that
1337 /// knows its own kinds — folders, native projects — never reads or writes it, and
1338 /// passes it through as ordinary caller metadata with its JSON type intact, exactly
1339 /// as it passes through every other key it does not own. `github-projects` is the one
1340 /// source that needs it, because a GitHub Projects board holds only issues and an
1341 /// empty project is indistinguishable from a task without it.
1342 pub const METADATA_KEY: &'static str = "onetaskgraph.item_kind";
1343
1344 /// The value this kind is marked with under [`Self::METADATA_KEY`].
1345 #[must_use]
1346 pub const fn marker(self) -> &'static str {
1347 match self {
1348 Self::Task => "task",
1349 Self::Project => "project",
1350 }
1351 }
1352
1353 /// The kind `metadata` marks, or `None` when it carries no marker at all.
1354 ///
1355 /// # Errors
1356 ///
1357 /// Returns a message when [`Self::METADATA_KEY`] holds anything other than the two
1358 /// markers [`Self::marker`] spells.
1359 pub fn from_metadata(metadata: &BTreeMap<String, Value>) -> Result<Option<Self>, String> {
1360 let Some(value) = metadata.get(Self::METADATA_KEY) else {
1361 return Ok(None);
1362 };
1363 match value.as_str() {
1364 Some(marker) if marker == Self::Task.marker() => Ok(Some(Self::Task)),
1365 Some(marker) if marker == Self::Project.marker() => Ok(Some(Self::Project)),
1366 _ => Err(format!(
1367 "{} is {value}; it accepts only {:?} or {:?}",
1368 Self::METADATA_KEY,
1369 Self::Project.marker(),
1370 Self::Task.marker()
1371 )),
1372 }
1373 }
1374}
1375
1376/// What a [`DependencyEdge`] means.
1377///
1378/// Both variants are read in the one direction [`DependencyEdge::from`] fixes: `from`
1379/// depends on `to`. This enum said the opposite of that until the orientation was settled,
1380/// which is why it is spelled out twice rather than once.
1381#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1382#[serde(rename_all = "kebab-case")]
1383pub enum DependencyKind {
1384 /// `from` depends on `to`, and `to` must finish before `from` can.
1385 // 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.
1386 Blocks,
1387 /// `from` and `to` are linked without an ordering.
1388 Related,
1389}
1390
1391/// Which way a dependency query walks the graph.
1392#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1393#[serde(rename_all = "kebab-case")]
1394pub enum Direction {
1395 /// What this item depends on — the forward edges every source can report.
1396 DependsOn,
1397 /// What depends on this item — emulated by the engine for a
1398 /// [`ForwardOnly`](crate::DependencySupport::ForwardOnly) source.
1399 DependedOnBy,
1400}