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