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