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, Location, MetadataKey, MetadataRecord, Metering,
15    NativeId, NewComment, Page, PageRequest, Priority, Project, ProjectQuery,
16    ProjectVersionCoverage, SharedClock, SourceError, SourceName, Status, StatusCategory,
17    StatusContradiction, Task, TaskDetailRead, TaskQuery, TaskRef, TaskUpdate, TaskUpdateOutcome,
18    VersionCoverage, Visibility, WriteJournal, WriteSupport, WriteTarget, assetless, commentless,
19    documentless, unwritable, 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/// The task query whose [`TaskQuery::origin_matches`] is the one statement of what "copied
56/// from `origin`" means, so the by-origin defaults read a project's and a document's entry
57/// exactly as a task's is read.
58fn origin_query(origin: &str) -> TaskQuery {
59    TaskQuery {
60        origin: Some(origin.to_owned()),
61        ..TaskQuery::default()
62    }
63}
64
65/// Refuse a page of the listing a by-origin default walks that holds more rows than it was
66/// asked for, in the words the engine refuses one in: a source may return fewer and never
67/// more, and a default that narrowed such a page would hide the defect behind it.
68fn overran(returned: usize, asked_for: u32) -> Result<(), SourceError> {
69    if returned as u64 <= u64::from(asked_for) {
70        return Ok(());
71    }
72    Err(SourceError::Malformed {
73        message: format!(
74            "the source returned {returned} rows for a page of at most {asked_for}; a source \
75             may return fewer than it was asked for and never more"
76        ),
77    })
78}
79
80/// What a by-origin default answers when the listing it walks hands back a cursor it has
81/// already handed out, which would walk forever.
82fn repeated_cursor() -> SourceError {
83    SourceError::Malformed {
84        message: "the source returned a cursor it had already handed out while its listing \
85                  was walked for one origin, so the walk would never end"
86            .to_owned(),
87    }
88}
89
90/// The page `page` asks for of `matched`, every item a by-origin default kept: the cursor
91/// it hands out is the position of the next match, so a walk of its pages neither repeats
92/// nor drops one while the listing under it holds still.
93fn page_of_matches<T>(matched: Vec<T>, page: &PageRequest) -> Result<Page<T>, SourceError> {
94    let start = match &page.cursor {
95        None => 0,
96        Some(cursor) => cursor
97            .0
98            .strip_prefix(MATCHED_PAGE_CURSOR)
99            .and_then(|position| position.parse::<usize>().ok())
100            .filter(|position| *position <= matched.len())
101            .ok_or_else(|| SourceError::Refused {
102                message: format!(
103                    "cursor {:?} was not handed out by this by-origin listing; start the walk \
104                     again without one",
105                    cursor.0
106                ),
107            })?,
108    };
109    let end = start.saturating_add(page.limit as usize).min(matched.len());
110    let next = (end < matched.len()).then(|| crate::Cursor(format!("{MATCHED_PAGE_CURSOR}{end}")));
111    Ok(Page {
112        items: matched.into_iter().skip(start).take(end - start).collect(),
113        next,
114    })
115}
116
117const MATCHED_PAGE_CURSOR: &str = "origin:";
118
119/// One configured source, as the engine drives it.
120///
121/// Dyn-compatible through `async_trait` because the engine holds
122/// `Vec<Box<dyn TaskSource>>` over heterogeneous plugins.
123///
124/// Three rules bind every implementation, and the engine's compensation is only
125/// correct while all three hold:
126///
127/// 1. **Apply** every predicate you declare [`Support::Native`](crate::Support::Native).
128/// 2. **Ignore** every [`Support`](crate::Support)-typed predicate you declare
129///    `Unsupported` — return the *wider* result set, never a narrower one.
130///    Silently dropping rows for a predicate you did not declare is the one
131///    failure no test above the plugin can catch.
132/// 3. Never return a silently empty dependency read. Rule 2 reaches the
133///    `Support`-typed *predicates* alone; a dependency read is always real, and so is a
134///    document read — [`Capabilities::documents`] says whether this source has documents
135///    at all, and a source that says it has none is never asked for one rather than
136///    answering an empty page.
137#[async_trait::async_trait]
138pub trait TaskSource: Send + Sync {
139    /// The plugin kind that built this source, for display and for plan output.
140    fn kind(&self) -> &'static str;
141
142    /// What this source applies itself. Read once per query by the engine.
143    fn capabilities(&self) -> Capabilities;
144
145    /// How `a`, a [`Task::version`] this source gave one of its tasks, stands to `b`, another
146    /// it gave the same task: `Greater` when `a` is the later, `Less` when it is the earlier,
147    /// `Equal` when nothing the token covers changed between them, and `None` when the two
148    /// cannot be put in order — a value this source cannot read, or two versions its token
149    /// says differ without saying which came first.
150    ///
151    /// A token's format and its order are the one source's that spells it, so the engine asks
152    /// the source that gave both rather than reading inside either.
153    ///
154    /// Defaulted to equality alone: two identical tokens are one version, and any two others
155    /// are unordered, which a reader takes as *changed, read it again* and never as
156    /// unchanged. A source whose token says which of two versions is the later overrides it.
157    fn order_versions(&self, a: &str, b: &str) -> Option<Ordering> {
158        (a == b).then_some(Ordering::Equal)
159    }
160
161    /// Which parts of a task this source's [`Task::version`] vouches for, which is what the
162    /// store's local cache may serve a task's parts from.
163    ///
164    /// Defaulted to no part, which keeps the cache from ever serving what a token was never
165    /// promised to cover: a source overrides it only for the parts its token covers, as
166    /// `docs/plugin-protocol.md` §4.13d states them.
167    fn version_coverage(&self) -> VersionCoverage {
168        VersionCoverage::none(format!(
169            "the {} plugin does not declare that its change token covers a task",
170            self.kind()
171        ))
172    }
173
174    /// Which parts of a task a copy may take this source's unchanged [`Task::version`] as
175    /// vouching for, when it decides to skip a task its destination already holds as written:
176    /// the task's fields, its comments when the copy carries them, and its forward edges. A copy
177    /// skips only a task whose source covers every one of those it writes.
178    ///
179    /// Defaulted to [`version_coverage`](Self::version_coverage). A source overrides it only to
180    /// state, with its measured bound, a claim about a copy's skip that is not one the cache may
181    /// serve from — as `docs/plugin-protocol.md` §4.13d does for the one plugin that does.
182    fn copy_version_coverage(&self) -> VersionCoverage {
183        self.version_coverage()
184    }
185
186    /// Which parts of a project this source's [`Project::version`] vouches for, on the terms
187    /// of [`version_coverage`](Self::version_coverage).
188    ///
189    /// Defaulted to no part, for the same reason.
190    fn project_version_coverage(&self) -> ProjectVersionCoverage {
191        ProjectVersionCoverage::none(format!(
192            "the {} plugin does not declare that its change token covers a project",
193            self.kind()
194        ))
195    }
196
197    /// Which parts of a document this source's [`Document::version`] vouches for, on the terms
198    /// of [`version_coverage`](Self::version_coverage).
199    ///
200    /// Defaulted to no part, for the same reason.
201    fn document_version_coverage(&self) -> DocumentVersionCoverage {
202        DocumentVersionCoverage::none(format!(
203            "the {} plugin does not declare that its change token covers a document",
204            self.kind()
205        ))
206    }
207
208    /// Tell this source the store's local cache now stands in front of it.
209    ///
210    /// Called exactly once, by the cache as it wraps the source, before any read and before
211    /// any coverage is read — so a source whose token needs a part only a wider selection
212    /// carries can widen its reads here, and declare the coverage that widening buys. Never
213    /// carried over the plugin protocol, as [`version_coverage`](Self::version_coverage) is
214    /// not.
215    ///
216    /// Defaulted to doing nothing: a source not overriding it reads exactly as it did.
217    fn attach_cache(&self) {}
218
219    /// The change token the response that answered this source's last
220    /// [`Direction::DependsOn`] read of task `id` in this process spelled, or `None` when it
221    /// spelled none.
222    ///
223    /// What lets the store's cache keep a task's forward edges by the version they were read
224    /// at when nothing else in the command read the task: those edges are served only to a pin
225    /// that version is at or after, and never vouch for the task's own fields. Synchronous, and
226    /// never carried over the plugin protocol, as [`version_coverage`](Self::version_coverage)
227    /// is not.
228    ///
229    /// Defaulted to `None`: a source whose dependency read spells no token keeps its edges
230    /// remote unless a read of the task itself vouched for them.
231    fn forward_edges_version(&self, id: &NativeId) -> Option<String> {
232        let _ = id;
233        None
234    }
235
236    /// The change token the response that answered this source's last dependency read of the
237    /// `kind` item `id` in `direction`, from its first page, spelled — or `None` when it spelled
238    /// none — on the terms of [`forward_edges_version`](Self::forward_edges_version), which is
239    /// what it answers for a task's [`Direction::DependsOn`].
240    ///
241    /// What lets the store's cache keep a project's forward edges, and either kind's reverse
242    /// ones, by the version they were read at: a project's forward edges are served only where
243    /// [`project_version_coverage`](Self::project_version_coverage) covers them, reverse ones only
244    /// where [`reverse_edges_coverage`](Self::reverse_edges_coverage) covers that kind's, and each
245    /// only to a pin that version is at or after. Synchronous, and never
246    /// carried over the plugin protocol.
247    ///
248    /// Defaulted to [`forward_edges_version`](Self::forward_edges_version) for a task's forward
249    /// edges and to `None` for every other read, which keeps those remote.
250    fn edges_version(&self, kind: ItemKind, id: &NativeId, direction: Direction) -> Option<String> {
251        match (kind, direction) {
252            (ItemKind::Task, Direction::DependsOn) => self.forward_edges_version(id),
253            _ => None,
254        }
255    }
256
257    /// Whether this source's token for a `kind` item — [`Task::version`] or
258    /// [`Project::version`] — vouches for its reverse edges, what a [`Direction::DependedOnBy`]
259    /// read answers, so the store's cache may serve them.
260    ///
261    /// A reverse edge is recorded on another item, so a token vouches for one only where it
262    /// carries a part that moves whenever one is added to or removed from that other item —
263    /// which no part of an item's own fields does. Never carried over the plugin protocol.
264    ///
265    /// Defaulted to not covering them, with that reason.
266    fn reverse_edges_coverage(&self, kind: ItemKind) -> crate::Coverage {
267        crate::Coverage::Uncovered {
268            reason: format!(
269                "the {} plugin does not declare that its change token covers a {}'s reverse \
270                 edges, which are recorded on the items that depend on it",
271                self.kind(),
272                match kind {
273                    ItemKind::Task => "task",
274                    ItemKind::Project => "project",
275                }
276            ),
277        }
278    }
279
280    /// What this source holds about task `id` — the item it read last in this process — that
281    /// a later write expecting that version of it could take instead of reading it again, or
282    /// `None` when it holds nothing of the kind.
283    ///
284    /// Opaque to the engine, which keeps it beside the cached task and hands it back through
285    /// [`prime_write`](Self::prime_write). Defaulted to `None`: a source whose writes read
286    /// nothing first has nothing to keep.
287    fn write_context(&self, id: &NativeId) -> Option<serde_json::Value> {
288        let _ = id;
289        None
290    }
291
292    /// What this source holds about the container every task of it shares — a board's field
293    /// and option ids — that a write could take instead of reading it, or `None`.
294    ///
295    /// Defaulted to `None`, on the terms of [`write_context`](Self::write_context).
296    fn board_context(&self) -> Option<serde_json::Value> {
297        None
298    }
299
300    /// Hold `context`, which [`write_context`](Self::write_context) gave for task `id` at a
301    /// version the caller expects it still at, and `board`, which
302    /// [`board_context`](Self::board_context) gave, so the next write of `id` takes them
303    /// instead of reading — answering whether it took them.
304    ///
305    /// A context this source cannot read is not taken, and the write then reads as it always
306    /// does. Defaulted to taking nothing.
307    fn prime_write(
308        &self,
309        id: &NativeId,
310        context: &serde_json::Value,
311        board: Option<&serde_json::Value>,
312    ) -> bool {
313        let _ = (id, context, board);
314        false
315    }
316
317    /// Drop whatever [`prime_write`](Self::prime_write) took for `id`, and the board context
318    /// with it, so the next write of it reads afresh.
319    fn unprime(&self, id: &NativeId) {
320        let _ = id;
321    }
322
323    /// Start recording every request this source sends, for [`end_journal`](Self::end_journal).
324    ///
325    /// The engine opens one journal around one write at a time. Defaulted to recording
326    /// nothing.
327    fn begin_journal(&self) {}
328
329    /// Stop recording, answering with every request sent since
330    /// [`begin_journal`](Self::begin_journal) — or `None` for a source that records none.
331    fn end_journal(&self) -> Option<WriteJournal> {
332        None
333    }
334
335    /// Whether the source is answering right now.
336    ///
337    /// # Errors
338    ///
339    /// Returns a [`SourceError`] when the check itself could not be made.
340    async fn health(&self) -> Result<Health, SourceError>;
341
342    /// Fetch one task by its native id, or `None` when there is no such task.
343    ///
344    /// # Errors
345    ///
346    /// Returns a [`SourceError`] when the source could not answer.
347    async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError>;
348
349    /// Fetch several tasks by their native ids, each with the first page of its comments
350    /// when `comments` names the page to read — one answer per id, in the order they were
351    /// given.
352    ///
353    /// Each answer is what [`get_task`](Self::get_task) answers for that id, so a task that
354    /// is not there is `Ok(None)` and a read that failed fails that id alone. Its
355    /// [`TaskDetailRead::comments`] is what [`task_comments`](Self::task_comments) answers
356    /// for `comments`. The engine passes `comments` only to a source declaring
357    /// [`Capabilities::comments`](crate::Capabilities::comments) native.
358    ///
359    /// Defaulted to exactly those calls, item by item, so a source that implements nothing
360    /// here answers as it always did. A source that can read many items — or an item and its
361    /// comments — in fewer requests than that overrides it, which is the whole reason it
362    /// exists: a caller holding twenty ids pays for one batch rather than forty reads.
363    async fn get_task_details(
364        &self,
365        ids: &[NativeId],
366        comments: Option<&PageRequest>,
367    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
368        let mut read = Vec::with_capacity(ids.len());
369        for id in ids {
370            read.push(match self.get_task(id).await {
371                Ok(Some(task)) => {
372                    let comments = match comments {
373                        Some(page) => Some(self.task_comments(id, page).await),
374                        None => None,
375                    };
376                    Ok(Some(TaskDetailRead { task, comments }))
377                }
378                Ok(None) => Ok(None),
379                Err(error) => Err(error),
380            });
381        }
382        read
383    }
384
385    /// Fetch one project by its native id, or `None` when there is no such project.
386    ///
387    /// # Errors
388    ///
389    /// Returns a [`SourceError`] when the source could not answer.
390    async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError>;
391
392    /// One page of the tasks matching `query`.
393    ///
394    /// # Errors
395    ///
396    /// Returns a [`SourceError`] when the source could not answer.
397    async fn query_tasks(
398        &self,
399        query: &TaskQuery,
400        page: &PageRequest,
401    ) -> Result<Page<Task>, SourceError>;
402
403    /// One page of the projects matching `query`.
404    ///
405    /// # Errors
406    ///
407    /// Returns a [`SourceError`] when the source could not answer.
408    async fn query_projects(
409        &self,
410        query: &ProjectQuery,
411        page: &PageRequest,
412    ) -> Result<Page<Project>, SourceError>;
413
414    /// One page of the projects whose [`TaskQuery::ORIGIN_KEY`] entry is a string equal to
415    /// `origin`, exactly — the projects copied from that qualified id, and none other.
416    ///
417    /// `origin` is compared byte for byte, on the terms [`TaskQuery::origin`] states, and is
418    /// never constructed or interpreted here. Zero, one or several projects may match; which
419    /// of several a caller wants is the caller's question.
420    ///
421    /// Defaulted to [`query_projects`](Self::query_projects) unfiltered, walked to its end on
422    /// every call and narrowed here, so a source that implements nothing answers exactly what
423    /// its own listing holds; the default's cursor is a position among the matches. A source
424    /// that can ask its store for one origin overrides it, which is the whole reason it
425    /// exists: a caller looking for the copies of one plan pays for those copies rather than
426    /// for every project the store holds.
427    ///
428    /// # Errors
429    ///
430    /// Returns a [`SourceError`] when the source could not answer, and
431    /// [`SourceError::Refused`] for a cursor the default did not hand out.
432    async fn query_projects_by_origin(
433        &self,
434        origin: &str,
435        page: &PageRequest,
436    ) -> Result<Page<Project>, SourceError> {
437        let wanted = origin_query(origin);
438        let mut matched = Vec::new();
439        let mut cursor: Option<crate::Cursor> = None;
440        // Every cursor the listing handed out, so one cycling through several is caught as
441        // one repeating the last is.
442        let mut visited: Vec<String> = Vec::new();
443        loop {
444            let listed = self
445                .query_projects(
446                    &ProjectQuery::default(),
447                    &PageRequest {
448                        cursor: cursor.clone(),
449                        limit: page.limit,
450                    },
451                )
452                .await?;
453            overran(listed.items.len(), page.limit)?;
454            matched.extend(
455                listed
456                    .items
457                    .into_iter()
458                    .filter(|project| wanted.origin_matches(&project.metadata)),
459            );
460            cursor = match listed.next {
461                None => break,
462                Some(next) if visited.contains(&next.0) => return Err(repeated_cursor()),
463                Some(next) => {
464                    visited.push(next.0.clone());
465                    Some(next)
466                }
467            };
468        }
469        page_of_matches(matched, page)
470    }
471
472    /// One page of every label this source knows.
473    ///
474    /// # Errors
475    ///
476    /// Returns a [`SourceError`] when the source could not answer.
477    async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError>;
478
479    /// One page of the task dependency edges at `id`, in `direction`.
480    ///
481    /// # Errors
482    ///
483    /// Returns a [`SourceError`] when the source could not answer.
484    async fn task_dependencies(
485        &self,
486        id: &NativeId,
487        direction: Direction,
488        page: &PageRequest,
489    ) -> Result<Page<DependencyEdge>, SourceError>;
490
491    /// One page of the project dependency edges at `id`, in `direction`.
492    ///
493    /// # Errors
494    ///
495    /// Returns a [`SourceError`] when the source could not answer.
496    async fn project_dependencies(
497        &self,
498        id: &NativeId,
499        direction: Direction,
500        page: &PageRequest,
501    ) -> Result<Page<DependencyEdge>, SourceError>;
502
503    /// Whether this source can be written through at all.
504    ///
505    /// Defaulted to [`WriteSupport::Unsupported`], which is what keeps this a read
506    /// interface for every source that has nothing to write into: one that cannot be
507    /// written needs no edit and keeps working. Read before a write is attempted, so a
508    /// copy naming such a source as its destination is refused before anything is read.
509    fn writes(&self) -> WriteSupport {
510        WriteSupport::Unsupported
511    }
512
513    /// The content this source's backend stores when it is written `content`: the rewrite
514    /// the backend applies to the long-form text of a task, a project or a document on
515    /// write, declared rather than discovered.
516    ///
517    /// The engine applies it to the content before a copy, a create or a render sends it, so
518    /// what it sends is already what the backend keeps — and a rendering's `body_digest`, which
519    /// it records over that rewritten content where the provenance vouched for the content it
520    /// started from, is the digest of what a later read reports. A backend owes that applying
521    /// it to its own output changes nothing more. Defaulted to the identity: a backend that
522    /// stores what it is given declares nothing.
523    ///
524    /// Asynchronous and fallible because a source hosted over the stdio plugin protocol asks
525    /// the plugin that declares it; an in-process source answers at once and never fails.
526    ///
527    /// # Errors
528    ///
529    /// A [`SourceError`] when the source could not say what its backend stores — never the
530    /// identity in its place, which would record a digest of content the backend does not keep.
531    async fn stored_form(&self, content: &str) -> Result<String, SourceError> {
532        Ok(content.to_owned())
533    }
534
535    /// The status this source's backend holds once an item of `kind` is written at `status`:
536    /// the name it records for the category, where it names a category itself rather than
537    /// keeping the name it was given.
538    ///
539    /// What a copy compares a destination item's status with, beside
540    /// [`stored_form`](Self::stored_form), so an item whose category it already holds reads as
541    /// unchanged rather than as differing by a name no write could change. Defaulted to
542    /// `status` as given: a backend that keeps the name it is written declares nothing.
543    ///
544    /// # Errors
545    ///
546    /// A [`SourceError`] on the terms of [`stored_form`](Self::stored_form).
547    async fn stored_status(&self, kind: ItemKind, status: &Status) -> Result<Status, SourceError> {
548        let _ = kind;
549        Ok(status.clone())
550    }
551
552    /// The content the backend answered it now holds for the `record` `id`, as the response
553    /// to this instance's latest write of that item's content reported it — taken, so a second
554    /// call answers `None` until the next such write.
555    ///
556    /// What the engine compares, byte for byte, with the content it sent: a difference is a
557    /// rewrite [`stored_form`](Self::stored_form) does not declare. It is read off the write's
558    /// own response, never by a request of its own. Defaulted to `None`, which leaves the
559    /// engine nothing to compare and compares nothing.
560    fn stored_content(&self, record: MetadataRecord, id: &NativeId) -> Option<String> {
561        let _ = (record, id);
562        None
563    }
564
565    /// Create or update one task, answering with the native id the destination holds it
566    /// under.
567    ///
568    /// A source declaring [`WriteSupport::Supported`] owes three things here. It refuses,
569    /// naming the field, anything it cannot represent rather than dropping it — including
570    /// a metadata key it cannot carry, which it names. It writes every other field it was
571    /// given. And it never creates when [`ItemWrite::target`] names an item it does not
572    /// hold.
573    ///
574    /// # Errors
575    ///
576    /// Returns [`SourceError::Refused`] when this source has no write side, when a field
577    /// or a metadata key cannot be represented, or when `target` names nothing here; and
578    /// whatever else the source could not do the write for.
579    async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
580        let _ = write;
581        Err(unwritable(self.kind()))
582    }
583
584    /// Create or update one project, on exactly the terms of
585    /// [`write_task`](Self::write_task).
586    ///
587    /// # Errors
588    ///
589    /// As [`write_task`](Self::write_task).
590    async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
591        let _ = write;
592        Err(unwritable(self.kind()))
593    }
594
595    /// Whether this source can represent every field of `write` — its status, its content, the
596    /// tasks it delivers and every other field a [`write_task`](Self::write_task) of it would
597    /// refuse as "cannot represent the field …" — asked before anything is written and changing
598    /// nothing.
599    ///
600    /// A task copy asks it of every task it plans before its first write, and leaves out each
601    /// task this refuses — answered `failed`, with this refusal as its reason — writing the rest
602    /// as one copy. It answers what the write itself would refuse in the same words; and it is a
603    /// promise only about representability, so a write may still fail for any other reason.
604    ///
605    /// Defaulted to `Ok(())`: a source that does not answer it in advance still refuses such a
606    /// write in its write, which a copy then takes back whole, exactly as before.
607    ///
608    /// # Errors
609    ///
610    /// Returns [`SourceError::Refused`] naming the field this source cannot represent; and
611    /// whatever else kept it from finding out.
612    async fn check_task_write(&self, write: &ItemWrite<Task>) -> Result<(), SourceError> {
613        let _ = write;
614        Ok(())
615    }
616
617    /// Whether a write of an item of `kind` at `category` — over the item `target` names, or
618    /// creating one when it is `None` — would have a status to write, asked before the write
619    /// and changing nothing.
620    ///
621    /// A caller that has to put an item back when a later write of it fails — a copy, whose
622    /// journal records what an item held before overwriting it — asks this first, so a status
623    /// this source has no name for is refused while nothing has been recorded or written, and
624    /// nothing has to be put back. It answers what the write itself would refuse a status
625    /// with, in the same words, and sends no request a write of that status would not have
626    /// sent anyway: what it reads to answer, it holds for the write that follows.
627    ///
628    /// Defaulted to `Ok(())`: a source that does not answer it in advance still refuses the
629    /// status in its write, exactly as before.
630    ///
631    /// # Errors
632    ///
633    /// Returns [`SourceError::Refused`] naming the kind, the category and what is missing
634    /// when this source has no name for that status; and whatever else kept it from finding
635    /// out.
636    async fn check_status_write(
637        &self,
638        kind: ItemKind,
639        category: StatusCategory,
640        target: Option<&NativeId>,
641    ) -> Result<(), SourceError> {
642        let _ = (kind, category, target);
643        Ok(())
644    }
645
646    /// The status an item of `kind` reads back as once this source has written `status` for
647    /// it, asked without writing or reading anything.
648    ///
649    /// A source that keeps a status's name as it was given answers `status` itself. One that
650    /// writes a category to a name of its own — a board's `Status` option the category maps
651    /// to — answers that name, so a caller comparing what it would write with what the source
652    /// holds does not read a difference of spelling alone as a change: a copy then leaves an
653    /// item that already reads as the source does unwritten.
654    ///
655    /// Defaulted to `status` itself, which is what every source keeping names verbatim reads
656    /// back, and what a caller compared against before this was asked.
657    fn status_as_written(&self, kind: ItemKind, status: &Status) -> Status {
658        let _ = kind;
659        status.clone()
660    }
661
662    /// Set the status of one task this source holds, and change nothing else about it,
663    /// answering with the status as this source now reads it — or `None` when this source
664    /// holds no such task.
665    ///
666    /// The category lands where this source's own mapping sends it, exactly as a
667    /// [`write_task`](Self::write_task) of a task in that category would: a category this
668    /// source has disabled is refused in the words a write of it is refused with. Title,
669    /// content, labels, metadata, dependencies, [`Task::delivers`], [`Task::delivered_by`],
670    /// project and comments are left exactly as they are.
671    ///
672    /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
673    /// break: a source that cannot write a status on its own needs no edit and refuses by
674    /// saying so. A source declaring [`WriteSupport::Unsupported`] is never asked.
675    ///
676    /// [`Task::delivers`]: crate::Task::delivers
677    /// [`Task::delivered_by`]: crate::Task::delivered_by
678    ///
679    /// # Errors
680    ///
681    /// Returns [`SourceError::Refused`] when this source cannot write a status, or cannot
682    /// write this one; and whatever else the source could not do the write for.
683    async fn set_task_status(
684        &self,
685        id: &NativeId,
686        category: StatusCategory,
687    ) -> Result<Option<Status>, SourceError> {
688        let _ = (id, category);
689        Err(unwritable_field(self.kind(), "status"))
690    }
691
692    /// Set the status of one project this source holds, and change nothing else about it,
693    /// answering with the status as this source now reads it — or `None` when this source
694    /// holds no such project.
695    ///
696    /// The category lands where this source's own mapping sends it for a project, exactly as a
697    /// [`write_project`](Self::write_project) of a project in that category would: a category
698    /// this source has disabled is refused in the words a write of it is refused with. Title,
699    /// content, labels, metadata, repositories, dependencies and the project's tasks are left
700    /// exactly as they are. A project delivers no task, so nothing is kept in step after it.
701    ///
702    /// Defaulted to the refusal [`set_task_status`](Self::set_task_status) defaults to,
703    /// [`unwritable_field`] naming `status`, which is what keeps this an addition rather than a
704    /// break: a source that does not implement it needs no edit. A source declaring
705    /// [`WriteSupport::Unsupported`] is never asked.
706    ///
707    /// # Errors
708    ///
709    /// Returns [`SourceError::Refused`] when this source cannot write a project's status, or
710    /// cannot write this one; and whatever else the source could not do the write for.
711    async fn set_project_status(
712        &self,
713        id: &NativeId,
714        category: StatusCategory,
715    ) -> Result<Option<Status>, SourceError> {
716        let _ = (id, category);
717        Err(unwritable_field(self.kind(), "status"))
718    }
719
720    /// Set the status of one task this source holds, as [`set_task_status`](Self::set_task_status)
721    /// does, and answer with the whole task as this source now reads it — its
722    /// [`Task::delivers`] among what a caller keeping delivered tasks in step needs — or `None`
723    /// when this source holds no such task.
724    ///
725    /// Defaulted to exactly the two calls a caller would otherwise make: [`get_task`] first,
726    /// answering `None` with nothing written when it does, then `set_task_status`, the status
727    /// it answers put on the task read. A source whose status write answers the whole task in
728    /// the same round trip overrides it to save the read.
729    ///
730    /// [`Task::delivers`]: crate::Task::delivers
731    /// [`get_task`]: Self::get_task
732    ///
733    /// # Errors
734    ///
735    /// As [`get_task`](Self::get_task) and [`set_task_status`](Self::set_task_status).
736    async fn set_task_status_reading(
737        &self,
738        id: &NativeId,
739        category: StatusCategory,
740    ) -> Result<Option<Task>, SourceError> {
741        let Some(mut task) = self.get_task(id).await? else {
742            return Ok(None);
743        };
744        let Some(status) = self.set_task_status(id, category).await? else {
745            return Ok(None);
746        };
747        task.status = status;
748        Ok(Some(task))
749    }
750
751    /// Every task this source holds whose card contradicts its issue's closure, each with the
752    /// status that brings it in line — what `task status reconcile` writes, through
753    /// [`set_task_status`](Self::set_task_status), one task at a time.
754    ///
755    /// A task needs it when its issue is closed with a reason that reads `done` or
756    /// `cancelled` and its card does not sit at the option this source's mapping gives that
757    /// category. An open task, a closure that reads `unknown` and a card already in line are
758    /// never answered. Changes nothing.
759    ///
760    /// Asked only of a source declaring
761    /// [`Capabilities::reconcile_status`](crate::Capabilities::reconcile_status); defaulted to a
762    /// refusal saying so, which no caller holding to that declaration ever receives.
763    ///
764    /// # Errors
765    ///
766    /// Returns [`SourceError::Refused`] when this source answers no such question; and whatever
767    /// kept it from reading its items.
768    async fn status_contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
769        Err(SourceError::Refused {
770            message: format!(
771                "a {} source's status is its closure, so nothing needs reconciling",
772                self.kind()
773            ),
774        })
775    }
776
777    /// For each issue in `issues`, in order and once each, the task this source holds for it
778    /// and what moving it to `done` comes to — what `task status complete` writes, through
779    /// [`set_task_status`](Self::set_task_status), for each one answered
780    /// [`Completion::Due`](crate::Completion::Due).
781    ///
782    /// The read is proportional to `issues` and never to the size of what this source holds,
783    /// and an empty `issues` reads nothing. Changes nothing.
784    ///
785    /// Asked only of a source declaring
786    /// [`Capabilities::complete_by_issue`](crate::Capabilities::complete_by_issue); defaulted
787    /// to a refusal saying so, which no caller holding to that declaration ever receives.
788    ///
789    /// # Errors
790    ///
791    /// Returns [`SourceError::Refused`] when this source answers no such question; and whatever
792    /// kept it from reading the issues.
793    async fn issue_holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
794        let _ = issues;
795        Err(SourceError::Refused {
796            message: format!("a {} source holds no items by issue reference", self.kind()),
797        })
798    }
799
800    /// Set the priority of one task this source holds, and change nothing else about it,
801    /// answering with the priority as this source now reads it — or `None` when this source
802    /// holds no such task.
803    ///
804    /// [`Priority::None`] clears the priority. Title, content, status, labels, metadata,
805    /// repositories, dependencies and comments are left exactly as they are. Nothing about
806    /// the task's status moves, so the engine re-evaluates no delivered task after it.
807    ///
808    /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
809    /// break. A source declaring [`WriteSupport::Unsupported`], or declaring
810    /// [`Capabilities::priority`] unsupported, is never asked.
811    ///
812    /// # Errors
813    ///
814    /// Returns [`SourceError::Refused`] when this source cannot write a priority, or cannot
815    /// write this one — a board with no option for it, naming the option; and whatever else
816    /// the source could not do the write for.
817    async fn set_task_priority(
818        &self,
819        id: &NativeId,
820        priority: Priority,
821    ) -> Result<Option<Priority>, SourceError> {
822        let _ = (id, priority);
823        Err(unwritable_field(self.kind(), "priority"))
824    }
825
826    /// Replace the content of one task this source holds with `content`, byte for byte, and
827    /// change nothing else about it — or answer `None` when this source holds no such task.
828    ///
829    /// The content is [`Task::content`] exactly as this source reports it: what a later read
830    /// answers there is `content`. Where the source keeps something else inside the same
831    /// backend field — a metadata block in an issue body — that is kept as it was, and so is
832    /// every other member: title, status, priority, labels, metadata, repositories,
833    /// dependencies, project and comments. Nothing about the task's status moves, so the
834    /// engine re-evaluates no delivered task after it.
835    ///
836    /// Defaulted to [`unwritable_field`] on exactly the terms of
837    /// [`set_task_status`](Self::set_task_status). A source declaring
838    /// [`WriteSupport::Unsupported`] is never asked.
839    ///
840    /// # Errors
841    ///
842    /// Returns [`SourceError::Refused`] when this source cannot write a task's content on its
843    /// own, or cannot represent this one; and whatever else the source could not do the write
844    /// for.
845    async fn set_task_content(
846        &self,
847        id: &NativeId,
848        content: &str,
849    ) -> Result<Option<()>, SourceError> {
850        let _ = (id, content);
851        Err(unwritable_field(self.kind(), "content"))
852    }
853
854    /// Replace the [`Task::delivered_by`] of one task this source holds, and change nothing
855    /// else about it — or answer `None` when this source holds no such task.
856    ///
857    /// Every entry is a qualified id, and the list is the whole of it: what the task held
858    /// there before is replaced, not merged. It is the store's to keep in step — the engine
859    /// calls this whenever it writes a task's [`Task::delivers`] — and nothing a person types
860    /// reaches it directly.
861    ///
862    /// Defaulted to [`unwritable_field`] on exactly the terms of
863    /// [`set_task_status`](Self::set_task_status).
864    ///
865    /// [`Task::delivers`]: crate::Task::delivers
866    /// [`Task::delivered_by`]: crate::Task::delivered_by
867    ///
868    /// # Errors
869    ///
870    /// Returns [`SourceError::Refused`] when this source cannot hold the list, and whatever
871    /// else it could not do the write for.
872    async fn set_delivered_by(
873        &self,
874        id: &NativeId,
875        delivered_by: &[TaskRef],
876    ) -> Result<Option<()>, SourceError> {
877        let _ = (id, delivered_by);
878        Err(unwritable_field(self.kind(), "delivered_by"))
879    }
880
881    /// Set one key of the metadata of one task this source holds, and change nothing else
882    /// about it, answering with the task as this source reads it back after the write — or
883    /// `None` when this source holds no such task.
884    ///
885    /// The key is added when the task does not hold it and replaced when it does; every other
886    /// metadata key, and every other field of the task, is left exactly as it was. A `value`
887    /// the task already holds under `key` is a write that changes nothing, and a source owes
888    /// it no write at all. The answer is a read, not an echo: what the engine reports as the
889    /// value is what the returned task holds under `key`.
890    ///
891    /// Nothing about the task's status or its [`Task::delivers`] moves, so the engine
892    /// re-evaluates no delivered task after this write.
893    ///
894    /// Defaulted to [`unwritable_metadata`] on exactly the terms of
895    /// [`set_task_status`](Self::set_task_status): a source that cannot write one key on its
896    /// own needs no edit and refuses by saying so. A source declaring
897    /// [`WriteSupport::Unsupported`] is never asked.
898    ///
899    /// [`Task::delivers`]: crate::Task::delivers
900    ///
901    /// # Errors
902    ///
903    /// Returns [`SourceError::Refused`] when this source cannot write one key of a task's
904    /// metadata on its own, or cannot write this one without changing something else; and
905    /// whatever else the source could not do the write for.
906    async fn set_task_metadata(
907        &self,
908        id: &NativeId,
909        key: &MetadataKey,
910        value: &Value,
911    ) -> Result<Option<Task>, SourceError> {
912        let _ = (id, key, value);
913        Err(unwritable_metadata(self.kind(), MetadataRecord::Task))
914    }
915
916    /// Apply a targeted update to one task this source holds — every field `update` names, and
917    /// nothing else — answering with a [`TaskUpdateOutcome`], or `None` when this source holds
918    /// no such task.
919    ///
920    /// The outcome is everything the engine reports about the call, so it reads nothing of its
921    /// own: the task as this source reads it once the update landed — from the one read it made
922    /// and what it then wrote, where its backend answers a write with what it holds — the
923    /// fields it actually wrote, and the `delivers` the task held before.
924    ///
925    /// A field already holding the requested value is sent no write, and an update in which
926    /// nothing differs sends no write at all. Every field `update` leaves unnamed — labels,
927    /// repositories, project, [`Task::delivered_by`] and comments always among them — is left
928    /// exactly as it is. An update naming one metadata key both to set and to remove is refused
929    /// before anything is written, in the words of [`TaskUpdate::consistent`].
930    ///
931    /// Defaulted to [`TaskUpdate::rewrite`]: read the task, apply the update, and — only when
932    /// anything differs — [`write_task`](Self::write_task) it with its `target` set. That keeps
933    /// this an addition rather than a break, and a source that predates it behaves correctly and
934    /// is merely not minimal; one whose backend can take a field on its own owes an override
935    /// that sends only what differs. A source declaring [`WriteSupport::Unsupported`] is never
936    /// asked.
937    ///
938    /// [`Task::delivered_by`]: crate::Task::delivered_by
939    ///
940    /// # Errors
941    ///
942    /// Returns [`SourceError::Refused`] when the update contradicts itself, when a field it
943    /// names cannot be represented here — a category this source has disabled included — and
944    /// whatever else the source could not do the write for.
945    async fn update_task(
946        &self,
947        id: &NativeId,
948        update: &TaskUpdate,
949    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
950        update.rewrite(self, id).await
951    }
952
953    /// Set one key of the metadata of one project this source holds, on exactly the terms of
954    /// [`set_task_metadata`](Self::set_task_metadata).
955    ///
956    /// # Errors
957    ///
958    /// As [`set_task_metadata`](Self::set_task_metadata).
959    async fn set_project_metadata(
960        &self,
961        id: &NativeId,
962        key: &MetadataKey,
963        value: &Value,
964    ) -> Result<Option<Project>, SourceError> {
965        let _ = (id, key, value);
966        Err(unwritable_metadata(self.kind(), MetadataRecord::Project))
967    }
968
969    /// Set one key of the metadata of one document this source holds, on exactly the terms of
970    /// [`set_task_metadata`](Self::set_task_metadata).
971    ///
972    /// A source declaring [`Capabilities::documents`] unsupported is never asked, exactly as
973    /// it is never asked for a document read.
974    ///
975    /// # Errors
976    ///
977    /// As [`set_task_metadata`](Self::set_task_metadata).
978    async fn set_document_metadata(
979        &self,
980        id: &NativeId,
981        key: &MetadataKey,
982        value: &Value,
983    ) -> Result<Option<Document>, SourceError> {
984        let _ = (id, key, value);
985        Err(unwritable_metadata(self.kind(), MetadataRecord::Document))
986    }
987
988    /// Remove one task this destination holds, so a copy that could not finish can put
989    /// the destination back the way it found it.
990    ///
991    /// This is not a verb of the product: nothing a user types deletes anything, and a
992    /// copy never deletes an item it did not itself create in the run that is failing.
993    /// It exists because a copy is either complete or it never happened — a half-written
994    /// project has to be run again, and the re-run is the mutation burst that trips a
995    /// hosted destination's rate limiter. Undoing this run's own creates is what removes
996    /// that retry at source.
997    ///
998    /// A source declaring [`WriteSupport::Supported`] owes a real implementation, for the
999    /// reason it owes [`write_task`](Self::write_task) one: the engine will create items
1000    /// there, so it has to be able to remove the ones it created. An `id` naming nothing
1001    /// is **not** an error — the item is already gone, which is the state this asks for.
1002    ///
1003    /// # Errors
1004    ///
1005    /// Returns [`SourceError::Refused`] when this source has no write side, and whatever
1006    /// else the source could not remove the item for.
1007    async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
1008        let _ = id;
1009        Err(unwritable(self.kind()))
1010    }
1011
1012    /// Remove one project this destination holds, on exactly the terms of
1013    /// [`delete_task`](Self::delete_task).
1014    ///
1015    /// # Errors
1016    ///
1017    /// As [`delete_task`](Self::delete_task).
1018    async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
1019        let _ = id;
1020        Err(unwritable(self.kind()))
1021    }
1022
1023    /// Fetch one document by its native id, or `None` when there is no such document.
1024    ///
1025    /// Defaulted to [`documentless`], which is what keeps documents an addition rather
1026    /// than a break: a source with none needs no edit, keeps working, and says so in the
1027    /// same words every other document-free source does. A source that has documents
1028    /// declares [`Support::Native`](crate::Support::Native) for
1029    /// [`Capabilities::documents`] and owes a real implementation here, because that
1030    /// declaration is what makes the engine ask.
1031    ///
1032    /// # Errors
1033    ///
1034    /// Returns [`SourceError::Refused`] when this source has no documents, and whatever
1035    /// else the source could not answer for.
1036    async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
1037        let _ = id;
1038        Err(documentless(self.kind()))
1039    }
1040
1041    /// One page of the documents matching `query`.
1042    ///
1043    /// Defaulted on exactly the terms of [`get_document`](Self::get_document). A source
1044    /// with no documents refuses rather than answering an empty page: an empty page reads
1045    /// as a source that has documents and holds none matching, which is the one wrong
1046    /// answer this method can give.
1047    ///
1048    /// # Errors
1049    ///
1050    /// As [`get_document`](Self::get_document).
1051    async fn query_documents(
1052        &self,
1053        query: &DocumentQuery,
1054        page: &PageRequest,
1055    ) -> Result<Page<Document>, SourceError> {
1056        let _ = (query, page);
1057        Err(documentless(self.kind()))
1058    }
1059
1060    /// One page of the documents whose [`TaskQuery::ORIGIN_KEY`] entry is a string equal to
1061    /// `origin`, exactly, on the terms of
1062    /// [`query_projects_by_origin`](Self::query_projects_by_origin).
1063    ///
1064    /// Defaulted to [`query_documents`](Self::query_documents) unfiltered, walked and narrowed
1065    /// as that default is — so a source with no documents refuses exactly as its
1066    /// `query_documents` does.
1067    ///
1068    /// # Errors
1069    ///
1070    /// As [`query_documents`](Self::query_documents), and [`SourceError::Refused`] for a
1071    /// cursor the default did not hand out.
1072    async fn query_documents_by_origin(
1073        &self,
1074        origin: &str,
1075        page: &PageRequest,
1076    ) -> Result<Page<Document>, SourceError> {
1077        let wanted = origin_query(origin);
1078        let mut matched = Vec::new();
1079        let mut cursor: Option<crate::Cursor> = None;
1080        // Every cursor the listing handed out, so one cycling through several is caught as
1081        // one repeating the last is.
1082        let mut visited: Vec<String> = Vec::new();
1083        loop {
1084            let listed = self
1085                .query_documents(
1086                    &DocumentQuery::default(),
1087                    &PageRequest {
1088                        cursor: cursor.clone(),
1089                        limit: page.limit,
1090                    },
1091                )
1092                .await?;
1093            overran(listed.items.len(), page.limit)?;
1094            matched.extend(
1095                listed
1096                    .items
1097                    .into_iter()
1098                    .filter(|document| wanted.origin_matches(&document.metadata)),
1099            );
1100            cursor = match listed.next {
1101                None => break,
1102                Some(next) if visited.contains(&next.0) => return Err(repeated_cursor()),
1103                Some(next) => {
1104                    visited.push(next.0.clone());
1105                    Some(next)
1106                }
1107            };
1108        }
1109        page_of_matches(matched, page)
1110    }
1111
1112    /// Create or update one document, on exactly the terms of
1113    /// [`write_task`](Self::write_task).
1114    ///
1115    /// # Errors
1116    ///
1117    /// As [`write_task`](Self::write_task).
1118    async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
1119        let _ = write;
1120        Err(unwritable(self.kind()))
1121    }
1122
1123    /// Remove one document this destination holds, on exactly the terms of
1124    /// [`delete_task`](Self::delete_task).
1125    ///
1126    /// # Errors
1127    ///
1128    /// As [`delete_task`](Self::delete_task).
1129    async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
1130        let _ = id;
1131        Err(unwritable(self.kind()))
1132    }
1133
1134    /// One page of the comments on `task`, oldest first, or `None` when this source holds
1135    /// no such task.
1136    ///
1137    /// Defaulted to [`commentless`], which is what keeps comments an addition rather than a
1138    /// break: a source with none needs no edit and keeps working. A source whose tasks have
1139    /// comments declares [`Support::Native`](crate::Support::Native) for
1140    /// [`Capabilities::comments`] and owes a real implementation of all four comment methods,
1141    /// because that declaration is what makes the engine ask.
1142    ///
1143    /// "No such task" is `None` rather than an error, exactly as it is for
1144    /// [`get_task`](Self::get_task); a task that exists and has no comments is an empty page.
1145    ///
1146    /// # Errors
1147    ///
1148    /// Returns [`SourceError::Refused`] when this source has no comments, and whatever else
1149    /// the source could not answer for.
1150    async fn task_comments(
1151        &self,
1152        task: &NativeId,
1153        page: &PageRequest,
1154    ) -> Result<Option<Page<Comment>>, SourceError> {
1155        let _ = (task, page);
1156        Err(commentless(self.kind()))
1157    }
1158
1159    /// [`get_task_details`](Self::get_task_details) as a copy reads the tasks it carries: each
1160    /// with the first page of its comments `comments` names — and, where the same request can
1161    /// carry them, what this source needs to answer [`task_dependencies`](Self::task_dependencies)
1162    /// for it without another, since a copy reads every task's edges next.
1163    ///
1164    /// Defaulted to `get_task_details(ids, Some(comments))`, which is exactly what it answers.
1165    /// A source whose detail read is priced by what it selects overrides it with a read that
1166    /// also carries the edges, so a copy of a changed task costs its detail read and nothing
1167    /// more; one whose reads are free has no reason to.
1168    async fn get_task_details_for_copy(
1169        &self,
1170        ids: &[NativeId],
1171        comments: &PageRequest,
1172    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
1173        self.get_task_details(ids, Some(comments)).await
1174    }
1175
1176    /// Read the items `ids` names — tasks, projects and documents alike, whatever kind each
1177    /// is — together, as a copy reads the counterparts it is about to write, and hold each for
1178    /// this command so that the next [`get_task`](Self::get_task),
1179    /// [`get_project`](Self::get_project) or [`get_document`](Self::get_document) of it is
1180    /// answered from that read, once, instead of being sent on its own.
1181    ///
1182    /// What is held is exactly what that read by id would have answered — the item's fields,
1183    /// its edges, its asset manifest and its change token — and only until the next read of
1184    /// it, a write naming it, or [`end_command`](Self::end_command), whichever comes first, so
1185    /// a read answered from it is never staler than the read-before-write it stands in for.
1186    ///
1187    /// Defaulted to doing nothing, so every read is sent as it always was: a source whose
1188    /// reads are free has no reason to override it, and one priced per request overrides it
1189    /// with a batched read. An id the batched read finds nothing at is either held as absent —
1190    /// its next read answers `None`, exactly as that read would have — or not held, and its own
1191    /// read answers as it always does.
1192    ///
1193    /// # Errors
1194    ///
1195    /// Returns a [`SourceError`] when the batched read could not be made. Nothing is then
1196    /// held, and each item's own read answers as it would have.
1197    async fn read_ahead_for_copy(&self, ids: &[NativeId]) -> Result<(), SourceError> {
1198        let _ = ids;
1199        Ok(())
1200    }
1201
1202    /// Ask, together, which items were copied from each of `origins` — the qualified ids a copy
1203    /// is about to look for at this destination by the `onetaskgraph.origin` each item records
1204    /// — and hold each answer
1205    /// for this command, so that the next query for the items copied from one of them (a
1206    /// [`TaskQuery::origin`] task query, [`query_projects_by_origin`](Self::query_projects_by_origin)
1207    /// or [`query_documents_by_origin`](Self::query_documents_by_origin)) is answered from it,
1208    /// once, instead of being sent on its own. A source may carry in the same read whatever its
1209    /// creating an item would read first, since a copy finding nothing creates.
1210    ///
1211    /// What is held is exactly what those queries would have answered, and only until the next
1212    /// write or [`end_command`](Self::end_command). Defaulted to doing nothing, so each query is
1213    /// sent as it always was.
1214    ///
1215    /// # Errors
1216    ///
1217    /// Returns a [`SourceError`] when the read could not be made. Nothing is then held, and each
1218    /// query answers as it would have.
1219    async fn read_ahead_origins_for_copy(&self, origins: &[String]) -> Result<(), SourceError> {
1220        let _ = origins;
1221        Ok(())
1222    }
1223
1224    /// How many tasks this source creates in one [`write_tasks`](Self::write_tasks): more than
1225    /// one only for a source that creates several in one request.
1226    ///
1227    /// A copy hands such a source the tasks it creates together, and names each one's edges to
1228    /// the others in a write after they all exist. Defaulted to one, which has a copy write every
1229    /// task on its own, exactly as before.
1230    fn create_batch_limit(&self) -> usize {
1231        1
1232    }
1233
1234    /// Create every task of `writes` — each [`ItemWrite::target`] `None` — answering with the
1235    /// native ids they were created under, in order.
1236    ///
1237    /// All of them or none: a source that cannot create every one takes back each it did create
1238    /// before refusing, on the terms §4.9 of the protocol puts on [`write_task`](Self::write_task).
1239    /// Defaulted to creating them one at a time through [`write_task`](Self::write_task), taking
1240    /// back those created when a later one is refused.
1241    ///
1242    /// # Errors
1243    ///
1244    /// Refused, before anything is written, when a write names an existing target; otherwise
1245    /// whatever [`write_task`](Self::write_task) of one of them refuses with.
1246    // llmlint: ignore[invalid_states_unrepresentable] Approved by the contract's owner as an additive method taking `ItemWrite<Task>` exactly as `write_task` does; a create-only input type would be a new contract type. A write naming an existing target is refused below before anything is written, so rollback only ever takes back what this call created.
1247    async fn write_tasks(&self, writes: &[ItemWrite<Task>]) -> Result<Vec<NativeId>, SourceError> {
1248        if let Some(write) = writes.iter().find(|write| write.target.is_some()) {
1249            return Err(SourceError::Refused {
1250                message: format!(
1251                    "write_tasks creates tasks, and the write of {} names an existing target; \
1252                     next: update it with write_task",
1253                    write.item.id
1254                ),
1255            });
1256        }
1257        let mut created = Vec::with_capacity(writes.len());
1258        for write in writes {
1259            match self.write_task(write).await {
1260                Ok(id) => created.push(id),
1261                Err(error) => {
1262                    // The caller is never handed these ids, so one this source will not take
1263                    // back is named here or by nobody.
1264                    let mut left: Vec<&str> = Vec::new();
1265                    for id in &created {
1266                        if self.delete_task(id).await.is_err() {
1267                            left.push(id.0.as_str());
1268                        }
1269                    }
1270                    if left.is_empty() {
1271                        return Err(error);
1272                    }
1273                    return Err(SourceError::Refused {
1274                        message: format!(
1275                            "{error}; this source then refused to take back {}, which this \
1276                             write created and which it still holds; next: delete {} before \
1277                             writing again",
1278                            left.join(", "),
1279                            if left.len() == 1 { "it" } else { "them" }
1280                        ),
1281                    });
1282                }
1283            }
1284        }
1285        Ok(created)
1286    }
1287
1288    /// From here until [`finish_writes`](Self::finish_writes), a source may hold back the part of
1289    /// each write that can land later — a created item's fields and edges — and send it together
1290    /// with the others' when that is called.
1291    ///
1292    /// A caller asks for this only when it will call `finish_writes` before it reads what it
1293    /// wrote from anywhere but this source, or reports it written. Defaulted to holding nothing
1294    /// back, so every write lands whole as it is made.
1295    fn begin_deferred_writes(&self) {}
1296
1297    /// Send whatever this source has held back since [`begin_deferred_writes`](Self::begin_deferred_writes),
1298    /// and hold nothing back after it.
1299    ///
1300    /// All or nothing for the items it created: a source that cannot finish them takes them back
1301    /// before refusing, so a caller undoing its writes finds them gone. Defaulted to doing
1302    /// nothing, since nothing was held.
1303    ///
1304    /// # Errors
1305    ///
1306    /// Whatever sending what was held back was refused with.
1307    async fn finish_writes(&self) -> Result<(), SourceError> {
1308        Ok(())
1309    }
1310
1311    /// Where an item this source wrote in the current command is, when the write's own answer
1312    /// said so: `record` names which kind of item `id` is.
1313    ///
1314    /// Answered only from what a write already returned — never by a request — so a caller may
1315    /// ask it after every write for free. A caller treats `None` as not knowing, and reads the
1316    /// item when it needs its location. Defaulted to `None`.
1317    fn written_location(&self, record: MetadataRecord, id: &NativeId) -> Option<Location> {
1318        let _ = (record, id);
1319        None
1320    }
1321
1322    /// Add one comment to `task`, answering with the comment as the source now holds it, or
1323    /// `None` when this source holds no such task.
1324    ///
1325    /// The body is stored byte for byte. A source that records the author itself refuses a
1326    /// [`NewComment::author`] rather than dropping it, naming why; a source that cannot
1327    /// represent the body refuses it, naming why, rather than escaping it into something
1328    /// else.
1329    ///
1330    /// # Errors
1331    ///
1332    /// Returns [`SourceError::Refused`] when this source has no comments or cannot be
1333    /// written, when it cannot record what it was given, and whatever else it could not do
1334    /// the write for.
1335    async fn add_comment(
1336        &self,
1337        task: &NativeId,
1338        comment: &NewComment,
1339    ) -> Result<Option<Comment>, SourceError> {
1340        let _ = (task, comment);
1341        Err(commentless(self.kind()))
1342    }
1343
1344    /// Replace the body of the comment `comment` on `task`, answering with the comment as the
1345    /// source now holds it, or `None` when this source holds no such task or that task has no
1346    /// such comment.
1347    ///
1348    /// Only the body and the time it last changed move: the id, the author and the time it
1349    /// was written are the comment's own.
1350    ///
1351    /// # Errors
1352    ///
1353    /// As [`add_comment`](Self::add_comment).
1354    async fn edit_comment(
1355        &self,
1356        task: &NativeId,
1357        comment: &NativeId,
1358        body: &CommentBody,
1359    ) -> Result<Option<Comment>, SourceError> {
1360        let _ = (task, comment, body);
1361        Err(commentless(self.kind()))
1362    }
1363
1364    /// Remove the comment `comment` from `task`, answering with the id it removed, or `None`
1365    /// when this source holds no such task or that task has no such comment.
1366    ///
1367    /// Unlike [`delete_task`](Self::delete_task), this *is* a verb of the product — a person
1368    /// removes a comment they posted — so a comment that is not there is reported as `None`
1369    /// for the engine to refuse by name, rather than treated as already gone.
1370    ///
1371    /// # Errors
1372    ///
1373    /// As [`add_comment`](Self::add_comment).
1374    async fn delete_comment(
1375        &self,
1376        task: &NativeId,
1377        comment: &NativeId,
1378    ) -> Result<Option<NativeId>, SourceError> {
1379        let _ = (task, comment);
1380        Err(commentless(self.kind()))
1381    }
1382
1383    /// Write one comment a copy carries onto `task`: a new one when `existing` is `None`, and
1384    /// otherwise the comment `existing`, which a copy wrote before, made to say `copy` — or
1385    /// `None` when this source holds no such task or no such comment.
1386    ///
1387    /// The answer reports [`Comment::origin`] as `copy.origin`, however the source keeps it.
1388    ///
1389    /// **Defaulted to the hidden marker**, which is right for every source that records a
1390    /// comment's author and times itself: the body is written through
1391    /// [`add_comment`](Self::add_comment) or [`edit_comment`](Self::edit_comment) with
1392    /// [`CommentOrigin::mark`](crate::CommentOrigin::mark) appended, and read back
1393    /// [`unmarked`](Comment::unmarked). A source that can store the origin natively — and so
1394    /// takes the origin's own id, author and times for the copy — overrides this.
1395    ///
1396    /// # Errors
1397    ///
1398    /// As [`add_comment`](Self::add_comment).
1399    async fn write_comment_copy(
1400        &self,
1401        task: &NativeId,
1402        existing: Option<&NativeId>,
1403        copy: &CommentCopy,
1404    ) -> Result<Option<Comment>, SourceError> {
1405        let body = CommentBody::new(copy.origin.qualified()?.mark(copy.body.as_str()))?;
1406        let written = match existing {
1407            Some(comment) => self.edit_comment(task, comment, &body).await?,
1408            None => {
1409                self.add_comment(task, &NewComment { body, author: None })
1410                    .await?
1411            }
1412        };
1413        Ok(written.map(Comment::unmarked))
1414    }
1415
1416    /// Whether this source keeps template answers beside its items at all.
1417    ///
1418    /// What lets a regenerate tell an item whose answers went missing — a block deleted by
1419    /// hand, which the regenerate writes back — from an item of a source that never keeps any,
1420    /// where a missing answer is no difference. Defaulted to `false`, as
1421    /// [`task_template_answers`](Self::task_template_answers) is defaulted to `None`; a source
1422    /// that keeps answers answers `true` here.
1423    fn keeps_template_answers(&self) -> bool {
1424        false
1425    }
1426
1427    /// The template answers the task `id` was last rendered from, as this source keeps them
1428    /// beside the task — or `None` when it keeps none for it, or holds no such task.
1429    ///
1430    /// Keeping answers is a source's own choice, never an obligation: a source whose items
1431    /// are one record in a hosted system has no room beside the item that is not the item, and
1432    /// answers written into its content or its metadata would duplicate what the content
1433    /// already says. Defaulted to `None`, which is what keeps this an addition rather than a
1434    /// break. A source that keeps them owes three things: they are in neither
1435    /// [`Task::content`] nor [`Task::metadata`], they are written only by
1436    /// [`write_task_rendered`](Self::write_task_rendered) and
1437    /// [`set_task_rendering`](Self::set_task_rendering), and they come back here exactly as
1438    /// they were written, JSON types intact.
1439    ///
1440    /// # Errors
1441    ///
1442    /// Returns a [`SourceError`] when the source could not answer, a record whose answers it
1443    /// cannot read included.
1444    async fn task_template_answers(
1445        &self,
1446        id: &NativeId,
1447    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
1448        let _ = id;
1449        Ok(None)
1450    }
1451
1452    /// The template answers the document `id` was last rendered from, on exactly the terms of
1453    /// [`task_template_answers`](Self::task_template_answers).
1454    ///
1455    /// # Errors
1456    ///
1457    /// As [`task_template_answers`](Self::task_template_answers).
1458    async fn document_template_answers(
1459        &self,
1460        id: &NativeId,
1461    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
1462        let _ = id;
1463        Ok(None)
1464    }
1465
1466    /// The template answers the project `id` was last rendered from, on exactly the terms of
1467    /// [`task_template_answers`](Self::task_template_answers).
1468    ///
1469    /// # Errors
1470    ///
1471    /// As [`task_template_answers`](Self::task_template_answers).
1472    async fn project_template_answers(
1473        &self,
1474        id: &NativeId,
1475    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
1476        let _ = id;
1477        Ok(None)
1478    }
1479
1480    /// Create or update one task exactly as [`write_task`](Self::write_task) does, keeping
1481    /// `answers` — the answers its content was rendered from — beside it in the same write
1482    /// where this source keeps answers at all.
1483    ///
1484    /// The task arrives carrying its provenance under [`MetadataKey::TEMPLATE_KEY`] like any
1485    /// other metadata entry. Defaulted to [`write_task`](Self::write_task) alone: a source that
1486    /// keeps no answers writes the task and nothing beside it, which is the whole of what it
1487    /// owes. A source that keeps them writes the task and the answers together, so a reader
1488    /// never finds one without the other.
1489    ///
1490    /// # Errors
1491    ///
1492    /// As [`write_task`](Self::write_task).
1493    async fn write_task_rendered(
1494        &self,
1495        write: &ItemWrite<Task>,
1496        answers: &BTreeMap<String, Value>,
1497    ) -> Result<NativeId, SourceError> {
1498        let _ = answers;
1499        self.write_task(write).await
1500    }
1501
1502    /// Create or update one document, on exactly the terms of
1503    /// [`write_task_rendered`](Self::write_task_rendered).
1504    ///
1505    /// # Errors
1506    ///
1507    /// As [`write_document`](Self::write_document).
1508    async fn write_document_rendered(
1509        &self,
1510        write: &ItemWrite<Document>,
1511        answers: &BTreeMap<String, Value>,
1512    ) -> Result<NativeId, SourceError> {
1513        let _ = answers;
1514        self.write_document(write).await
1515    }
1516
1517    /// Create or update one project, on exactly the terms of
1518    /// [`write_task_rendered`](Self::write_task_rendered).
1519    ///
1520    /// # Errors
1521    ///
1522    /// As [`write_project`](Self::write_project).
1523    async fn write_project_rendered(
1524        &self,
1525        write: &ItemWrite<Project>,
1526        answers: &BTreeMap<String, Value>,
1527    ) -> Result<NativeId, SourceError> {
1528        let _ = answers;
1529        self.write_project(write).await
1530    }
1531
1532    /// Replace one task's rendering — its content, byte for byte, its
1533    /// [`MetadataKey::TEMPLATE_KEY`] entry, set to `provenance`, and the answers it keeps
1534    /// beside the task where it keeps any — in one write, and change nothing else about it;
1535    /// or answer `None` when this source holds no such task.
1536    ///
1537    /// The content is [`Task::content`] exactly as a later read reports it, on the terms of
1538    /// [`set_task_content`](Self::set_task_content). Title, status, priority, labels, every
1539    /// other metadata entry, repositories, dependencies, [`Task::delivers`],
1540    /// [`Task::delivered_by`], project and comments are left exactly as they are. The write is
1541    /// one write: a reader sees the task as it was or as it is now, never a new content beside
1542    /// the old provenance or the old answers.
1543    ///
1544    /// Defaulted to [`unwritable_field`] on exactly the terms of
1545    /// [`set_task_status`](Self::set_task_status). A source declaring
1546    /// [`WriteSupport::Unsupported`] is never asked.
1547    ///
1548    /// [`Task::delivers`]: crate::Task::delivers
1549    /// [`Task::delivered_by`]: crate::Task::delivered_by
1550    ///
1551    /// # Errors
1552    ///
1553    /// Returns [`SourceError::Refused`] when this source cannot replace a task's rendering on
1554    /// its own, or cannot represent this one; and whatever else the source could not do the
1555    /// write for.
1556    async fn set_task_rendering(
1557        &self,
1558        id: &NativeId,
1559        content: &str,
1560        provenance: &Value,
1561        answers: &BTreeMap<String, Value>,
1562    ) -> Result<Option<()>, SourceError> {
1563        let _ = (id, content, provenance, answers);
1564        Err(unwritable_field(self.kind(), "rendering"))
1565    }
1566
1567    /// Replace one document's rendering, on exactly the terms of
1568    /// [`set_task_rendering`](Self::set_task_rendering). A source declaring
1569    /// [`Capabilities::documents`] unsupported is never asked.
1570    ///
1571    /// # Errors
1572    ///
1573    /// As [`set_task_rendering`](Self::set_task_rendering).
1574    async fn set_document_rendering(
1575        &self,
1576        id: &NativeId,
1577        content: &str,
1578        provenance: &Value,
1579        answers: &BTreeMap<String, Value>,
1580    ) -> Result<Option<()>, SourceError> {
1581        let _ = (id, content, provenance, answers);
1582        Err(SourceError::Refused {
1583            message: format!(
1584                "the {} plugin cannot write a document's rendering on its own",
1585                self.kind()
1586            ),
1587        })
1588    }
1589
1590    /// Replace one project's rendering, on exactly the terms of
1591    /// [`set_task_rendering`](Self::set_task_rendering): its content, its
1592    /// [`MetadataKey::TEMPLATE_KEY`] entry and the answers kept beside it change, and its
1593    /// title, status, labels, every other metadata entry, repositories and dependencies are
1594    /// left exactly as they are.
1595    ///
1596    /// # Errors
1597    ///
1598    /// As [`set_task_rendering`](Self::set_task_rendering).
1599    async fn set_project_rendering(
1600        &self,
1601        id: &NativeId,
1602        content: &str,
1603        provenance: &Value,
1604        answers: &BTreeMap<String, Value>,
1605    ) -> Result<Option<()>, SourceError> {
1606        let _ = (id, content, provenance, answers);
1607        Err(SourceError::Refused {
1608            message: format!(
1609                "the {} plugin cannot write a project's rendering on its own",
1610                self.kind()
1611            ),
1612        })
1613    }
1614
1615    /// The image assets the task `id` holds, or none when it holds none or this source holds
1616    /// no such task.
1617    ///
1618    /// Defaulted to none, which is what keeps assets an addition rather than a break: a source
1619    /// that keeps no assets needs no edit and reports every record as holding none. A source
1620    /// declaring [`Capabilities::assets`] native answers what it holds for the record, in any
1621    /// order — the engine orders them by the content's first reference.
1622    ///
1623    /// # Errors
1624    ///
1625    /// Returns a [`SourceError`] when the source could not answer.
1626    async fn task_assets(&self, id: &NativeId) -> Result<Vec<Asset>, SourceError> {
1627        let _ = id;
1628        Ok(Vec::new())
1629    }
1630
1631    /// The image assets the document `id` holds, on exactly the terms of
1632    /// [`task_assets`](Self::task_assets).
1633    ///
1634    /// # Errors
1635    ///
1636    /// As [`task_assets`](Self::task_assets).
1637    async fn document_assets(&self, id: &NativeId) -> Result<Vec<Asset>, SourceError> {
1638        let _ = id;
1639        Ok(Vec::new())
1640    }
1641
1642    /// The bytes of the asset `name` the task `id` holds, or `None` when it holds no such asset
1643    /// or this source holds no such task.
1644    ///
1645    /// Defaulted to `None`, on the terms of [`task_assets`](Self::task_assets).
1646    ///
1647    /// # Errors
1648    ///
1649    /// Returns a [`SourceError`] when the source could not answer.
1650    async fn task_asset(
1651        &self,
1652        id: &NativeId,
1653        name: &AssetName,
1654    ) -> Result<Option<Vec<u8>>, SourceError> {
1655        let _ = (id, name);
1656        Ok(None)
1657    }
1658
1659    /// The bytes of the asset `name` the document `id` holds, on exactly the terms of
1660    /// [`task_asset`](Self::task_asset).
1661    ///
1662    /// # Errors
1663    ///
1664    /// As [`task_asset`](Self::task_asset).
1665    async fn document_asset(
1666        &self,
1667        id: &NativeId,
1668        name: &AssetName,
1669    ) -> Result<Option<Vec<u8>>, SourceError> {
1670        let _ = (id, name);
1671        Ok(None)
1672    }
1673
1674    /// Create or update one task carrying image assets, in one write: the task as
1675    /// [`write_task`](Self::write_task) writes it — or, with `answers`, as
1676    /// [`write_task_rendered`](Self::write_task_rendered) does — and `assets` as the record's
1677    /// whole asset set, answering with where it landed and the content as stored.
1678    ///
1679    /// Only a source declaring [`Capabilities::assets`] native is asked, and the engine has
1680    /// already checked that every reference in the content names one of `assets` and every one
1681    /// of `assets` is referenced. A source that keeps the bytes beside the record stores each
1682    /// payload under its name, removes every asset the record held that `assets` does not
1683    /// name, and answers the content unchanged. A source that serves them at a URL uploads each
1684    /// payload that carries bytes, reuses the URL [`AssetWrite::recorded_assets`] records for
1685    /// each that does not, and writes the record through
1686    /// [`serve_asset_references`](crate::serve_asset_references) — so its references point at
1687    /// those URLs, its [`MetadataKey::ASSETS_KEY`] records each `{sha256, url}`, and a
1688    /// rendering's `body_digest` stays true of what landed — answering the content it wrote.
1689    ///
1690    /// Defaulted to [`assetless`], which is what a source with no assets answers.
1691    ///
1692    /// # Errors
1693    ///
1694    /// As [`write_task`](Self::write_task), and [`SourceError::Refused`] from a source that
1695    /// keeps no assets.
1696    async fn write_task_with_assets(
1697        &self,
1698        write: &ItemWrite<Task>,
1699        answers: Option<&BTreeMap<String, Value>>,
1700        assets: &AssetWrite,
1701    ) -> Result<AssetsWritten, SourceError> {
1702        let _ = (write, answers, assets);
1703        Err(assetless(self.kind()))
1704    }
1705
1706    /// Create or update one document carrying image assets, on exactly the terms of
1707    /// [`write_task_with_assets`](Self::write_task_with_assets).
1708    ///
1709    /// # Errors
1710    ///
1711    /// As [`write_task_with_assets`](Self::write_task_with_assets).
1712    async fn write_document_with_assets(
1713        &self,
1714        write: &ItemWrite<Document>,
1715        answers: Option<&BTreeMap<String, Value>>,
1716        assets: &AssetWrite,
1717    ) -> Result<AssetsWritten, SourceError> {
1718        let _ = (write, answers, assets);
1719        Err(assetless(self.kind()))
1720    }
1721
1722    /// Replace one task's rendering as [`set_task_rendering`](Self::set_task_rendering) does,
1723    /// and its asset set as [`write_task_with_assets`](Self::write_task_with_assets) does, in
1724    /// one write; or answer `None` when this source holds no such task.
1725    ///
1726    /// Defaulted to [`assetless`].
1727    ///
1728    /// # Errors
1729    ///
1730    /// As [`set_task_rendering`](Self::set_task_rendering), and [`SourceError::Refused`] from a
1731    /// source that keeps no assets.
1732    async fn set_task_rendering_with_assets(
1733        &self,
1734        id: &NativeId,
1735        content: &str,
1736        provenance: &Value,
1737        answers: &BTreeMap<String, Value>,
1738        assets: &AssetWrite,
1739    ) -> Result<Option<AssetsWritten>, SourceError> {
1740        let _ = (id, content, provenance, answers, assets);
1741        Err(assetless(self.kind()))
1742    }
1743
1744    /// Replace one document's rendering and its asset set, on exactly the terms of
1745    /// [`set_task_rendering_with_assets`](Self::set_task_rendering_with_assets).
1746    ///
1747    /// # Errors
1748    ///
1749    /// As [`set_task_rendering_with_assets`](Self::set_task_rendering_with_assets).
1750    async fn set_document_rendering_with_assets(
1751        &self,
1752        id: &NativeId,
1753        content: &str,
1754        provenance: &Value,
1755        answers: &BTreeMap<String, Value>,
1756        assets: &AssetWrite,
1757    ) -> Result<Option<AssetsWritten>, SourceError> {
1758        let _ = (id, content, provenance, answers, assets);
1759        Err(assetless(self.kind()))
1760    }
1761
1762    /// What this source has sent to its backend since it was built and what that spent, or
1763    /// `None` when it does not meter its own requests.
1764    ///
1765    /// Defaulted to `None`, which is what keeps metering an addition rather than a break: a
1766    /// source that does not count its requests needs no edit, and is reported as not
1767    /// metering rather than as having spent nothing. A source that answers owes a running
1768    /// total — see [`Metering`] — because what one command spent is read as the difference
1769    /// between two readings.
1770    ///
1771    /// # Errors
1772    ///
1773    /// Returns a [`SourceError`] when the reading itself could not be taken. A caller
1774    /// reports such a source as not metering; what a command cost is never a reason for the
1775    /// command to fail.
1776    async fn metering(&self) -> Result<Option<Metering>, SourceError> {
1777        Ok(None)
1778    }
1779
1780    /// End one command: drop everything held that a person can change.
1781    ///
1782    /// A command is one unit of work — one invocation of the binary, or whatever a caller
1783    /// holding one engine for many units of work calls between them. Within a command a
1784    /// source may hold what it read and reuse it; across this call it may not. After it
1785    /// returns, a source answers no read and bases no write on item content, statuses, board
1786    /// contents or search results it held before the call. It may keep only identifiers and
1787    /// vocabulary that stay valid in normal use — a repository's node id, a team's workflow
1788    /// states — and only where a lookup that misses one re-reads rather than refusing.
1789    ///
1790    /// Defaulted to doing nothing, which is right for a source that holds nothing between
1791    /// calls or holds only what the rule above lets it keep. A source that holds more owes
1792    /// an override. Never called by the engine on its own: the binary's one command is its
1793    /// whole process, so only a caller that outlives a command calls it.
1794    ///
1795    /// # Errors
1796    ///
1797    /// Returns a [`SourceError`] when the source could not be sure it dropped what it held —
1798    /// ordinarily a hosted plugin that did not answer. A caller should not go on to the next
1799    /// command on that source's earlier reads.
1800    async fn end_command(&self) -> Result<(), SourceError> {
1801        Ok(())
1802    }
1803
1804    /// Who can read where `target` lands, read live from the backend.
1805    ///
1806    /// This is the destination's reality, which the engine holds a declaration against
1807    /// before it lets a write through: a source a configuration declares private receives an
1808    /// item that may only be written somewhere private only while this answers
1809    /// [`Visibility::Private`]. The engine asks immediately before the write it is about, so
1810    /// a source must not answer from anything it read for an earlier write unless its
1811    /// backend's visibility cannot change in between.
1812    ///
1813    /// Defaulted to [`Visibility::Unknown`], which is the answer of a source that cannot say
1814    /// and is never treated as private. A source on this machine answers `Private` — what it
1815    /// writes stays on the host — and a hosted source reads its backend.
1816    ///
1817    /// # Errors
1818    ///
1819    /// Returns a [`SourceError`] when the backend could not be asked or would not answer —
1820    /// a credential lacking the scope the read needs among them. An unreadable visibility is
1821    /// never guessed: the engine refuses the write.
1822    async fn visibility(&self, target: &WriteTarget<'_>) -> Result<Visibility, SourceError> {
1823        let _ = target;
1824        Ok(Visibility::Unknown)
1825    }
1826}
1827
1828/// The factory that turns one configuration block into a live [`TaskSource`].
1829///
1830/// Having the compile-time registry and the subprocess seam be the same shape is
1831/// the whole reason this is a trait rather than a free function.
1832pub trait SourcePlugin: Send + Sync + 'static {
1833    /// The name a configuration document's `plugin:` field names.
1834    fn kind(&self) -> &'static str;
1835
1836    /// The JSON Schema for this plugin's own `config:` block.
1837    fn config_schema(&self) -> Schema;
1838
1839    /// Build a live source from one configuration block.
1840    ///
1841    /// `name` is the configured source's name, for error messages only — a
1842    /// plugin never learns it for any other purpose.
1843    ///
1844    /// # Errors
1845    ///
1846    /// Returns [`SourceError::Config`] when `config` is not valid for this
1847    /// plugin, or [`SourceError::Auth`] when a named credential is absent.
1848    fn build(
1849        &self,
1850        name: &SourceName,
1851        config: &serde_json::Value,
1852        secrets: &dyn SecretResolver,
1853    ) -> Result<Box<dyn TaskSource>, SourceError>;
1854
1855    /// Build a live source from one configuration block, handing it the clock it paces and
1856    /// backs off on.
1857    ///
1858    /// The binary builds every in-process source through this, with the process's one
1859    /// [`SharedClock`] — [`system_clock`](crate::system_clock) unless a test asked for
1860    /// simulated time. Defaulted to [`build`](Self::build), which ignores the clock: a plugin
1861    /// that never waits needs no edit, and one that does overrides this and routes its waits
1862    /// through `clock`.
1863    ///
1864    /// # Errors
1865    ///
1866    /// As [`build`](Self::build).
1867    fn build_with_clock(
1868        &self,
1869        name: &SourceName,
1870        config: &serde_json::Value,
1871        secrets: &dyn SecretResolver,
1872        clock: SharedClock,
1873    ) -> Result<Box<dyn TaskSource>, SourceError> {
1874        let _ = clock;
1875        self.build(name, config, secrets)
1876    }
1877
1878    /// The fields of this plugin's `config:` block that name a filesystem path, as dotted
1879    /// paths into that block.
1880    ///
1881    /// A relative value at one of these, **supplied by a configuration document**, is
1882    /// resolved against the directory holding that document before [`Self::build`] sees it;
1883    /// supplied through the environment or a flag it keeps resolving against the process
1884    /// working directory, because there is no document to rebase it on. A plugin is handed
1885    /// values and no origins, so this declaration is the only way it can say which of its
1886    /// own fields that rule reaches.
1887    ///
1888    /// Defaulted to none, which is what keeps this an addition rather than a break: a
1889    /// plugin whose block holds no path needs no edit, and a caller asks every plugin
1890    /// rather than keeping a table of which ones answer.
1891    // llmlint: ignore[invalid_states_unrepresentable] The identity of a configuration field
1892    // is a name, and no type can make a wrong one unrepresentable here: every string is a
1893    // syntactically valid dotted path, so a newtype would validate nothing and would only
1894    // move where a name that is not a field of *this* plugin is accepted. What decides that
1895    // is whether the name is a property of the schema `config_schema` publishes — a
1896    // per-plugin fact no shared type can hold — so the gate is per plugin and executable:
1897    // `document_relative_fields_are_fields_this_plugin_declares` in
1898    // `onetaskgraph-local-md/tests/plugin.rs`, which a plugin adding a declaration owes its
1899    // own copy of.
1900    fn document_relative_paths(&self) -> &'static [&'static str] {
1901        &[]
1902    }
1903
1904    /// What names the remote store a source built from `config` reads — a board's owner and
1905    /// number, a Linear endpoint and team — or `None` for a source with no remote.
1906    ///
1907    /// The store's local cache of a remote source lives under a digest of this, so every
1908    /// process configuring the same remote shares one cache and no two remotes share one.
1909    /// Defaulted to `None`, which is what a source keeping its work on this machine — a
1910    /// folder of Markdown — answers: it has nothing to cache, and its cache setting is
1911    /// ignored. A `config` this plugin would refuse answers `None` too.
1912    fn remote_identity(&self, config: &serde_json::Value) -> Option<String> {
1913        let _ = config;
1914        None
1915    }
1916}
1917
1918/// How a plugin reads the credential its configuration names.
1919///
1920/// A configuration document never carries a credential value, only the name of
1921/// the environment variable holding it.
1922pub trait SecretResolver: Send + Sync {
1923    /// The value of `var`, or `None` when nothing defines it.
1924    ///
1925    /// The returned value is never logged and never appears in `Debug` output.
1926    fn get(&self, var: &str) -> Option<SecretString>;
1927}