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