Skip to main content

onetaskgraph_plugin_api/
source.rs

1//! The two traits a plugin implements, and the secret lookup it is handed.
2
3use std::cmp::Ordering;
4use std::collections::BTreeMap;
5
6use schemars::{JsonSchema, Schema};
7use secrecy::SecretString;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11use crate::{
12    Asset, AssetName, AssetWrite, AssetsWritten, Capabilities, Comment, CommentBody, CommentCopy,
13    DependencyEdge, Direction, Document, DocumentQuery, DocumentVersionCoverage, IssueHolding,
14    IssueRef, ItemKind, ItemWrite, Label, MetadataKey, MetadataRecord, Metering, NativeId,
15    NewComment, Page, PageRequest, Priority, Project, ProjectQuery, ProjectVersionCoverage,
16    SharedClock, SourceError, SourceName, Status, StatusCategory, StatusContradiction, Task,
17    TaskDetailRead, TaskQuery, TaskRef, TaskUpdate, TaskUpdateOutcome, VersionCoverage, Visibility,
18    WriteJournal, WriteSupport, WriteTarget, assetless, commentless, documentless, unwritable,
19    unwritable_field, unwritable_metadata,
20};
21
22/// Whether a source is answering right now.
23///
24/// # Placement is an open contract question
25///
26/// This type lives here because [`TaskSource::health`] returns it and the trait
27/// lives here: placing it in `onetaskgraph-core` would make this crate depend on
28/// the engine and invert the one direction the crate split exists to establish.
29/// The approved contract enumerates this crate's contents exhaustively and does
30/// not name `Health`, so the enumeration and the trait as written cannot both
31/// stand. Compiling forces the placement below; the resolution — add it to the
32/// enumeration, or redesign `health` so no such type crosses the boundary —
33/// belongs to the contract's owner, not to this crate. See `AGENTS.md`.
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
35// 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 a third time in this type's own doc comment above and in AGENTS.md's "Open contract question — `Health`": `Health`'s shape is approved contract text that `TaskSource::health` returns, so an enum here would change the serialized form and the trait six undispatched nodes implement. That is the contract owner's call, not this crate's.
36pub struct Health {
37    /// Whether the source answered.
38    ///
39    /// A bare `bool` beside an untyped `detail` cannot say that an unreachable source
40    /// must explain itself, or keep "reachable with a warning" apart from "reachable";
41    /// an enum carrying the detail in its unreachable variant would.
42    // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this
43    // restates at this field the justification already recorded at
44    // `Capabilities.max_page_size` (capability.rs), `PageRequest.limit` (query.rs), this
45    // type's own doc comment above, and AGENTS.md's "Open contract question — `Health`":
46    // `Health`'s shape is approved contract text that `TaskSource::health` returns, so an
47    // enum here would change the serialized form and the trait six undispatched nodes
48    // implement. That is the contract owner's call, not this crate's.
49    // llmlint: ignore[boundary_inputs_validated] making "unreachable with no reason given" unrepresentable means an enum here, which changes the serialized form and the trait six undispatched nodes implement. Deferred to the contract's owner — AGENTS.md, "Open contract question — `Health`".
50    pub reachable: bool,
51    /// What the source said, when it said anything useful.
52    pub detail: Option<String>,
53}
54
55/// One configured source, as the engine drives it.
56///
57/// Dyn-compatible through `async_trait` because the engine holds
58/// `Vec<Box<dyn TaskSource>>` over heterogeneous plugins.
59///
60/// Three rules bind every implementation, and the engine's compensation is only
61/// correct while all three hold:
62///
63/// 1. **Apply** every predicate you declare [`Support::Native`](crate::Support::Native).
64/// 2. **Ignore** every [`Support`](crate::Support)-typed predicate you declare
65///    `Unsupported` — return the *wider* result set, never a narrower one.
66///    Silently dropping rows for a predicate you did not declare is the one
67///    failure no test above the plugin can catch.
68/// 3. Never return a silently empty dependency read. Rule 2 reaches the
69///    `Support`-typed *predicates* alone; a dependency read is always real, and so is a
70///    document read — [`Capabilities::documents`] says whether this source has documents
71///    at all, and a source that says it has none is never asked for one rather than
72///    answering an empty page.
73#[async_trait::async_trait]
74pub trait TaskSource: Send + Sync {
75    /// The plugin kind that built this source, for display and for plan output.
76    fn kind(&self) -> &'static str;
77
78    /// What this source applies itself. Read once per query by the engine.
79    fn capabilities(&self) -> Capabilities;
80
81    /// How `a`, a [`Task::version`] this source gave one of its tasks, stands to `b`, another
82    /// it gave the same task: `Greater` when `a` is the later, `Less` when it is the earlier,
83    /// `Equal` when nothing the token covers changed between them, and `None` when the two
84    /// cannot be put in order — a value this source cannot read, or two versions its token
85    /// says differ without saying which came first.
86    ///
87    /// A token's format and its order are the one source's that spells it, so the engine asks
88    /// the source that gave both rather than reading inside either.
89    ///
90    /// Defaulted to equality alone: two identical tokens are one version, and any two others
91    /// are unordered, which a reader takes as *changed, read it again* and never as
92    /// unchanged. A source whose token says which of two versions is the later overrides it.
93    fn order_versions(&self, a: &str, b: &str) -> Option<Ordering> {
94        (a == b).then_some(Ordering::Equal)
95    }
96
97    /// Which parts of a task this source's [`Task::version`] vouches for, which is what the
98    /// store's local cache may serve a task's parts from.
99    ///
100    /// Defaulted to no part, which keeps the cache from ever serving what a token was never
101    /// promised to cover: a source overrides it only for the parts its token covers, as
102    /// `docs/plugin-protocol.md` §4.13d states them.
103    fn version_coverage(&self) -> VersionCoverage {
104        VersionCoverage::none(format!(
105            "the {} plugin does not declare that its change token covers a task",
106            self.kind()
107        ))
108    }
109
110    /// Which parts of a task a copy may take this source's unchanged [`Task::version`] as
111    /// vouching for, when it decides to skip a task its destination already holds as written:
112    /// the task's fields, its comments when the copy carries them, and its forward edges. A copy
113    /// skips only a task whose source covers every one of those it writes.
114    ///
115    /// Defaulted to [`version_coverage`](Self::version_coverage). A source overrides it only to
116    /// state, with its measured bound, a claim about a copy's skip that is not one the cache may
117    /// serve from — as `docs/plugin-protocol.md` §4.13d does for the one plugin that does.
118    fn copy_version_coverage(&self) -> VersionCoverage {
119        self.version_coverage()
120    }
121
122    /// Which parts of a project this source's [`Project::version`] vouches for, on the terms
123    /// of [`version_coverage`](Self::version_coverage).
124    ///
125    /// Defaulted to no part, for the same reason.
126    fn project_version_coverage(&self) -> ProjectVersionCoverage {
127        ProjectVersionCoverage::none(format!(
128            "the {} plugin does not declare that its change token covers a project",
129            self.kind()
130        ))
131    }
132
133    /// Which parts of a document this source's [`Document::version`] vouches for, on the terms
134    /// of [`version_coverage`](Self::version_coverage).
135    ///
136    /// Defaulted to no part, for the same reason.
137    fn document_version_coverage(&self) -> DocumentVersionCoverage {
138        DocumentVersionCoverage::none(format!(
139            "the {} plugin does not declare that its change token covers a document",
140            self.kind()
141        ))
142    }
143
144    /// Tell this source the store's local cache now stands in front of it.
145    ///
146    /// Called exactly once, by the cache as it wraps the source, before any read and before
147    /// any coverage is read — so a source whose token needs a part only a wider selection
148    /// carries can widen its reads here, and declare the coverage that widening buys. Never
149    /// carried over the plugin protocol, as [`version_coverage`](Self::version_coverage) is
150    /// not.
151    ///
152    /// Defaulted to doing nothing: a source not overriding it reads exactly as it did.
153    fn attach_cache(&self) {}
154
155    /// The change token the response that answered this source's last
156    /// [`Direction::DependsOn`] read of task `id` in this process spelled, or `None` when it
157    /// spelled none.
158    ///
159    /// What lets the store's cache keep a task's forward edges by the version they were read
160    /// at when nothing else in the command read the task: those edges are served only to a pin
161    /// that version is at or after, and never vouch for the task's own fields. Synchronous, and
162    /// never carried over the plugin protocol, as [`version_coverage`](Self::version_coverage)
163    /// is not.
164    ///
165    /// Defaulted to `None`: a source whose dependency read spells no token keeps its edges
166    /// remote unless a read of the task itself vouched for them.
167    fn forward_edges_version(&self, id: &NativeId) -> Option<String> {
168        let _ = id;
169        None
170    }
171
172    /// The change token the response that answered this source's last dependency read of the
173    /// `kind` item `id` in `direction`, from its first page, spelled — or `None` when it spelled
174    /// none — on the terms of [`forward_edges_version`](Self::forward_edges_version), which is
175    /// what it answers for a task's [`Direction::DependsOn`].
176    ///
177    /// What lets the store's cache keep a project's forward edges, and either kind's reverse
178    /// ones, by the version they were read at: a project's forward edges are served only where
179    /// [`project_version_coverage`](Self::project_version_coverage) covers them, reverse ones only
180    /// where [`reverse_edges_coverage`](Self::reverse_edges_coverage) covers that kind's, and each
181    /// only to a pin that version is at or after. Synchronous, and never
182    /// carried over the plugin protocol.
183    ///
184    /// Defaulted to [`forward_edges_version`](Self::forward_edges_version) for a task's forward
185    /// edges and to `None` for every other read, which keeps those remote.
186    fn edges_version(&self, kind: ItemKind, id: &NativeId, direction: Direction) -> Option<String> {
187        match (kind, direction) {
188            (ItemKind::Task, Direction::DependsOn) => self.forward_edges_version(id),
189            _ => None,
190        }
191    }
192
193    /// Whether this source's token for a `kind` item — [`Task::version`] or
194    /// [`Project::version`] — vouches for its reverse edges, what a [`Direction::DependedOnBy`]
195    /// read answers, so the store's cache may serve them.
196    ///
197    /// A reverse edge is recorded on another item, so a token vouches for one only where it
198    /// carries a part that moves whenever one is added to or removed from that other item —
199    /// which no part of an item's own fields does. Never carried over the plugin protocol.
200    ///
201    /// Defaulted to not covering them, with that reason.
202    fn reverse_edges_coverage(&self, kind: ItemKind) -> crate::Coverage {
203        crate::Coverage::Uncovered {
204            reason: format!(
205                "the {} plugin does not declare that its change token covers a {}'s reverse \
206                 edges, which are recorded on the items that depend on it",
207                self.kind(),
208                match kind {
209                    ItemKind::Task => "task",
210                    ItemKind::Project => "project",
211                }
212            ),
213        }
214    }
215
216    /// What this source holds about task `id` — the item it read last in this process — that
217    /// a later write expecting that version of it could take instead of reading it again, or
218    /// `None` when it holds nothing of the kind.
219    ///
220    /// Opaque to the engine, which keeps it beside the cached task and hands it back through
221    /// [`prime_write`](Self::prime_write). Defaulted to `None`: a source whose writes read
222    /// nothing first has nothing to keep.
223    fn write_context(&self, id: &NativeId) -> Option<serde_json::Value> {
224        let _ = id;
225        None
226    }
227
228    /// What this source holds about the container every task of it shares — a board's field
229    /// and option ids — that a write could take instead of reading it, or `None`.
230    ///
231    /// Defaulted to `None`, on the terms of [`write_context`](Self::write_context).
232    fn board_context(&self) -> Option<serde_json::Value> {
233        None
234    }
235
236    /// Hold `context`, which [`write_context`](Self::write_context) gave for task `id` at a
237    /// version the caller expects it still at, and `board`, which
238    /// [`board_context`](Self::board_context) gave, so the next write of `id` takes them
239    /// instead of reading — answering whether it took them.
240    ///
241    /// A context this source cannot read is not taken, and the write then reads as it always
242    /// does. Defaulted to taking nothing.
243    fn prime_write(
244        &self,
245        id: &NativeId,
246        context: &serde_json::Value,
247        board: Option<&serde_json::Value>,
248    ) -> bool {
249        let _ = (id, context, board);
250        false
251    }
252
253    /// Drop whatever [`prime_write`](Self::prime_write) took for `id`, and the board context
254    /// with it, so the next write of it reads afresh.
255    fn unprime(&self, id: &NativeId) {
256        let _ = id;
257    }
258
259    /// Start recording every request this source sends, for [`end_journal`](Self::end_journal).
260    ///
261    /// The engine opens one journal around one write at a time. Defaulted to recording
262    /// nothing.
263    fn begin_journal(&self) {}
264
265    /// Stop recording, answering with every request sent since
266    /// [`begin_journal`](Self::begin_journal) — or `None` for a source that records none.
267    fn end_journal(&self) -> Option<WriteJournal> {
268        None
269    }
270
271    /// Whether the source is answering right now.
272    ///
273    /// # Errors
274    ///
275    /// Returns a [`SourceError`] when the check itself could not be made.
276    async fn health(&self) -> Result<Health, SourceError>;
277
278    /// Fetch one task by its native id, or `None` when there is no such task.
279    ///
280    /// # Errors
281    ///
282    /// Returns a [`SourceError`] when the source could not answer.
283    async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError>;
284
285    /// Fetch several tasks by their native ids, each with the first page of its comments
286    /// when `comments` names the page to read — one answer per id, in the order they were
287    /// given.
288    ///
289    /// Each answer is what [`get_task`](Self::get_task) answers for that id, so a task that
290    /// is not there is `Ok(None)` and a read that failed fails that id alone. Its
291    /// [`TaskDetailRead::comments`] is what [`task_comments`](Self::task_comments) answers
292    /// for `comments`. The engine passes `comments` only to a source declaring
293    /// [`Capabilities::comments`](crate::Capabilities::comments) native.
294    ///
295    /// Defaulted to exactly those calls, item by item, so a source that implements nothing
296    /// here answers as it always did. A source that can read many items — or an item and its
297    /// comments — in fewer requests than that overrides it, which is the whole reason it
298    /// exists: a caller holding twenty ids pays for one batch rather than forty reads.
299    async fn get_task_details(
300        &self,
301        ids: &[NativeId],
302        comments: Option<&PageRequest>,
303    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
304        let mut read = Vec::with_capacity(ids.len());
305        for id in ids {
306            read.push(match self.get_task(id).await {
307                Ok(Some(task)) => {
308                    let comments = match comments {
309                        Some(page) => Some(self.task_comments(id, page).await),
310                        None => None,
311                    };
312                    Ok(Some(TaskDetailRead { task, comments }))
313                }
314                Ok(None) => Ok(None),
315                Err(error) => Err(error),
316            });
317        }
318        read
319    }
320
321    /// Fetch one project by its native id, or `None` when there is no such project.
322    ///
323    /// # Errors
324    ///
325    /// Returns a [`SourceError`] when the source could not answer.
326    async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError>;
327
328    /// One page of the tasks matching `query`.
329    ///
330    /// # Errors
331    ///
332    /// Returns a [`SourceError`] when the source could not answer.
333    async fn query_tasks(
334        &self,
335        query: &TaskQuery,
336        page: &PageRequest,
337    ) -> Result<Page<Task>, SourceError>;
338
339    /// One page of the projects matching `query`.
340    ///
341    /// # Errors
342    ///
343    /// Returns a [`SourceError`] when the source could not answer.
344    async fn query_projects(
345        &self,
346        query: &ProjectQuery,
347        page: &PageRequest,
348    ) -> Result<Page<Project>, SourceError>;
349
350    /// One page of every label this source knows.
351    ///
352    /// # Errors
353    ///
354    /// Returns a [`SourceError`] when the source could not answer.
355    async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError>;
356
357    /// One page of the task dependency edges at `id`, in `direction`.
358    ///
359    /// # Errors
360    ///
361    /// Returns a [`SourceError`] when the source could not answer.
362    async fn task_dependencies(
363        &self,
364        id: &NativeId,
365        direction: Direction,
366        page: &PageRequest,
367    ) -> Result<Page<DependencyEdge>, SourceError>;
368
369    /// One page of the project dependency edges at `id`, in `direction`.
370    ///
371    /// # Errors
372    ///
373    /// Returns a [`SourceError`] when the source could not answer.
374    async fn project_dependencies(
375        &self,
376        id: &NativeId,
377        direction: Direction,
378        page: &PageRequest,
379    ) -> Result<Page<DependencyEdge>, SourceError>;
380
381    /// Whether this source can be written through at all.
382    ///
383    /// Defaulted to [`WriteSupport::Unsupported`], which is what keeps this a read
384    /// interface for every source that has nothing to write into: one that cannot be
385    /// written needs no edit and keeps working. Read before a write is attempted, so a
386    /// copy naming such a source as its destination is refused before anything is read.
387    fn writes(&self) -> WriteSupport {
388        WriteSupport::Unsupported
389    }
390
391    /// Create or update one task, answering with the native id the destination holds it
392    /// under.
393    ///
394    /// A source declaring [`WriteSupport::Supported`] owes three things here. It refuses,
395    /// naming the field, anything it cannot represent rather than dropping it — including
396    /// a metadata key it cannot carry, which it names. It writes every other field it was
397    /// given. And it never creates when [`ItemWrite::target`] names an item it does not
398    /// hold.
399    ///
400    /// # Errors
401    ///
402    /// Returns [`SourceError::Refused`] when this source has no write side, when a field
403    /// or a metadata key cannot be represented, or when `target` names nothing here; and
404    /// whatever else the source could not do the write for.
405    async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
406        let _ = write;
407        Err(unwritable(self.kind()))
408    }
409
410    /// Create or update one project, on exactly the terms of
411    /// [`write_task`](Self::write_task).
412    ///
413    /// # Errors
414    ///
415    /// As [`write_task`](Self::write_task).
416    async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
417        let _ = write;
418        Err(unwritable(self.kind()))
419    }
420
421    /// Whether this source can represent every field of `write` — its status, its content, the
422    /// tasks it delivers and every other field a [`write_task`](Self::write_task) of it would
423    /// refuse as "cannot represent the field …" — asked before anything is written and changing
424    /// nothing.
425    ///
426    /// A task copy asks it of every task it plans before its first write, and leaves out each
427    /// task this refuses — answered `failed`, with this refusal as its reason — writing the rest
428    /// as one copy. It answers what the write itself would refuse in the same words; and it is a
429    /// promise only about representability, so a write may still fail for any other reason.
430    ///
431    /// Defaulted to `Ok(())`: a source that does not answer it in advance still refuses such a
432    /// write in its write, which a copy then takes back whole, exactly as before.
433    ///
434    /// # Errors
435    ///
436    /// Returns [`SourceError::Refused`] naming the field this source cannot represent; and
437    /// whatever else kept it from finding out.
438    async fn check_task_write(&self, write: &ItemWrite<Task>) -> Result<(), SourceError> {
439        let _ = write;
440        Ok(())
441    }
442
443    /// Whether a write of an item of `kind` at `category` — over the item `target` names, or
444    /// creating one when it is `None` — would have a status to write, asked before the write
445    /// and changing nothing.
446    ///
447    /// A caller that has to put an item back when a later write of it fails — a copy, whose
448    /// journal records what an item held before overwriting it — asks this first, so a status
449    /// this source has no name for is refused while nothing has been recorded or written, and
450    /// nothing has to be put back. It answers what the write itself would refuse a status
451    /// with, in the same words, and sends no request a write of that status would not have
452    /// sent anyway: what it reads to answer, it holds for the write that follows.
453    ///
454    /// Defaulted to `Ok(())`: a source that does not answer it in advance still refuses the
455    /// status in its write, exactly as before.
456    ///
457    /// # Errors
458    ///
459    /// Returns [`SourceError::Refused`] naming the kind, the category and what is missing
460    /// when this source has no name for that status; and whatever else kept it from finding
461    /// out.
462    async fn check_status_write(
463        &self,
464        kind: ItemKind,
465        category: StatusCategory,
466        target: Option<&NativeId>,
467    ) -> Result<(), SourceError> {
468        let _ = (kind, category, target);
469        Ok(())
470    }
471
472    /// Set the status of one task this source holds, and change nothing else about it,
473    /// answering with the status as this source now reads it — or `None` when this source
474    /// holds no such task.
475    ///
476    /// The category lands where this source's own mapping sends it, exactly as a
477    /// [`write_task`](Self::write_task) of a task in that category would: a category this
478    /// source has disabled is refused in the words a write of it is refused with. Title,
479    /// content, labels, metadata, dependencies, [`Task::delivers`], [`Task::delivered_by`],
480    /// project and comments are left exactly as they are.
481    ///
482    /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
483    /// break: a source that cannot write a status on its own needs no edit and refuses by
484    /// saying so. A source declaring [`WriteSupport::Unsupported`] is never asked.
485    ///
486    /// [`Task::delivers`]: crate::Task::delivers
487    /// [`Task::delivered_by`]: crate::Task::delivered_by
488    ///
489    /// # Errors
490    ///
491    /// Returns [`SourceError::Refused`] when this source cannot write a status, or cannot
492    /// write this one; and whatever else the source could not do the write for.
493    async fn set_task_status(
494        &self,
495        id: &NativeId,
496        category: StatusCategory,
497    ) -> Result<Option<Status>, SourceError> {
498        let _ = (id, category);
499        Err(unwritable_field(self.kind(), "status"))
500    }
501
502    /// Set the status of one project this source holds, and change nothing else about it,
503    /// answering with the status as this source now reads it — or `None` when this source
504    /// holds no such project.
505    ///
506    /// The category lands where this source's own mapping sends it for a project, exactly as a
507    /// [`write_project`](Self::write_project) of a project in that category would: a category
508    /// this source has disabled is refused in the words a write of it is refused with. Title,
509    /// content, labels, metadata, repositories, dependencies and the project's tasks are left
510    /// exactly as they are. A project delivers no task, so nothing is kept in step after it.
511    ///
512    /// Defaulted to the refusal [`set_task_status`](Self::set_task_status) defaults to,
513    /// [`unwritable_field`] naming `status`, which is what keeps this an addition rather than a
514    /// break: a source that does not implement it needs no edit. A source declaring
515    /// [`WriteSupport::Unsupported`] is never asked.
516    ///
517    /// # Errors
518    ///
519    /// Returns [`SourceError::Refused`] when this source cannot write a project's status, or
520    /// cannot write this one; and whatever else the source could not do the write for.
521    async fn set_project_status(
522        &self,
523        id: &NativeId,
524        category: StatusCategory,
525    ) -> Result<Option<Status>, SourceError> {
526        let _ = (id, category);
527        Err(unwritable_field(self.kind(), "status"))
528    }
529
530    /// Set the status of one task this source holds, as [`set_task_status`](Self::set_task_status)
531    /// does, and answer with the whole task as this source now reads it — its
532    /// [`Task::delivers`] among what a caller keeping delivered tasks in step needs — or `None`
533    /// when this source holds no such task.
534    ///
535    /// Defaulted to exactly the two calls a caller would otherwise make: [`get_task`] first,
536    /// answering `None` with nothing written when it does, then `set_task_status`, the status
537    /// it answers put on the task read. A source whose status write answers the whole task in
538    /// the same round trip overrides it to save the read.
539    ///
540    /// [`Task::delivers`]: crate::Task::delivers
541    /// [`get_task`]: Self::get_task
542    ///
543    /// # Errors
544    ///
545    /// As [`get_task`](Self::get_task) and [`set_task_status`](Self::set_task_status).
546    async fn set_task_status_reading(
547        &self,
548        id: &NativeId,
549        category: StatusCategory,
550    ) -> Result<Option<Task>, SourceError> {
551        let Some(mut task) = self.get_task(id).await? else {
552            return Ok(None);
553        };
554        let Some(status) = self.set_task_status(id, category).await? else {
555            return Ok(None);
556        };
557        task.status = status;
558        Ok(Some(task))
559    }
560
561    /// Every task this source holds whose card contradicts its issue's closure, each with the
562    /// status that brings it in line — what `task status reconcile` writes, through
563    /// [`set_task_status`](Self::set_task_status), one task at a time.
564    ///
565    /// A task needs it when its issue is closed with a reason that reads `done` or
566    /// `cancelled` and its card does not sit at the option this source's mapping gives that
567    /// category. An open task, a closure that reads `unknown` and a card already in line are
568    /// never answered. Changes nothing.
569    ///
570    /// Asked only of a source declaring
571    /// [`Capabilities::reconcile_status`](crate::Capabilities::reconcile_status); defaulted to a
572    /// refusal saying so, which no caller holding to that declaration ever receives.
573    ///
574    /// # Errors
575    ///
576    /// Returns [`SourceError::Refused`] when this source answers no such question; and whatever
577    /// kept it from reading its items.
578    async fn status_contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
579        Err(SourceError::Refused {
580            message: format!(
581                "a {} source's status is its closure, so nothing needs reconciling",
582                self.kind()
583            ),
584        })
585    }
586
587    /// For each issue in `issues`, in order and once each, the task this source holds for it
588    /// and what moving it to `done` comes to — what `task status complete` writes, through
589    /// [`set_task_status`](Self::set_task_status), for each one answered
590    /// [`Completion::Due`](crate::Completion::Due).
591    ///
592    /// The read is proportional to `issues` and never to the size of what this source holds,
593    /// and an empty `issues` reads nothing. Changes nothing.
594    ///
595    /// Asked only of a source declaring
596    /// [`Capabilities::complete_by_issue`](crate::Capabilities::complete_by_issue); defaulted
597    /// to a refusal saying so, which no caller holding to that declaration ever receives.
598    ///
599    /// # Errors
600    ///
601    /// Returns [`SourceError::Refused`] when this source answers no such question; and whatever
602    /// kept it from reading the issues.
603    async fn issue_holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
604        let _ = issues;
605        Err(SourceError::Refused {
606            message: format!("a {} source holds no items by issue reference", self.kind()),
607        })
608    }
609
610    /// Set the priority of one task this source holds, and change nothing else about it,
611    /// answering with the priority as this source now reads it — or `None` when this source
612    /// holds no such task.
613    ///
614    /// [`Priority::None`] clears the priority. Title, content, status, labels, metadata,
615    /// repositories, dependencies and comments are left exactly as they are. Nothing about
616    /// the task's status moves, so the engine re-evaluates no delivered task after it.
617    ///
618    /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
619    /// break. A source declaring [`WriteSupport::Unsupported`], or declaring
620    /// [`Capabilities::priority`] unsupported, is never asked.
621    ///
622    /// # Errors
623    ///
624    /// Returns [`SourceError::Refused`] when this source cannot write a priority, or cannot
625    /// write this one — a board with no option for it, naming the option; and whatever else
626    /// the source could not do the write for.
627    async fn set_task_priority(
628        &self,
629        id: &NativeId,
630        priority: Priority,
631    ) -> Result<Option<Priority>, SourceError> {
632        let _ = (id, priority);
633        Err(unwritable_field(self.kind(), "priority"))
634    }
635
636    /// Replace the content of one task this source holds with `content`, byte for byte, and
637    /// change nothing else about it — or answer `None` when this source holds no such task.
638    ///
639    /// The content is [`Task::content`] exactly as this source reports it: what a later read
640    /// answers there is `content`. Where the source keeps something else inside the same
641    /// backend field — a metadata block in an issue body — that is kept as it was, and so is
642    /// every other member: title, status, priority, labels, metadata, repositories,
643    /// dependencies, project and comments. Nothing about the task's status moves, so the
644    /// engine re-evaluates no delivered task after it.
645    ///
646    /// Defaulted to [`unwritable_field`] on exactly the terms of
647    /// [`set_task_status`](Self::set_task_status). A source declaring
648    /// [`WriteSupport::Unsupported`] is never asked.
649    ///
650    /// # Errors
651    ///
652    /// Returns [`SourceError::Refused`] when this source cannot write a task's content on its
653    /// own, or cannot represent this one; and whatever else the source could not do the write
654    /// for.
655    async fn set_task_content(
656        &self,
657        id: &NativeId,
658        content: &str,
659    ) -> Result<Option<()>, SourceError> {
660        let _ = (id, content);
661        Err(unwritable_field(self.kind(), "content"))
662    }
663
664    /// Replace the [`Task::delivered_by`] of one task this source holds, and change nothing
665    /// else about it — or answer `None` when this source holds no such task.
666    ///
667    /// Every entry is a qualified id, and the list is the whole of it: what the task held
668    /// there before is replaced, not merged. It is the store's to keep in step — the engine
669    /// calls this whenever it writes a task's [`Task::delivers`] — and nothing a person types
670    /// reaches it directly.
671    ///
672    /// Defaulted to [`unwritable_field`] on exactly the terms of
673    /// [`set_task_status`](Self::set_task_status).
674    ///
675    /// [`Task::delivers`]: crate::Task::delivers
676    /// [`Task::delivered_by`]: crate::Task::delivered_by
677    ///
678    /// # Errors
679    ///
680    /// Returns [`SourceError::Refused`] when this source cannot hold the list, and whatever
681    /// else it could not do the write for.
682    async fn set_delivered_by(
683        &self,
684        id: &NativeId,
685        delivered_by: &[TaskRef],
686    ) -> Result<Option<()>, SourceError> {
687        let _ = (id, delivered_by);
688        Err(unwritable_field(self.kind(), "delivered_by"))
689    }
690
691    /// Set one key of the metadata of one task this source holds, and change nothing else
692    /// about it, answering with the task as this source reads it back after the write — or
693    /// `None` when this source holds no such task.
694    ///
695    /// The key is added when the task does not hold it and replaced when it does; every other
696    /// metadata key, and every other field of the task, is left exactly as it was. A `value`
697    /// the task already holds under `key` is a write that changes nothing, and a source owes
698    /// it no write at all. The answer is a read, not an echo: what the engine reports as the
699    /// value is what the returned task holds under `key`.
700    ///
701    /// Nothing about the task's status or its [`Task::delivers`] moves, so the engine
702    /// re-evaluates no delivered task after this write.
703    ///
704    /// Defaulted to [`unwritable_metadata`] on exactly the terms of
705    /// [`set_task_status`](Self::set_task_status): a source that cannot write one key on its
706    /// own needs no edit and refuses by saying so. A source declaring
707    /// [`WriteSupport::Unsupported`] is never asked.
708    ///
709    /// [`Task::delivers`]: crate::Task::delivers
710    ///
711    /// # Errors
712    ///
713    /// Returns [`SourceError::Refused`] when this source cannot write one key of a task's
714    /// metadata on its own, or cannot write this one without changing something else; and
715    /// whatever else the source could not do the write for.
716    async fn set_task_metadata(
717        &self,
718        id: &NativeId,
719        key: &MetadataKey,
720        value: &Value,
721    ) -> Result<Option<Task>, SourceError> {
722        let _ = (id, key, value);
723        Err(unwritable_metadata(self.kind(), MetadataRecord::Task))
724    }
725
726    /// Apply a targeted update to one task this source holds — every field `update` names, and
727    /// nothing else — answering with a [`TaskUpdateOutcome`], or `None` when this source holds
728    /// no such task.
729    ///
730    /// The outcome is everything the engine reports about the call, so it reads nothing of its
731    /// own: the task as this source reads it once the update landed — from the one read it made
732    /// and what it then wrote, where its backend answers a write with what it holds — the
733    /// fields it actually wrote, and the `delivers` the task held before.
734    ///
735    /// A field already holding the requested value is sent no write, and an update in which
736    /// nothing differs sends no write at all. Every field `update` leaves unnamed — labels,
737    /// repositories, project, [`Task::delivered_by`] and comments always among them — is left
738    /// exactly as it is. An update naming one metadata key both to set and to remove is refused
739    /// before anything is written, in the words of [`TaskUpdate::consistent`].
740    ///
741    /// Defaulted to [`TaskUpdate::rewrite`]: read the task, apply the update, and — only when
742    /// anything differs — [`write_task`](Self::write_task) it with its `target` set. That keeps
743    /// this an addition rather than a break, and a source that predates it behaves correctly and
744    /// is merely not minimal; one whose backend can take a field on its own owes an override
745    /// that sends only what differs. A source declaring [`WriteSupport::Unsupported`] is never
746    /// asked.
747    ///
748    /// [`Task::delivered_by`]: crate::Task::delivered_by
749    ///
750    /// # Errors
751    ///
752    /// Returns [`SourceError::Refused`] when the update contradicts itself, when a field it
753    /// names cannot be represented here — a category this source has disabled included — and
754    /// whatever else the source could not do the write for.
755    async fn update_task(
756        &self,
757        id: &NativeId,
758        update: &TaskUpdate,
759    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
760        update.rewrite(self, id).await
761    }
762
763    /// Set one key of the metadata of one project this source holds, on exactly the terms of
764    /// [`set_task_metadata`](Self::set_task_metadata).
765    ///
766    /// # Errors
767    ///
768    /// As [`set_task_metadata`](Self::set_task_metadata).
769    async fn set_project_metadata(
770        &self,
771        id: &NativeId,
772        key: &MetadataKey,
773        value: &Value,
774    ) -> Result<Option<Project>, SourceError> {
775        let _ = (id, key, value);
776        Err(unwritable_metadata(self.kind(), MetadataRecord::Project))
777    }
778
779    /// Set one key of the metadata of one document this source holds, on exactly the terms of
780    /// [`set_task_metadata`](Self::set_task_metadata).
781    ///
782    /// A source declaring [`Capabilities::documents`] unsupported is never asked, exactly as
783    /// it is never asked for a document read.
784    ///
785    /// # Errors
786    ///
787    /// As [`set_task_metadata`](Self::set_task_metadata).
788    async fn set_document_metadata(
789        &self,
790        id: &NativeId,
791        key: &MetadataKey,
792        value: &Value,
793    ) -> Result<Option<Document>, SourceError> {
794        let _ = (id, key, value);
795        Err(unwritable_metadata(self.kind(), MetadataRecord::Document))
796    }
797
798    /// Remove one task this destination holds, so a copy that could not finish can put
799    /// the destination back the way it found it.
800    ///
801    /// This is not a verb of the product: nothing a user types deletes anything, and a
802    /// copy never deletes an item it did not itself create in the run that is failing.
803    /// It exists because a copy is either complete or it never happened — a half-written
804    /// project has to be run again, and the re-run is the mutation burst that trips a
805    /// hosted destination's rate limiter. Undoing this run's own creates is what removes
806    /// that retry at source.
807    ///
808    /// A source declaring [`WriteSupport::Supported`] owes a real implementation, for the
809    /// reason it owes [`write_task`](Self::write_task) one: the engine will create items
810    /// there, so it has to be able to remove the ones it created. An `id` naming nothing
811    /// is **not** an error — the item is already gone, which is the state this asks for.
812    ///
813    /// # Errors
814    ///
815    /// Returns [`SourceError::Refused`] when this source has no write side, and whatever
816    /// else the source could not remove the item for.
817    async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
818        let _ = id;
819        Err(unwritable(self.kind()))
820    }
821
822    /// Remove one project this destination holds, on exactly the terms of
823    /// [`delete_task`](Self::delete_task).
824    ///
825    /// # Errors
826    ///
827    /// As [`delete_task`](Self::delete_task).
828    async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
829        let _ = id;
830        Err(unwritable(self.kind()))
831    }
832
833    /// Fetch one document by its native id, or `None` when there is no such document.
834    ///
835    /// Defaulted to [`documentless`], which is what keeps documents an addition rather
836    /// than a break: a source with none needs no edit, keeps working, and says so in the
837    /// same words every other document-free source does. A source that has documents
838    /// declares [`Support::Native`](crate::Support::Native) for
839    /// [`Capabilities::documents`] and owes a real implementation here, because that
840    /// declaration is what makes the engine ask.
841    ///
842    /// # Errors
843    ///
844    /// Returns [`SourceError::Refused`] when this source has no documents, and whatever
845    /// else the source could not answer for.
846    async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
847        let _ = id;
848        Err(documentless(self.kind()))
849    }
850
851    /// One page of the documents matching `query`.
852    ///
853    /// Defaulted on exactly the terms of [`get_document`](Self::get_document). A source
854    /// with no documents refuses rather than answering an empty page: an empty page reads
855    /// as a source that has documents and holds none matching, which is the one wrong
856    /// answer this method can give.
857    ///
858    /// # Errors
859    ///
860    /// As [`get_document`](Self::get_document).
861    async fn query_documents(
862        &self,
863        query: &DocumentQuery,
864        page: &PageRequest,
865    ) -> Result<Page<Document>, SourceError> {
866        let _ = (query, page);
867        Err(documentless(self.kind()))
868    }
869
870    /// Create or update one document, on exactly the terms of
871    /// [`write_task`](Self::write_task).
872    ///
873    /// # Errors
874    ///
875    /// As [`write_task`](Self::write_task).
876    async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
877        let _ = write;
878        Err(unwritable(self.kind()))
879    }
880
881    /// Remove one document this destination holds, on exactly the terms of
882    /// [`delete_task`](Self::delete_task).
883    ///
884    /// # Errors
885    ///
886    /// As [`delete_task`](Self::delete_task).
887    async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
888        let _ = id;
889        Err(unwritable(self.kind()))
890    }
891
892    /// One page of the comments on `task`, oldest first, or `None` when this source holds
893    /// no such task.
894    ///
895    /// Defaulted to [`commentless`], which is what keeps comments an addition rather than a
896    /// break: a source with none needs no edit and keeps working. A source whose tasks have
897    /// comments declares [`Support::Native`](crate::Support::Native) for
898    /// [`Capabilities::comments`] and owes a real implementation of all four comment methods,
899    /// because that declaration is what makes the engine ask.
900    ///
901    /// "No such task" is `None` rather than an error, exactly as it is for
902    /// [`get_task`](Self::get_task); a task that exists and has no comments is an empty page.
903    ///
904    /// # Errors
905    ///
906    /// Returns [`SourceError::Refused`] when this source has no comments, and whatever else
907    /// the source could not answer for.
908    async fn task_comments(
909        &self,
910        task: &NativeId,
911        page: &PageRequest,
912    ) -> Result<Option<Page<Comment>>, SourceError> {
913        let _ = (task, page);
914        Err(commentless(self.kind()))
915    }
916
917    /// [`get_task_details`](Self::get_task_details) as a copy reads the tasks it carries: each
918    /// with the first page of its comments `comments` names — and, where the same request can
919    /// carry them, what this source needs to answer [`task_dependencies`](Self::task_dependencies)
920    /// for it without another, since a copy reads every task's edges next.
921    ///
922    /// Defaulted to `get_task_details(ids, Some(comments))`, which is exactly what it answers.
923    /// A source whose detail read is priced by what it selects overrides it with a read that
924    /// also carries the edges, so a copy of a changed task costs its detail read and nothing
925    /// more; one whose reads are free has no reason to.
926    async fn get_task_details_for_copy(
927        &self,
928        ids: &[NativeId],
929        comments: &PageRequest,
930    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
931        self.get_task_details(ids, Some(comments)).await
932    }
933
934    /// Add one comment to `task`, answering with the comment as the source now holds it, or
935    /// `None` when this source holds no such task.
936    ///
937    /// The body is stored byte for byte. A source that records the author itself refuses a
938    /// [`NewComment::author`] rather than dropping it, naming why; a source that cannot
939    /// represent the body refuses it, naming why, rather than escaping it into something
940    /// else.
941    ///
942    /// # Errors
943    ///
944    /// Returns [`SourceError::Refused`] when this source has no comments or cannot be
945    /// written, when it cannot record what it was given, and whatever else it could not do
946    /// the write for.
947    async fn add_comment(
948        &self,
949        task: &NativeId,
950        comment: &NewComment,
951    ) -> Result<Option<Comment>, SourceError> {
952        let _ = (task, comment);
953        Err(commentless(self.kind()))
954    }
955
956    /// Replace the body of the comment `comment` on `task`, answering with the comment as the
957    /// source now holds it, or `None` when this source holds no such task or that task has no
958    /// such comment.
959    ///
960    /// Only the body and the time it last changed move: the id, the author and the time it
961    /// was written are the comment's own.
962    ///
963    /// # Errors
964    ///
965    /// As [`add_comment`](Self::add_comment).
966    async fn edit_comment(
967        &self,
968        task: &NativeId,
969        comment: &NativeId,
970        body: &CommentBody,
971    ) -> Result<Option<Comment>, SourceError> {
972        let _ = (task, comment, body);
973        Err(commentless(self.kind()))
974    }
975
976    /// Remove the comment `comment` from `task`, answering with the id it removed, or `None`
977    /// when this source holds no such task or that task has no such comment.
978    ///
979    /// Unlike [`delete_task`](Self::delete_task), this *is* a verb of the product — a person
980    /// removes a comment they posted — so a comment that is not there is reported as `None`
981    /// for the engine to refuse by name, rather than treated as already gone.
982    ///
983    /// # Errors
984    ///
985    /// As [`add_comment`](Self::add_comment).
986    async fn delete_comment(
987        &self,
988        task: &NativeId,
989        comment: &NativeId,
990    ) -> Result<Option<NativeId>, SourceError> {
991        let _ = (task, comment);
992        Err(commentless(self.kind()))
993    }
994
995    /// Write one comment a copy carries onto `task`: a new one when `existing` is `None`, and
996    /// otherwise the comment `existing`, which a copy wrote before, made to say `copy` — or
997    /// `None` when this source holds no such task or no such comment.
998    ///
999    /// The answer reports [`Comment::origin`] as `copy.origin`, however the source keeps it.
1000    ///
1001    /// **Defaulted to the hidden marker**, which is right for every source that records a
1002    /// comment's author and times itself: the body is written through
1003    /// [`add_comment`](Self::add_comment) or [`edit_comment`](Self::edit_comment) with
1004    /// [`CommentOrigin::mark`](crate::CommentOrigin::mark) appended, and read back
1005    /// [`unmarked`](Comment::unmarked). A source that can store the origin natively — and so
1006    /// takes the origin's own id, author and times for the copy — overrides this.
1007    ///
1008    /// # Errors
1009    ///
1010    /// As [`add_comment`](Self::add_comment).
1011    async fn write_comment_copy(
1012        &self,
1013        task: &NativeId,
1014        existing: Option<&NativeId>,
1015        copy: &CommentCopy,
1016    ) -> Result<Option<Comment>, SourceError> {
1017        let body = CommentBody::new(copy.origin.qualified()?.mark(copy.body.as_str()))?;
1018        let written = match existing {
1019            Some(comment) => self.edit_comment(task, comment, &body).await?,
1020            None => {
1021                self.add_comment(task, &NewComment { body, author: None })
1022                    .await?
1023            }
1024        };
1025        Ok(written.map(Comment::unmarked))
1026    }
1027
1028    /// Whether this source keeps template answers beside its items at all.
1029    ///
1030    /// What lets a regenerate tell an item whose answers went missing — a block deleted by
1031    /// hand, which the regenerate writes back — from an item of a source that never keeps any,
1032    /// where a missing answer is no difference. Defaulted to `false`, as
1033    /// [`task_template_answers`](Self::task_template_answers) is defaulted to `None`; a source
1034    /// that keeps answers answers `true` here.
1035    fn keeps_template_answers(&self) -> bool {
1036        false
1037    }
1038
1039    /// The template answers the task `id` was last rendered from, as this source keeps them
1040    /// beside the task — or `None` when it keeps none for it, or holds no such task.
1041    ///
1042    /// Keeping answers is a source's own choice, never an obligation: a source whose items
1043    /// are one record in a hosted system has no room beside the item that is not the item, and
1044    /// answers written into its content or its metadata would duplicate what the content
1045    /// already says. Defaulted to `None`, which is what keeps this an addition rather than a
1046    /// break. A source that keeps them owes three things: they are in neither
1047    /// [`Task::content`] nor [`Task::metadata`], they are written only by
1048    /// [`write_task_rendered`](Self::write_task_rendered) and
1049    /// [`set_task_rendering`](Self::set_task_rendering), and they come back here exactly as
1050    /// they were written, JSON types intact.
1051    ///
1052    /// # Errors
1053    ///
1054    /// Returns a [`SourceError`] when the source could not answer, a record whose answers it
1055    /// cannot read included.
1056    async fn task_template_answers(
1057        &self,
1058        id: &NativeId,
1059    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
1060        let _ = id;
1061        Ok(None)
1062    }
1063
1064    /// The template answers the document `id` was last rendered from, on exactly the terms of
1065    /// [`task_template_answers`](Self::task_template_answers).
1066    ///
1067    /// # Errors
1068    ///
1069    /// As [`task_template_answers`](Self::task_template_answers).
1070    async fn document_template_answers(
1071        &self,
1072        id: &NativeId,
1073    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
1074        let _ = id;
1075        Ok(None)
1076    }
1077
1078    /// The template answers the project `id` was last rendered from, on exactly the terms of
1079    /// [`task_template_answers`](Self::task_template_answers).
1080    ///
1081    /// # Errors
1082    ///
1083    /// As [`task_template_answers`](Self::task_template_answers).
1084    async fn project_template_answers(
1085        &self,
1086        id: &NativeId,
1087    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
1088        let _ = id;
1089        Ok(None)
1090    }
1091
1092    /// Create or update one task exactly as [`write_task`](Self::write_task) does, keeping
1093    /// `answers` — the answers its content was rendered from — beside it in the same write
1094    /// where this source keeps answers at all.
1095    ///
1096    /// The task arrives carrying its provenance under [`MetadataKey::TEMPLATE_KEY`] like any
1097    /// other metadata entry. Defaulted to [`write_task`](Self::write_task) alone: a source that
1098    /// keeps no answers writes the task and nothing beside it, which is the whole of what it
1099    /// owes. A source that keeps them writes the task and the answers together, so a reader
1100    /// never finds one without the other.
1101    ///
1102    /// # Errors
1103    ///
1104    /// As [`write_task`](Self::write_task).
1105    async fn write_task_rendered(
1106        &self,
1107        write: &ItemWrite<Task>,
1108        answers: &BTreeMap<String, Value>,
1109    ) -> Result<NativeId, SourceError> {
1110        let _ = answers;
1111        self.write_task(write).await
1112    }
1113
1114    /// Create or update one document, on exactly the terms of
1115    /// [`write_task_rendered`](Self::write_task_rendered).
1116    ///
1117    /// # Errors
1118    ///
1119    /// As [`write_document`](Self::write_document).
1120    async fn write_document_rendered(
1121        &self,
1122        write: &ItemWrite<Document>,
1123        answers: &BTreeMap<String, Value>,
1124    ) -> Result<NativeId, SourceError> {
1125        let _ = answers;
1126        self.write_document(write).await
1127    }
1128
1129    /// Create or update one project, on exactly the terms of
1130    /// [`write_task_rendered`](Self::write_task_rendered).
1131    ///
1132    /// # Errors
1133    ///
1134    /// As [`write_project`](Self::write_project).
1135    async fn write_project_rendered(
1136        &self,
1137        write: &ItemWrite<Project>,
1138        answers: &BTreeMap<String, Value>,
1139    ) -> Result<NativeId, SourceError> {
1140        let _ = answers;
1141        self.write_project(write).await
1142    }
1143
1144    /// Replace one task's rendering — its content, byte for byte, its
1145    /// [`MetadataKey::TEMPLATE_KEY`] entry, set to `provenance`, and the answers it keeps
1146    /// beside the task where it keeps any — in one write, and change nothing else about it;
1147    /// or answer `None` when this source holds no such task.
1148    ///
1149    /// The content is [`Task::content`] exactly as a later read reports it, on the terms of
1150    /// [`set_task_content`](Self::set_task_content). Title, status, priority, labels, every
1151    /// other metadata entry, repositories, dependencies, [`Task::delivers`],
1152    /// [`Task::delivered_by`], project and comments are left exactly as they are. The write is
1153    /// one write: a reader sees the task as it was or as it is now, never a new content beside
1154    /// the old provenance or the old answers.
1155    ///
1156    /// Defaulted to [`unwritable_field`] on exactly the terms of
1157    /// [`set_task_status`](Self::set_task_status). A source declaring
1158    /// [`WriteSupport::Unsupported`] is never asked.
1159    ///
1160    /// [`Task::delivers`]: crate::Task::delivers
1161    /// [`Task::delivered_by`]: crate::Task::delivered_by
1162    ///
1163    /// # Errors
1164    ///
1165    /// Returns [`SourceError::Refused`] when this source cannot replace a task's rendering on
1166    /// its own, or cannot represent this one; and whatever else the source could not do the
1167    /// write for.
1168    async fn set_task_rendering(
1169        &self,
1170        id: &NativeId,
1171        content: &str,
1172        provenance: &Value,
1173        answers: &BTreeMap<String, Value>,
1174    ) -> Result<Option<()>, SourceError> {
1175        let _ = (id, content, provenance, answers);
1176        Err(unwritable_field(self.kind(), "rendering"))
1177    }
1178
1179    /// Replace one document's rendering, on exactly the terms of
1180    /// [`set_task_rendering`](Self::set_task_rendering). A source declaring
1181    /// [`Capabilities::documents`] unsupported is never asked.
1182    ///
1183    /// # Errors
1184    ///
1185    /// As [`set_task_rendering`](Self::set_task_rendering).
1186    async fn set_document_rendering(
1187        &self,
1188        id: &NativeId,
1189        content: &str,
1190        provenance: &Value,
1191        answers: &BTreeMap<String, Value>,
1192    ) -> Result<Option<()>, SourceError> {
1193        let _ = (id, content, provenance, answers);
1194        Err(SourceError::Refused {
1195            message: format!(
1196                "the {} plugin cannot write a document's rendering on its own",
1197                self.kind()
1198            ),
1199        })
1200    }
1201
1202    /// Replace one project's rendering, on exactly the terms of
1203    /// [`set_task_rendering`](Self::set_task_rendering): its content, its
1204    /// [`MetadataKey::TEMPLATE_KEY`] entry and the answers kept beside it change, and its
1205    /// title, status, labels, every other metadata entry, repositories and dependencies are
1206    /// left exactly as they are.
1207    ///
1208    /// # Errors
1209    ///
1210    /// As [`set_task_rendering`](Self::set_task_rendering).
1211    async fn set_project_rendering(
1212        &self,
1213        id: &NativeId,
1214        content: &str,
1215        provenance: &Value,
1216        answers: &BTreeMap<String, Value>,
1217    ) -> Result<Option<()>, SourceError> {
1218        let _ = (id, content, provenance, answers);
1219        Err(SourceError::Refused {
1220            message: format!(
1221                "the {} plugin cannot write a project's rendering on its own",
1222                self.kind()
1223            ),
1224        })
1225    }
1226
1227    /// The image assets the task `id` holds, or none when it holds none or this source holds
1228    /// no such task.
1229    ///
1230    /// Defaulted to none, which is what keeps assets an addition rather than a break: a source
1231    /// that keeps no assets needs no edit and reports every record as holding none. A source
1232    /// declaring [`Capabilities::assets`] native answers what it holds for the record, in any
1233    /// order — the engine orders them by the content's first reference.
1234    ///
1235    /// # Errors
1236    ///
1237    /// Returns a [`SourceError`] when the source could not answer.
1238    async fn task_assets(&self, id: &NativeId) -> Result<Vec<Asset>, SourceError> {
1239        let _ = id;
1240        Ok(Vec::new())
1241    }
1242
1243    /// The image assets the document `id` holds, on exactly the terms of
1244    /// [`task_assets`](Self::task_assets).
1245    ///
1246    /// # Errors
1247    ///
1248    /// As [`task_assets`](Self::task_assets).
1249    async fn document_assets(&self, id: &NativeId) -> Result<Vec<Asset>, SourceError> {
1250        let _ = id;
1251        Ok(Vec::new())
1252    }
1253
1254    /// The bytes of the asset `name` the task `id` holds, or `None` when it holds no such asset
1255    /// or this source holds no such task.
1256    ///
1257    /// Defaulted to `None`, on the terms of [`task_assets`](Self::task_assets).
1258    ///
1259    /// # Errors
1260    ///
1261    /// Returns a [`SourceError`] when the source could not answer.
1262    async fn task_asset(
1263        &self,
1264        id: &NativeId,
1265        name: &AssetName,
1266    ) -> Result<Option<Vec<u8>>, SourceError> {
1267        let _ = (id, name);
1268        Ok(None)
1269    }
1270
1271    /// The bytes of the asset `name` the document `id` holds, on exactly the terms of
1272    /// [`task_asset`](Self::task_asset).
1273    ///
1274    /// # Errors
1275    ///
1276    /// As [`task_asset`](Self::task_asset).
1277    async fn document_asset(
1278        &self,
1279        id: &NativeId,
1280        name: &AssetName,
1281    ) -> Result<Option<Vec<u8>>, SourceError> {
1282        let _ = (id, name);
1283        Ok(None)
1284    }
1285
1286    /// Create or update one task carrying image assets, in one write: the task as
1287    /// [`write_task`](Self::write_task) writes it — or, with `answers`, as
1288    /// [`write_task_rendered`](Self::write_task_rendered) does — and `assets` as the record's
1289    /// whole asset set, answering with where it landed and the content as stored.
1290    ///
1291    /// Only a source declaring [`Capabilities::assets`] native is asked, and the engine has
1292    /// already checked that every reference in the content names one of `assets` and every one
1293    /// of `assets` is referenced. A source that keeps the bytes beside the record stores each
1294    /// payload under its name, removes every asset the record held that `assets` does not
1295    /// name, and answers the content unchanged. A source that serves them at a URL uploads each
1296    /// payload that carries bytes, reuses the URL [`AssetWrite::recorded_assets`] records for
1297    /// each that does not, and writes the record through
1298    /// [`serve_asset_references`](crate::serve_asset_references) — so its references point at
1299    /// those URLs, its [`MetadataKey::ASSETS_KEY`] records each `{sha256, url}`, and a
1300    /// rendering's `body_digest` stays true of what landed — answering the content it wrote.
1301    ///
1302    /// Defaulted to [`assetless`], which is what a source with no assets answers.
1303    ///
1304    /// # Errors
1305    ///
1306    /// As [`write_task`](Self::write_task), and [`SourceError::Refused`] from a source that
1307    /// keeps no assets.
1308    async fn write_task_with_assets(
1309        &self,
1310        write: &ItemWrite<Task>,
1311        answers: Option<&BTreeMap<String, Value>>,
1312        assets: &AssetWrite,
1313    ) -> Result<AssetsWritten, SourceError> {
1314        let _ = (write, answers, assets);
1315        Err(assetless(self.kind()))
1316    }
1317
1318    /// Create or update one document carrying image assets, on exactly the terms of
1319    /// [`write_task_with_assets`](Self::write_task_with_assets).
1320    ///
1321    /// # Errors
1322    ///
1323    /// As [`write_task_with_assets`](Self::write_task_with_assets).
1324    async fn write_document_with_assets(
1325        &self,
1326        write: &ItemWrite<Document>,
1327        answers: Option<&BTreeMap<String, Value>>,
1328        assets: &AssetWrite,
1329    ) -> Result<AssetsWritten, SourceError> {
1330        let _ = (write, answers, assets);
1331        Err(assetless(self.kind()))
1332    }
1333
1334    /// Replace one task's rendering as [`set_task_rendering`](Self::set_task_rendering) does,
1335    /// and its asset set as [`write_task_with_assets`](Self::write_task_with_assets) does, in
1336    /// one write; or answer `None` when this source holds no such task.
1337    ///
1338    /// Defaulted to [`assetless`].
1339    ///
1340    /// # Errors
1341    ///
1342    /// As [`set_task_rendering`](Self::set_task_rendering), and [`SourceError::Refused`] from a
1343    /// source that keeps no assets.
1344    async fn set_task_rendering_with_assets(
1345        &self,
1346        id: &NativeId,
1347        content: &str,
1348        provenance: &Value,
1349        answers: &BTreeMap<String, Value>,
1350        assets: &AssetWrite,
1351    ) -> Result<Option<AssetsWritten>, SourceError> {
1352        let _ = (id, content, provenance, answers, assets);
1353        Err(assetless(self.kind()))
1354    }
1355
1356    /// Replace one document's rendering and its asset set, on exactly the terms of
1357    /// [`set_task_rendering_with_assets`](Self::set_task_rendering_with_assets).
1358    ///
1359    /// # Errors
1360    ///
1361    /// As [`set_task_rendering_with_assets`](Self::set_task_rendering_with_assets).
1362    async fn set_document_rendering_with_assets(
1363        &self,
1364        id: &NativeId,
1365        content: &str,
1366        provenance: &Value,
1367        answers: &BTreeMap<String, Value>,
1368        assets: &AssetWrite,
1369    ) -> Result<Option<AssetsWritten>, SourceError> {
1370        let _ = (id, content, provenance, answers, assets);
1371        Err(assetless(self.kind()))
1372    }
1373
1374    /// What this source has sent to its backend since it was built and what that spent, or
1375    /// `None` when it does not meter its own requests.
1376    ///
1377    /// Defaulted to `None`, which is what keeps metering an addition rather than a break: a
1378    /// source that does not count its requests needs no edit, and is reported as not
1379    /// metering rather than as having spent nothing. A source that answers owes a running
1380    /// total — see [`Metering`] — because what one command spent is read as the difference
1381    /// between two readings.
1382    ///
1383    /// # Errors
1384    ///
1385    /// Returns a [`SourceError`] when the reading itself could not be taken. A caller
1386    /// reports such a source as not metering; what a command cost is never a reason for the
1387    /// command to fail.
1388    async fn metering(&self) -> Result<Option<Metering>, SourceError> {
1389        Ok(None)
1390    }
1391
1392    /// End one command: drop everything held that a person can change.
1393    ///
1394    /// A command is one unit of work — one invocation of the binary, or whatever a caller
1395    /// holding one engine for many units of work calls between them. Within a command a
1396    /// source may hold what it read and reuse it; across this call it may not. After it
1397    /// returns, a source answers no read and bases no write on item content, statuses, board
1398    /// contents or search results it held before the call. It may keep only identifiers and
1399    /// vocabulary that stay valid in normal use — a repository's node id, a team's workflow
1400    /// states — and only where a lookup that misses one re-reads rather than refusing.
1401    ///
1402    /// Defaulted to doing nothing, which is right for a source that holds nothing between
1403    /// calls or holds only what the rule above lets it keep. A source that holds more owes
1404    /// an override. Never called by the engine on its own: the binary's one command is its
1405    /// whole process, so only a caller that outlives a command calls it.
1406    ///
1407    /// # Errors
1408    ///
1409    /// Returns a [`SourceError`] when the source could not be sure it dropped what it held —
1410    /// ordinarily a hosted plugin that did not answer. A caller should not go on to the next
1411    /// command on that source's earlier reads.
1412    async fn end_command(&self) -> Result<(), SourceError> {
1413        Ok(())
1414    }
1415
1416    /// Who can read where `target` lands, read live from the backend.
1417    ///
1418    /// This is the destination's reality, which the engine holds a declaration against
1419    /// before it lets a write through: a source a configuration declares private receives an
1420    /// item that may only be written somewhere private only while this answers
1421    /// [`Visibility::Private`]. The engine asks immediately before the write it is about, so
1422    /// a source must not answer from anything it read for an earlier write unless its
1423    /// backend's visibility cannot change in between.
1424    ///
1425    /// Defaulted to [`Visibility::Unknown`], which is the answer of a source that cannot say
1426    /// and is never treated as private. A source on this machine answers `Private` — what it
1427    /// writes stays on the host — and a hosted source reads its backend.
1428    ///
1429    /// # Errors
1430    ///
1431    /// Returns a [`SourceError`] when the backend could not be asked or would not answer —
1432    /// a credential lacking the scope the read needs among them. An unreadable visibility is
1433    /// never guessed: the engine refuses the write.
1434    async fn visibility(&self, target: &WriteTarget<'_>) -> Result<Visibility, SourceError> {
1435        let _ = target;
1436        Ok(Visibility::Unknown)
1437    }
1438}
1439
1440/// The factory that turns one configuration block into a live [`TaskSource`].
1441///
1442/// Having the compile-time registry and the subprocess seam be the same shape is
1443/// the whole reason this is a trait rather than a free function.
1444pub trait SourcePlugin: Send + Sync + 'static {
1445    /// The name a configuration document's `plugin:` field names.
1446    fn kind(&self) -> &'static str;
1447
1448    /// The JSON Schema for this plugin's own `config:` block.
1449    fn config_schema(&self) -> Schema;
1450
1451    /// Build a live source from one configuration block.
1452    ///
1453    /// `name` is the configured source's name, for error messages only — a
1454    /// plugin never learns it for any other purpose.
1455    ///
1456    /// # Errors
1457    ///
1458    /// Returns [`SourceError::Config`] when `config` is not valid for this
1459    /// plugin, or [`SourceError::Auth`] when a named credential is absent.
1460    fn build(
1461        &self,
1462        name: &SourceName,
1463        config: &serde_json::Value,
1464        secrets: &dyn SecretResolver,
1465    ) -> Result<Box<dyn TaskSource>, SourceError>;
1466
1467    /// Build a live source from one configuration block, handing it the clock it paces and
1468    /// backs off on.
1469    ///
1470    /// The binary builds every in-process source through this, with the process's one
1471    /// [`SharedClock`] — [`system_clock`](crate::system_clock) unless a test asked for
1472    /// simulated time. Defaulted to [`build`](Self::build), which ignores the clock: a plugin
1473    /// that never waits needs no edit, and one that does overrides this and routes its waits
1474    /// through `clock`.
1475    ///
1476    /// # Errors
1477    ///
1478    /// As [`build`](Self::build).
1479    fn build_with_clock(
1480        &self,
1481        name: &SourceName,
1482        config: &serde_json::Value,
1483        secrets: &dyn SecretResolver,
1484        clock: SharedClock,
1485    ) -> Result<Box<dyn TaskSource>, SourceError> {
1486        let _ = clock;
1487        self.build(name, config, secrets)
1488    }
1489
1490    /// The fields of this plugin's `config:` block that name a filesystem path, as dotted
1491    /// paths into that block.
1492    ///
1493    /// A relative value at one of these, **supplied by a configuration document**, is
1494    /// resolved against the directory holding that document before [`Self::build`] sees it;
1495    /// supplied through the environment or a flag it keeps resolving against the process
1496    /// working directory, because there is no document to rebase it on. A plugin is handed
1497    /// values and no origins, so this declaration is the only way it can say which of its
1498    /// own fields that rule reaches.
1499    ///
1500    /// Defaulted to none, which is what keeps this an addition rather than a break: a
1501    /// plugin whose block holds no path needs no edit, and a caller asks every plugin
1502    /// rather than keeping a table of which ones answer.
1503    // llmlint: ignore[invalid_states_unrepresentable] The identity of a configuration field
1504    // is a name, and no type can make a wrong one unrepresentable here: every string is a
1505    // syntactically valid dotted path, so a newtype would validate nothing and would only
1506    // move where a name that is not a field of *this* plugin is accepted. What decides that
1507    // is whether the name is a property of the schema `config_schema` publishes — a
1508    // per-plugin fact no shared type can hold — so the gate is per plugin and executable:
1509    // `document_relative_fields_are_fields_this_plugin_declares` in
1510    // `onetaskgraph-local-md/tests/plugin.rs`, which a plugin adding a declaration owes its
1511    // own copy of.
1512    fn document_relative_paths(&self) -> &'static [&'static str] {
1513        &[]
1514    }
1515
1516    /// What names the remote store a source built from `config` reads — a board's owner and
1517    /// number, a Linear endpoint and team — or `None` for a source with no remote.
1518    ///
1519    /// The store's local cache of a remote source lives under a digest of this, so every
1520    /// process configuring the same remote shares one cache and no two remotes share one.
1521    /// Defaulted to `None`, which is what a source keeping its work on this machine — a
1522    /// folder of Markdown — answers: it has nothing to cache, and its cache setting is
1523    /// ignored. A `config` this plugin would refuse answers `None` too.
1524    fn remote_identity(&self, config: &serde_json::Value) -> Option<String> {
1525        let _ = config;
1526        None
1527    }
1528}
1529
1530/// How a plugin reads the credential its configuration names.
1531///
1532/// A configuration document never carries a credential value, only the name of
1533/// the environment variable holding it.
1534pub trait SecretResolver: Send + Sync {
1535    /// The value of `var`, or `None` when nothing defines it.
1536    ///
1537    /// The returned value is never logged and never appears in `Debug` output.
1538    fn get(&self, var: &str) -> Option<SecretString>;
1539}