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, QuotaReading, Repository, SharedClock,
17    SourceError, SourceName, Status, StatusCategory, StatusContradiction, StoredFormMigration,
18    Task, TaskDetailRead, TaskQuery, TaskRef, TaskUpdate, TaskUpdateOutcome, VersionCoverage,
19    Visibility, WriteJournal, WriteSupport, WriteTarget, assetless, commentless, documentless,
20    unwritable, unwritable_field, 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    /// What this source read in this process about where it creates — the node ids of the
319    /// repository it filed in — under a setup-context token, or `None`.
320    ///
321    /// The token is the source's own digest of every input the context depends on: the
322    /// container's field definitions and options, the repository it creates in, the project it
323    /// files under and the visibility it was declared. Immutable placement knowledge only: it
324    /// holds no item's title, content or membership, and nothing that authorizes a versioned
325    /// write. Defaulted to `None`.
326    fn placement_context(&self) -> Option<serde_json::Value> {
327        None
328    }
329
330    /// Hold `context`, which [`placement_context`](Self::placement_context) gave in an earlier
331    /// process, for the next create to take only if its token still holds — computed from a
332    /// read that create makes anyway, so taking it adds no request and a changed input is read
333    /// afresh rather than reused. Answers whether it held it; a context this source cannot read
334    /// is not held. Defaulted to holding nothing.
335    fn prime_placement(&self, context: &serde_json::Value) -> bool {
336        let _ = context;
337        false
338    }
339
340    /// The ids — never the title or the content — a later process needs to write task `id`,
341    /// which this process wrote, without reading it first, or `None`. Defaulted to `None`.
342    fn written_context(&self, id: &NativeId) -> Option<serde_json::Value> {
343        let _ = id;
344        None
345    }
346
347    /// Take `context`, which [`written_context`](Self::written_context) gave, with `task`'s
348    /// fields, as the record of `id` — so the next [`update_task`](Self::update_task) of it
349    /// sends only its mutations. What the caller holds of the body is never written: an update
350    /// that changes the body reads it first — in the answer to one of its own mutations where it
351    /// can — and composes it against what the backend holds now. Answers whether it took them;
352    /// a context it cannot read is not taken, and the update then reads as it always does.
353    /// Defaulted to taking nothing.
354    fn prime_written(
355        &self,
356        id: &NativeId,
357        context: &serde_json::Value,
358        task: &crate::Task,
359    ) -> bool {
360        let _ = (id, context, task);
361        false
362    }
363
364    /// Drop whatever [`prime_write`](Self::prime_write) took for `id`, and the board context
365    /// with it, so the next write of it reads afresh.
366    fn unprime(&self, id: &NativeId) {
367        let _ = id;
368    }
369
370    /// Who wrote `comment`, a comment this source answered: a person, a bot or unknown.
371    ///
372    /// Defaulted to [`AuthorKind::of_name`](crate::AuthorKind::of_name) over its author. A
373    /// source whose backend says more — a GitHub board, which reads each author's kind — answers
374    /// from what it read.
375    fn comment_author_kind(&self, comment: &crate::Comment) -> crate::AuthorKind {
376        crate::AuthorKind::of_name(comment.author.as_deref())
377    }
378
379    /// How long after a comment is made or edited a read of this source may still not see it —
380    /// a search index's lag behind the writes it indexes.
381    ///
382    /// A read of the comments made since an instant answers a watermark set back by this, so a
383    /// caller resuming from it reads again whatever this source had not yet shown. Defaulted to
384    /// none: a source whose reads see every write at once.
385    fn comment_consistency_window(&self) -> std::time::Duration {
386        std::time::Duration::ZERO
387    }
388
389    /// The time this source's backend last stated on an answer — a hosted service's `Date` —
390    /// or `None` for a source that states none, whose time is the engine's own clock's.
391    ///
392    /// The instant a watermark is set back from is the earlier of this and the engine's clock
393    /// at the read's start, so a backend whose clock is behind this host's loses no comment.
394    fn served_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
395        None
396    }
397
398    /// Whether this source enforces a [`HeldVersion`](crate::HeldVersion) itself, as one step
399    /// with the write it holds: `true` for a source that serializes its own writes and, inside
400    /// every task write, refuses with [`HeldVersion::moved`](crate::HeldVersion::moved) a task
401    /// not at the version [`HeldVersion::expected`](crate::HeldVersion::expected) names.
402    ///
403    /// Defaulted to `false`: the engine then reads the task through this source immediately
404    /// before a held write and refuses it there, and the time between that read and the
405    /// mutation is the backend's residual race.
406    fn holds_versions(&self) -> bool {
407        false
408    }
409
410    /// Start recording every request this source sends, for [`end_journal`](Self::end_journal).
411    ///
412    /// The engine opens one journal around one write at a time. Defaulted to recording
413    /// nothing.
414    fn begin_journal(&self) {}
415
416    /// Stop recording, answering with every request sent since
417    /// [`begin_journal`](Self::begin_journal) — or `None` for a source that records none.
418    fn end_journal(&self) -> Option<WriteJournal> {
419        None
420    }
421
422    /// Whether the source is answering right now.
423    ///
424    /// # Errors
425    ///
426    /// Returns a [`SourceError`] when the check itself could not be made.
427    async fn health(&self) -> Result<Health, SourceError>;
428
429    /// The [`Designator`](crate::Designator) naming the tracker this source reads, built by
430    /// [`Designator::of_backend`](crate::Designator::of_backend) over the backend's own opaque
431    /// identifier of itself — or `None` for a backend with none, whose configuration may
432    /// declare a `public_alias` instead.
433    ///
434    /// At most one request. The engine keeps the answer per host, so a source is asked once.
435    /// The default is `None`.
436    ///
437    /// # Errors
438    ///
439    /// Returns a [`SourceError`] when the backend could not be asked.
440    async fn designator(&self) -> Result<Option<crate::Designator>, SourceError> {
441        Ok(None)
442    }
443
444    /// Fetch one task by its native id, or `None` when there is no such task.
445    ///
446    /// # Errors
447    ///
448    /// Returns a [`SourceError`] when the source could not answer.
449    async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError>;
450
451    /// Fetch several tasks by their native ids, each with the first page of its comments
452    /// when `comments` names the page to read — one answer per id, in the order they were
453    /// given.
454    ///
455    /// Each answer is what [`get_task`](Self::get_task) answers for that id, so a task that
456    /// is not there is `Ok(None)` and a read that failed fails that id alone. Its
457    /// [`TaskDetailRead::comments`] is what [`task_comments`](Self::task_comments) answers
458    /// for `comments`. The engine passes `comments` only to a source declaring
459    /// [`Capabilities::comments`](crate::Capabilities::comments) native.
460    ///
461    /// Defaulted to exactly those calls, item by item, so a source that implements nothing
462    /// here answers as it always did. A source that can read many items — or an item and its
463    /// comments — in fewer requests than that overrides it, which is the whole reason it
464    /// exists: a caller holding twenty ids pays for one batch rather than forty reads.
465    async fn get_task_details(
466        &self,
467        ids: &[NativeId],
468        comments: Option<&PageRequest>,
469    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
470        let mut read = Vec::with_capacity(ids.len());
471        for id in ids {
472            read.push(match self.get_task(id).await {
473                Ok(Some(task)) => {
474                    let comments = match comments {
475                        Some(page) => Some(self.task_comments(id, page).await),
476                        None => None,
477                    };
478                    Ok(Some(TaskDetailRead { task, comments }))
479                }
480                Ok(None) => Ok(None),
481                Err(error) => Err(error),
482            });
483        }
484        read
485    }
486
487    /// Fetch one project by its native id, or `None` when there is no such project.
488    ///
489    /// # Errors
490    ///
491    /// Returns a [`SourceError`] when the source could not answer.
492    async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError>;
493
494    /// One page of the tasks matching `query`.
495    ///
496    /// # Errors
497    ///
498    /// Returns a [`SourceError`] when the source could not answer.
499    async fn query_tasks(
500        &self,
501        query: &TaskQuery,
502        page: &PageRequest,
503    ) -> Result<Page<Task>, SourceError>;
504
505    /// One page of each of many task queries, answered in the order asked, each exactly as
506    /// [`query_tasks`](Self::query_tasks) would answer it alone — the three capability rules
507    /// included, query by query.
508    ///
509    /// One query's page failing is that query's answer alone: the others are answered as
510    /// though it had not been asked. Defaulted to one [`query_tasks`](Self::query_tasks) per
511    /// query; a source whose backend answers several searches in one request overrides it.
512    async fn query_tasks_batch(
513        &self,
514        asks: &[(TaskQuery, PageRequest)],
515    ) -> Vec<Result<Page<Task>, SourceError>> {
516        let mut answers = Vec::with_capacity(asks.len());
517        for (query, page) in asks {
518            answers.push(self.query_tasks(query, page).await);
519        }
520        answers
521    }
522
523    /// One page of tasks, optionally carrying each task's first comment page.
524    ///
525    /// With `comments` absent this answers exactly [`Self::query_tasks`], with no
526    /// comments requested. With it present, every returned item must carry
527    /// [`TaskDetailRead::comments`], including a per-item refusal for a task that
528    /// cannot have comments. The comment request must have no cursor: subsequent
529    /// pages belong to individual tasks and are read through [`Self::task_comments`].
530    ///
531    /// Sources may return fewer tasks than the limit, including an empty page with a
532    /// continuation cursor when the underlying page contains only non-task items. Cursors
533    /// belong to this method and must not be exchanged with ordinary listing cursors.
534    /// A source may document the backend enumeration's consistency separately from its
535    /// ordinary listing, but must apply every predicate it declares native or refuse it.
536    ///
537    /// # Errors
538    ///
539    /// A source that cannot include comments refuses the listing rather than silently
540    /// omitting them. The default refuses before reading any tasks when asked for comments.
541    async fn query_task_details(
542        &self,
543        query: &TaskQuery,
544        page: &PageRequest,
545        comments: Option<&PageRequest>,
546    ) -> Result<Page<TaskDetailRead>, SourceError> {
547        if comments.is_some() {
548            return Err(SourceError::Refused {
549                message: format!("the {} plugin cannot list tasks with comments", self.kind()),
550            });
551        }
552        let tasks = self.query_tasks(query, page).await?;
553        Ok(Page {
554            items: tasks
555                .items
556                .into_iter()
557                .map(|task| TaskDetailRead {
558                    task,
559                    comments: None,
560                })
561                .collect(),
562            next: tasks.next,
563        })
564    }
565
566    /// One page of the projects matching `query`.
567    ///
568    /// # Errors
569    ///
570    /// Returns a [`SourceError`] when the source could not answer.
571    async fn query_projects(
572        &self,
573        query: &ProjectQuery,
574        page: &PageRequest,
575    ) -> Result<Page<Project>, SourceError>;
576
577    /// One page of the projects whose [`TaskQuery::ORIGIN_KEY`] entry is a string equal to
578    /// `origin`, exactly — the projects copied from that qualified id, and none other.
579    ///
580    /// `origin` is compared byte for byte, on the terms [`TaskQuery::origin`] states, and is
581    /// never constructed or interpreted here. Zero, one or several projects may match; which
582    /// of several a caller wants is the caller's question.
583    ///
584    /// Defaulted to [`query_projects`](Self::query_projects) unfiltered, walked to its end on
585    /// every call and narrowed here, so a source that implements nothing answers exactly what
586    /// its own listing holds; the default's cursor is a position among the matches. A source
587    /// that can ask its store for one origin overrides it, which is the whole reason it
588    /// exists: a caller looking for the copies of one plan pays for those copies rather than
589    /// for every project the store holds.
590    ///
591    /// # Errors
592    ///
593    /// Returns a [`SourceError`] when the source could not answer, and
594    /// [`SourceError::Refused`] for a cursor the default did not hand out.
595    async fn query_projects_by_origin(
596        &self,
597        origin: &str,
598        page: &PageRequest,
599    ) -> Result<Page<Project>, SourceError> {
600        let wanted = origin_query(origin);
601        let mut matched = Vec::new();
602        let mut cursor: Option<crate::Cursor> = None;
603        // Every cursor the listing handed out, so one cycling through several is caught as
604        // one repeating the last is.
605        let mut visited: Vec<String> = Vec::new();
606        loop {
607            let listed = self
608                .query_projects(
609                    &ProjectQuery::default(),
610                    &PageRequest {
611                        cursor: cursor.clone(),
612                        limit: page.limit,
613                    },
614                )
615                .await?;
616            overran(listed.items.len(), page.limit)?;
617            matched.extend(
618                listed
619                    .items
620                    .into_iter()
621                    .filter(|project| wanted.origin_matches(&project.metadata)),
622            );
623            cursor = match listed.next {
624                None => break,
625                Some(next) if visited.contains(&next.0) => return Err(repeated_cursor()),
626                Some(next) => {
627                    visited.push(next.0.clone());
628                    Some(next)
629                }
630            };
631        }
632        page_of_matches(matched, page)
633    }
634
635    /// One page of every label this source knows.
636    ///
637    /// # Errors
638    ///
639    /// Returns a [`SourceError`] when the source could not answer.
640    async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError>;
641
642    /// One page of the task dependency edges at `id`, in `direction`.
643    ///
644    /// # Errors
645    ///
646    /// Returns a [`SourceError`] when the source could not answer.
647    async fn task_dependencies(
648        &self,
649        id: &NativeId,
650        direction: Direction,
651        page: &PageRequest,
652    ) -> Result<Page<DependencyEdge>, SourceError>;
653
654    /// One page of the project dependency edges at `id`, in `direction`.
655    ///
656    /// # Errors
657    ///
658    /// Returns a [`SourceError`] when the source could not answer.
659    async fn project_dependencies(
660        &self,
661        id: &NativeId,
662        direction: Direction,
663        page: &PageRequest,
664    ) -> Result<Page<DependencyEdge>, SourceError>;
665
666    /// Whether this source can be written through at all.
667    ///
668    /// Defaulted to [`WriteSupport::Unsupported`], which is what keeps this a read
669    /// interface for every source that has nothing to write into: one that cannot be
670    /// written needs no edit and keeps working. Read before a write is attempted, so a
671    /// copy naming such a source as its destination is refused before anything is read.
672    fn writes(&self) -> WriteSupport {
673        WriteSupport::Unsupported
674    }
675
676    /// The status this source's backend holds once an item of `kind` is written at `status`:
677    /// the name it records for the category, where it names a category itself rather than
678    /// keeping the name it was given.
679    ///
680    /// What a copy compares a destination item's status with, so an item whose category it
681    /// already holds reads as unchanged rather than as differing by a name no write could
682    /// change. Defaulted to `status` as given: a backend that keeps the name it is written
683    /// declares nothing.
684    ///
685    /// Asynchronous and fallible because a source hosted over the stdio plugin protocol asks
686    /// the plugin that declares it; an in-process source answers at once and never fails.
687    ///
688    /// # Errors
689    ///
690    /// A [`SourceError`] when the source could not say what its backend holds — never the
691    /// status as given in its place.
692    async fn stored_status(&self, kind: ItemKind, status: &Status) -> Result<Status, SourceError> {
693        let _ = kind;
694        Ok(status.clone())
695    }
696
697    /// The content the backend answered it now holds for the `record` `id`, as the response
698    /// to this instance's latest write of that item's content reported it — taken, so a second
699    /// call answers `None` until the next such write.
700    ///
701    /// The content is as a read reports content — the metadata slot, and whatever separates
702    /// it from the content, removed — and it is read off the write's own response, never by a
703    /// request of its own. It is what the engine takes as the record of what the item holds: a
704    /// backend may rewrite the Markdown it is written, keeping its rendered meaning, and where
705    /// this differs from what was sent the engine records each fingerprint it keeps over this
706    /// content instead — a rendering's `body_digest`, a copy's
707    /// [`MetadataKey::COPIED_DESTINATION_VERSION_KEY`] — and writes it back once, beside them,
708    /// as its own request. That follow-up write's own answer is then compared with this
709    /// content, and a backend that does not hold its own stored content stable is refused as
710    /// `stored-content-diverged`; only a `linear` source's answer that autolinked or escaped a copy's
711    /// own text is written back once more instead, and that write's answer is compared byte for
712    /// byte. Defaulted to `None`: a backend that stores what
713    /// it is given says nothing, and nothing is compared or written again.
714    fn stored_content(&self, record: MetadataRecord, id: &NativeId) -> Option<String> {
715        let _ = (record, id);
716        None
717    }
718
719    /// The headings of the `record` `id` as this source's backend stores them — each one's
720    /// text and the id the backend gave it, in order — from the latest answer this source
721    /// read or wrote it with in the current command.
722    ///
723    /// Answered without a request: a backend that assigns its headings ids reports them out
724    /// of the responses its reads and writes already received, so a caller may ask after
725    /// every read and every write for free. `None` is not knowing — the record was not read
726    /// or written here, or its answer carried no headings — and a caller that needs them
727    /// reads the record. Defaulted to `None`: a backend whose headings have no ids of their
728    /// own has nothing to say.
729    fn stored_headings(
730        &self,
731        record: MetadataRecord,
732        id: &NativeId,
733    ) -> Option<Vec<crate::StoredHeading>> {
734        let _ = (record, id);
735        None
736    }
737
738    /// Hand this source the markup its bodies carry — for a reader to address their headings,
739    /// or for a block to be expandable there: see [`crate::BodyMarkup`]. Called once, by the engine, as it builds the source.
740    /// Defaulted to ignoring it, which a source whose backend needs no such markup does.
741    fn attach_body_markup(&self, markup: crate::SharedBodyMarkup) {
742        let _ = markup;
743    }
744
745    /// Create or update one task, answering with the native id the destination holds it
746    /// under.
747    ///
748    /// A source declaring [`WriteSupport::Supported`] owes three things here. It refuses,
749    /// naming the field, anything it cannot represent rather than dropping it — including
750    /// a metadata key it cannot carry, which it names. It writes every other field it was
751    /// given. And it never creates when [`ItemWrite::target`] names an item it does not
752    /// hold.
753    ///
754    /// # Errors
755    ///
756    /// Returns [`SourceError::Refused`] when this source has no write side, when a field
757    /// or a metadata key cannot be represented, or when `target` names nothing here; and
758    /// whatever else the source could not do the write for.
759    async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
760        let _ = write;
761        Err(unwritable(self.kind()))
762    }
763
764    /// Create or update one project, on exactly the terms of
765    /// [`write_task`](Self::write_task).
766    ///
767    /// # Errors
768    ///
769    /// As [`write_task`](Self::write_task).
770    async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
771        let _ = write;
772        Err(unwritable(self.kind()))
773    }
774
775    /// Whether this source can represent every field of `write` — its status, its content, the
776    /// tasks it delivers and every other field a [`write_task`](Self::write_task) of it would
777    /// refuse as "cannot represent the field …" — asked before anything is written and changing
778    /// nothing.
779    ///
780    /// A task copy asks it of every task it plans before its first write, and leaves out each
781    /// task this refuses — answered `failed`, with this refusal as its reason — writing the rest
782    /// as one copy. It answers what the write itself would refuse in the same words; and it is a
783    /// promise only about representability, so a write may still fail for any other reason.
784    ///
785    /// Defaulted to `Ok(())`: a source that does not answer it in advance still refuses such a
786    /// write in its write, which a copy then takes back whole, exactly as before.
787    ///
788    /// # Errors
789    ///
790    /// Returns [`SourceError::Refused`] naming the field this source cannot represent; and
791    /// whatever else kept it from finding out.
792    async fn check_task_write(&self, write: &ItemWrite<Task>) -> Result<(), SourceError> {
793        let _ = write;
794        Ok(())
795    }
796
797    /// How large the body a [`write_task`](Self::write_task) of `write` would store is — or a
798    /// [`write_task_with_assets`](Self::write_task_with_assets) of it, when `assets` is given —
799    /// and the most one body here holds, answered without a request and changing nothing.
800    ///
801    /// The body is composed as the write would compose it: the content, this source's metadata
802    /// slot and every asset reference rewritten to where this source serves the asset, an asset
803    /// not uploaded yet at the length its address will have. A copy asks it of every item it
804    /// plans before its first write, refuses the whole copy when any item's body is larger than
805    /// the limit, and reports each size from a dry run. What the write itself decides from a
806    /// read — the repository an issue lands in, an edge no relationship here can name — is
807    /// taken as this source would most likely decide it, so the answer may differ from what
808    /// lands by those few characters; the write still refuses a body its backend will not take.
809    ///
810    /// Defaulted to `None`: a source that cannot say, and one whose bodies have no size worth
811    /// stating, answers nothing, and its items are copied exactly as before.
812    fn task_body_size(
813        &self,
814        write: &ItemWrite<Task>,
815        assets: Option<&crate::AssetWrite>,
816    ) -> Option<crate::BodySize> {
817        let _ = (write, assets);
818        None
819    }
820
821    /// [`task_body_size`](Self::task_body_size), for a [`write_project`](Self::write_project).
822    fn project_body_size(&self, write: &ItemWrite<Project>) -> Option<crate::BodySize> {
823        let _ = write;
824        None
825    }
826
827    /// [`task_body_size`](Self::task_body_size), for a [`write_document`](Self::write_document) —
828    /// or a [`write_document_with_assets`](Self::write_document_with_assets), when `assets` is
829    /// given.
830    fn document_body_size(
831        &self,
832        write: &ItemWrite<Document>,
833        assets: Option<&crate::AssetWrite>,
834    ) -> Option<crate::BodySize> {
835        let _ = (write, assets);
836        None
837    }
838
839    /// Whether a write of an item of `kind` at `category` — over the item `target` names, or
840    /// creating one when it is `None` — would have a status to write, asked before the write
841    /// and changing nothing.
842    ///
843    /// A caller that has to put an item back when a later write of it fails — a copy, whose
844    /// journal records what an item held before overwriting it — asks this first, so a status
845    /// this source has no name for is refused while nothing has been recorded or written, and
846    /// nothing has to be put back. It answers what the write itself would refuse a status
847    /// with, in the same words, and sends no request a write of that status would not have
848    /// sent anyway: what it reads to answer, it holds for the write that follows.
849    ///
850    /// Defaulted to `Ok(())`: a source that does not answer it in advance still refuses the
851    /// status in its write, exactly as before.
852    ///
853    /// # Errors
854    ///
855    /// Returns [`SourceError::Refused`] naming the kind, the category and what is missing
856    /// when this source has no name for that status; and whatever else kept it from finding
857    /// out.
858    async fn check_status_write(
859        &self,
860        kind: ItemKind,
861        category: StatusCategory,
862        target: Option<&NativeId>,
863    ) -> Result<(), SourceError> {
864        let _ = (kind, category, target);
865        Ok(())
866    }
867
868    /// The status an item of `kind` reads back as once this source has written `status` for
869    /// it, asked without writing or reading anything.
870    ///
871    /// A source that keeps a status's name as it was given answers `status` itself. One that
872    /// writes a category to a name of its own — a board's `Status` option the category maps
873    /// to — answers that name, so a caller comparing what it would write with what the source
874    /// holds does not read a difference of spelling alone as a change: a copy then leaves an
875    /// item that already reads as the source does unwritten.
876    ///
877    /// Defaulted to `status` itself, which is what every source keeping names verbatim reads
878    /// back, and what a caller compared against before this was asked.
879    fn status_as_written(&self, kind: ItemKind, status: &Status) -> Status {
880        let _ = kind;
881        status.clone()
882    }
883
884    /// Whether this source has a name to write `category` as on an item of `kind`, so a status
885    /// write of it would not be refused for want of one — answered from this source's
886    /// configuration alone, sending no request and reading nothing.
887    ///
888    /// `false` for a category its `status_mapping` does not name, sets to `null`, or names for
889    /// the other kind only. A name the backend's own vocabulary lacks still answers `true`:
890    /// only a write discovers that, exactly as [`check_status_write`](Self::check_status_write)
891    /// or the write itself does.
892    ///
893    /// Defaulted to `true`, which is what a source that keeps whatever category it is given —
894    /// the in-memory source — answers for every one.
895    fn maps_status(&self, kind: ItemKind, category: StatusCategory) -> bool {
896        let _ = (kind, category);
897        true
898    }
899
900    /// Set the status of one task this source holds, and change nothing else about it,
901    /// answering with the status as this source now reads it — or `None` when this source
902    /// holds no such task.
903    ///
904    /// The category lands where this source's own mapping sends it, exactly as a
905    /// [`write_task`](Self::write_task) of a task in that category would: a category this
906    /// source has disabled is refused in the words a write of it is refused with. Title,
907    /// content, labels, metadata, dependencies, [`Task::delivers`], [`Task::delivered_by`],
908    /// project and comments are left exactly as they are.
909    ///
910    /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
911    /// break: a source that cannot write a status on its own needs no edit and refuses by
912    /// saying so. A source declaring [`WriteSupport::Unsupported`] is never asked.
913    ///
914    /// [`Task::delivers`]: crate::Task::delivers
915    /// [`Task::delivered_by`]: crate::Task::delivered_by
916    ///
917    /// # Errors
918    ///
919    /// Returns [`SourceError::Refused`] when this source cannot write a status, or cannot
920    /// write this one; and whatever else the source could not do the write for.
921    async fn set_task_status(
922        &self,
923        id: &NativeId,
924        category: StatusCategory,
925    ) -> Result<Option<Status>, SourceError> {
926        let _ = (id, category);
927        Err(unwritable_field(self.kind(), "status"))
928    }
929
930    /// Set the status of one project this source holds, and change nothing else about it,
931    /// answering with the status as this source now reads it — or `None` when this source
932    /// holds no such project.
933    ///
934    /// The category lands where this source's own mapping sends it for a project, exactly as a
935    /// [`write_project`](Self::write_project) of a project in that category would: a category
936    /// this source has disabled is refused in the words a write of it is refused with. Title,
937    /// content, labels, metadata, repositories, dependencies and the project's tasks are left
938    /// exactly as they are. A project delivers no task, so nothing is kept in step after it.
939    ///
940    /// Defaulted to the refusal [`set_task_status`](Self::set_task_status) defaults to,
941    /// [`unwritable_field`] naming `status`, which is what keeps this an addition rather than a
942    /// break: a source that does not implement it needs no edit. A source declaring
943    /// [`WriteSupport::Unsupported`] is never asked.
944    ///
945    /// # Errors
946    ///
947    /// Returns [`SourceError::Refused`] when this source cannot write a project's status, or
948    /// cannot write this one; and whatever else the source could not do the write for.
949    async fn set_project_status(
950        &self,
951        id: &NativeId,
952        category: StatusCategory,
953    ) -> Result<Option<Status>, SourceError> {
954        let _ = (id, category);
955        Err(unwritable_field(self.kind(), "status"))
956    }
957
958    /// Set the status of one task this source holds, as [`set_task_status`](Self::set_task_status)
959    /// does, and answer with the whole task as this source now reads it — its
960    /// [`Task::delivers`] among what a caller keeping delivered tasks in step needs — or `None`
961    /// when this source holds no such task.
962    ///
963    /// Defaulted to exactly the two calls a caller would otherwise make: [`get_task`] first,
964    /// answering `None` with nothing written when it does, then `set_task_status`, the status
965    /// it answers put on the task read. A source whose status write answers the whole task in
966    /// the same round trip overrides it to save the read.
967    ///
968    /// [`Task::delivers`]: crate::Task::delivers
969    /// [`get_task`]: Self::get_task
970    ///
971    /// # Errors
972    ///
973    /// As [`get_task`](Self::get_task) and [`set_task_status`](Self::set_task_status).
974    async fn set_task_status_reading(
975        &self,
976        id: &NativeId,
977        category: StatusCategory,
978    ) -> Result<Option<Task>, SourceError> {
979        let Some(mut task) = self.get_task(id).await? else {
980            return Ok(None);
981        };
982        let Some(status) = self.set_task_status(id, category).await? else {
983            return Ok(None);
984        };
985        task.status = status;
986        Ok(Some(task))
987    }
988
989    /// Every task this source holds whose card contradicts its issue's closure, each with the
990    /// status that brings it in line — what `task status reconcile` writes, through
991    /// [`set_task_status`](Self::set_task_status), one task at a time.
992    ///
993    /// A task needs it when its issue is closed with a reason that reads `done` or
994    /// `cancelled` and its card does not sit at the option this source's mapping gives that
995    /// category. An open task, a closure that reads `unknown` and a card already in line are
996    /// never answered. Changes nothing.
997    ///
998    /// Asked only of a source declaring
999    /// [`Capabilities::reconcile_status`](crate::Capabilities::reconcile_status); defaulted to a
1000    /// refusal saying so, which no caller holding to that declaration ever receives.
1001    ///
1002    /// # Errors
1003    ///
1004    /// Returns [`SourceError::Refused`] when this source answers no such question; and whatever
1005    /// kept it from reading its items.
1006    async fn status_contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
1007        Err(SourceError::Refused {
1008            message: format!(
1009                "a {} source's status is its closure, so nothing needs reconciling",
1010                self.kind()
1011            ),
1012        })
1013    }
1014
1015    /// For each issue in `issues`, in order and once each, the task this source holds for it
1016    /// and what moving it to `done` comes to — what `task status complete` writes, through
1017    /// [`set_task_status`](Self::set_task_status), for each one answered
1018    /// [`Completion::Due`](crate::Completion::Due).
1019    ///
1020    /// The read is proportional to `issues` and never to the size of what this source holds,
1021    /// and an empty `issues` reads nothing. Changes nothing.
1022    ///
1023    /// Asked only of a source declaring
1024    /// [`Capabilities::complete_by_issue`](crate::Capabilities::complete_by_issue); defaulted
1025    /// to a refusal saying so, which no caller holding to that declaration ever receives.
1026    ///
1027    /// # Errors
1028    ///
1029    /// Returns [`SourceError::Refused`] when this source answers no such question; and whatever
1030    /// kept it from reading the issues.
1031    async fn issue_holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
1032        let _ = issues;
1033        Err(SourceError::Refused {
1034            message: format!("a {} source holds no items by issue reference", self.kind()),
1035        })
1036    }
1037
1038    /// Set the priority of one task this source holds, and change nothing else about it,
1039    /// answering with the priority as this source now reads it — or `None` when this source
1040    /// holds no such task.
1041    ///
1042    /// [`Priority::None`] clears the priority. Title, content, status, labels, metadata,
1043    /// repositories, dependencies and comments are left exactly as they are. Nothing about
1044    /// the task's status moves, so the engine re-evaluates no delivered task after it.
1045    ///
1046    /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
1047    /// break. A source declaring [`WriteSupport::Unsupported`], or declaring
1048    /// [`Capabilities::priority`] unsupported, is never asked.
1049    ///
1050    /// # Errors
1051    ///
1052    /// Returns [`SourceError::Refused`] when this source cannot write a priority, or cannot
1053    /// write this one — a board with no option for it, naming the option; and whatever else
1054    /// the source could not do the write for.
1055    async fn set_task_priority(
1056        &self,
1057        id: &NativeId,
1058        priority: Priority,
1059    ) -> Result<Option<Priority>, SourceError> {
1060        let _ = (id, priority);
1061        Err(unwritable_field(self.kind(), "priority"))
1062    }
1063
1064    /// Replace the content of one task this source holds with `content`, byte for byte, and
1065    /// change nothing else about it — or answer `None` when this source holds no such task.
1066    ///
1067    /// The content is [`Task::content`] exactly as this source reports it: what a later read
1068    /// answers there is `content`. Where the source keeps something else inside the same
1069    /// backend field — a metadata block in an issue body — that is kept as it was, and so is
1070    /// every other member: title, status, priority, labels, metadata, repositories,
1071    /// dependencies, project and comments. Nothing about the task's status moves, so the
1072    /// engine re-evaluates no delivered task after it.
1073    ///
1074    /// Defaulted to [`unwritable_field`] on exactly the terms of
1075    /// [`set_task_status`](Self::set_task_status). A source declaring
1076    /// [`WriteSupport::Unsupported`] is never asked.
1077    ///
1078    /// # Errors
1079    ///
1080    /// Returns [`SourceError::Refused`] when this source cannot write a task's content on its
1081    /// own, or cannot represent this one; and whatever else the source could not do the write
1082    /// for.
1083    async fn set_task_content(
1084        &self,
1085        id: &NativeId,
1086        content: &str,
1087    ) -> Result<Option<()>, SourceError> {
1088        let _ = (id, content);
1089        Err(unwritable_field(self.kind(), "content"))
1090    }
1091
1092    /// Replace the [`Task::delivered_by`] of one task this source holds, and change nothing
1093    /// else about it — or answer `None` when this source holds no such task.
1094    ///
1095    /// Every entry is a qualified id, and the list is the whole of it: what the task held
1096    /// there before is replaced, not merged. It is the store's to keep in step — the engine
1097    /// calls this whenever it writes a task's [`Task::delivers`] — and nothing a person types
1098    /// reaches it directly.
1099    ///
1100    /// Defaulted to [`unwritable_field`] on exactly the terms of
1101    /// [`set_task_status`](Self::set_task_status).
1102    ///
1103    /// [`Task::delivers`]: crate::Task::delivers
1104    /// [`Task::delivered_by`]: crate::Task::delivered_by
1105    ///
1106    /// # Errors
1107    ///
1108    /// Returns [`SourceError::Refused`] when this source cannot hold the list, and whatever
1109    /// else it could not do the write for.
1110    async fn set_delivered_by(
1111        &self,
1112        id: &NativeId,
1113        delivered_by: &[TaskRef],
1114    ) -> Result<Option<()>, SourceError> {
1115        let _ = (id, delivered_by);
1116        Err(unwritable_field(self.kind(), "delivered_by"))
1117    }
1118
1119    /// Set one key of the metadata of one task this source holds, and change nothing else
1120    /// about it, answering with the task as this source reads it back after the write — or
1121    /// `None` when this source holds no such task.
1122    ///
1123    /// The key is added when the task does not hold it and replaced when it does; every other
1124    /// metadata key, and every other field of the task, is left exactly as it was. A `value`
1125    /// the task already holds under `key` is a write that changes nothing, and a source owes
1126    /// it no write at all. The answer is a read, not an echo: what the engine reports as the
1127    /// value is what the returned task holds under `key`.
1128    ///
1129    /// Nothing about the task's status or its [`Task::delivers`] moves, so the engine
1130    /// re-evaluates no delivered task after this write.
1131    ///
1132    /// Defaulted to [`unwritable_metadata`] on exactly the terms of
1133    /// [`set_task_status`](Self::set_task_status): a source that cannot write one key on its
1134    /// own needs no edit and refuses by saying so. A source declaring
1135    /// [`WriteSupport::Unsupported`] is never asked.
1136    ///
1137    /// [`Task::delivers`]: crate::Task::delivers
1138    ///
1139    /// # Errors
1140    ///
1141    /// Returns [`SourceError::Refused`] when this source cannot write one key of a task's
1142    /// metadata on its own, or cannot write this one without changing something else; and
1143    /// whatever else the source could not do the write for.
1144    async fn set_task_metadata(
1145        &self,
1146        id: &NativeId,
1147        key: &MetadataKey,
1148        value: &Value,
1149    ) -> Result<Option<Task>, SourceError> {
1150        let _ = (id, key, value);
1151        Err(unwritable_metadata(self.kind(), MetadataRecord::Task))
1152    }
1153
1154    /// Apply a targeted update to one task this source holds — every field `update` names, and
1155    /// nothing else — answering with a [`TaskUpdateOutcome`], or `None` when this source holds
1156    /// no such task.
1157    ///
1158    /// The outcome is everything the engine reports about the call, so it reads nothing of its
1159    /// own: the task as this source reads it once the update landed — from the one read it made
1160    /// and what it then wrote, where its backend answers a write with what it holds — the
1161    /// fields it actually wrote, and the `delivers` the task held before.
1162    ///
1163    /// A field already holding the requested value is sent no write, and an update in which
1164    /// nothing differs sends no write at all. Every field `update` leaves unnamed — labels,
1165    /// repositories, project, [`Task::delivered_by`] and comments always among them — is left
1166    /// exactly as it is. An update naming one metadata key both to set and to remove is refused
1167    /// before anything is written, in the words of [`TaskUpdate::consistent`].
1168    ///
1169    /// Defaulted to [`TaskUpdate::rewrite`]: read the task, apply the update, and — only when
1170    /// anything differs — [`write_task`](Self::write_task) it with its `target` set. That keeps
1171    /// this an addition rather than a break, and a source that predates it behaves correctly and
1172    /// is merely not minimal; one whose backend can take a field on its own owes an override
1173    /// that sends only what differs. A source declaring [`WriteSupport::Unsupported`] is never
1174    /// asked.
1175    ///
1176    /// [`Task::delivered_by`]: crate::Task::delivered_by
1177    ///
1178    /// # Errors
1179    ///
1180    /// Returns [`SourceError::Refused`] when the update contradicts itself, when a field it
1181    /// names cannot be represented here — a category this source has disabled included — and
1182    /// whatever else the source could not do the write for.
1183    async fn update_task(
1184        &self,
1185        id: &NativeId,
1186        update: &TaskUpdate,
1187    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
1188        update.rewrite(self, id).await
1189    }
1190
1191    /// Apply many targeted updates, each on exactly the terms of
1192    /// [`update_task`](Self::update_task), answering one [`BatchAnswer`] per update in the
1193    /// order given.
1194    ///
1195    /// Each update is its own write, held to its own `if_version` and guarded by its own
1196    /// `when_priority` and `when_assignees`: one answered [`BatchAnswer::VersionMoved`],
1197    /// [`BatchAnswer::PriorityHeld`], [`BatchAnswer::AssigneesHeld`], [`BatchAnswer::Missing`]
1198    /// or an error writes nothing of
1199    /// its own and never writes or refuses another. Every field one update names is written
1200    /// together or not at all.
1201    ///
1202    /// Defaulted to one [`update_task`](Self::update_task) per update, preceded by one read of
1203    /// the task where its hold or its guard needs one — exactly the requests a caller making
1204    /// each update on its own would send. A source whose backend carries several updates in one
1205    /// request overrides it, and sends on its own exactly the update its backend would refuse
1206    /// as a whole.
1207    async fn update_tasks(
1208        &self,
1209        updates: &[crate::BatchUpdate],
1210    ) -> Vec<Result<crate::BatchAnswer<TaskUpdateOutcome>, SourceError>> {
1211        crate::batch::update_each(self, updates).await
1212    }
1213
1214    /// Each task's relations — its parent, its children and, in its metadata, its links — one
1215    /// answer per id in the order given, `None` for an id this source holds no task under.
1216    ///
1217    /// Each [`Relations::task`](crate::Relations::task) is the task exactly as
1218    /// [`get_task`](Self::get_task) answers it, its `## Links` section stripped
1219    /// ([`read_content`](crate::read_content)); a source that holds no parent relation — or,
1220    /// like a GitHub board read with sub-issues as projects, gives it another meaning — answers
1221    /// every task with none and no children. A source whose backend reads many items in one
1222    /// request reads them together.
1223    ///
1224    /// Each answer is its own: an id the source cannot read — one its backend refuses, or
1225    /// answers malformed — carries that [`SourceError`] while every other id is answered, so
1226    /// one bad id never costs a relation call the rest of its items. A failure that reaches
1227    /// every id, a request that never answered among them, is every id's answer.
1228    ///
1229    /// Defaulted to a refusal of every id: a source that predates relations, or a peer over
1230    /// the plugin protocol, holds none and strips no section, so a link is never written to
1231    /// it.
1232    async fn read_relations(
1233        &self,
1234        ids: &[NativeId],
1235    ) -> Vec<Result<Option<crate::Relations>, SourceError>> {
1236        let refused = crate::relationless(self.kind());
1237        ids.iter().map(|_| Err(refused.clone())).collect()
1238    }
1239
1240    /// Set or remove each child's parent, answering one [`ParentAnswer`](crate::ParentAnswer)
1241    /// per write in the order given.
1242    ///
1243    /// Each write is its own: one held to a version the child has moved past, one naming a
1244    /// missing task, and one the destination refuses — a cycle, or a limit on children or depth
1245    /// — is that write's answer alone, and every other write goes on. A child already under the
1246    /// parent named is answered `Unchanged` and nothing is sent for it.
1247    ///
1248    /// Defaulted to refusing every write, for a source that holds no parent relation.
1249    async fn set_parents(
1250        &self,
1251        writes: &[crate::ParentWrite],
1252    ) -> Vec<Result<crate::ParentAnswer, SourceError>> {
1253        writes
1254            .iter()
1255            .map(|_| Err(crate::relationless(self.kind())))
1256            .collect()
1257    }
1258
1259    /// The link types this source mirrors as its own relation, each with its native word, as
1260    /// its `link_types` configuration names them. Defaulted to none.
1261    fn link_types(&self) -> crate::LinkTypes {
1262        crate::LinkTypes::default()
1263    }
1264
1265    /// Add each native relation mirroring a link — idempotently, so adding one that is already
1266    /// there is no change — answering one result per relation in the order given.
1267    ///
1268    /// The engine asks this only for a link type [`link_types`](Self::link_types) names, and
1269    /// only between two tasks of this source. Defaulted to refusing each.
1270    async fn add_native_links(&self, links: &[crate::NativeLink]) -> Vec<Result<(), SourceError>> {
1271        links
1272            .iter()
1273            .map(|_| Err(crate::relationless(self.kind())))
1274            .collect()
1275    }
1276
1277    /// Remove each native relation mirroring a link — one that is not there is no change —
1278    /// answering one result per relation in the order given. The engine asks only once no
1279    /// mirrored link between that pair remains. Defaulted to refusing each.
1280    async fn remove_native_links(
1281        &self,
1282        links: &[crate::NativeLink],
1283    ) -> Vec<Result<(), SourceError>> {
1284        links
1285            .iter()
1286            .map(|_| Err(crate::relationless(self.kind())))
1287            .collect()
1288    }
1289
1290    /// Set one key of the metadata of one project this source holds, on exactly the terms of
1291    /// [`set_task_metadata`](Self::set_task_metadata).
1292    ///
1293    /// # Errors
1294    ///
1295    /// As [`set_task_metadata`](Self::set_task_metadata).
1296    async fn set_project_metadata(
1297        &self,
1298        id: &NativeId,
1299        key: &MetadataKey,
1300        value: &Value,
1301    ) -> Result<Option<Project>, SourceError> {
1302        let _ = (id, key, value);
1303        Err(unwritable_metadata(self.kind(), MetadataRecord::Project))
1304    }
1305
1306    /// Set one key of the metadata of one document this source holds, on exactly the terms of
1307    /// [`set_task_metadata`](Self::set_task_metadata).
1308    ///
1309    /// A source declaring [`Capabilities::documents`] unsupported is never asked, exactly as
1310    /// it is never asked for a document read.
1311    ///
1312    /// # Errors
1313    ///
1314    /// As [`set_task_metadata`](Self::set_task_metadata).
1315    async fn set_document_metadata(
1316        &self,
1317        id: &NativeId,
1318        key: &MetadataKey,
1319        value: &Value,
1320    ) -> Result<Option<Document>, SourceError> {
1321        let _ = (id, key, value);
1322        Err(unwritable_metadata(self.kind(), MetadataRecord::Document))
1323    }
1324
1325    /// Remove one task this destination holds, so a copy that could not finish can put
1326    /// the destination back the way it found it.
1327    ///
1328    /// This is not a verb of the product: nothing a user types deletes anything, and a
1329    /// copy never deletes an item it did not itself create in the run that is failing.
1330    /// It exists because a copy is either complete or it never happened — a half-written
1331    /// project has to be run again, and the re-run is the mutation burst that trips a
1332    /// hosted destination's rate limiter. Undoing this run's own creates is what removes
1333    /// that retry at source.
1334    ///
1335    /// A source declaring [`WriteSupport::Supported`] owes a real implementation, for the
1336    /// reason it owes [`write_task`](Self::write_task) one: the engine will create items
1337    /// there, so it has to be able to remove the ones it created. An `id` naming nothing
1338    /// is **not** an error — the item is already gone, which is the state this asks for.
1339    ///
1340    /// # Errors
1341    ///
1342    /// Returns [`SourceError::Refused`] when this source has no write side, and whatever
1343    /// else the source could not remove the item for.
1344    async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
1345        let _ = id;
1346        Err(unwritable(self.kind()))
1347    }
1348
1349    /// Remove one project this destination holds, on exactly the terms of
1350    /// [`delete_task`](Self::delete_task).
1351    ///
1352    /// # Errors
1353    ///
1354    /// As [`delete_task`](Self::delete_task).
1355    async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
1356        let _ = id;
1357        Err(unwritable(self.kind()))
1358    }
1359
1360    /// Fetch one document by its native id, or `None` when there is no such document.
1361    ///
1362    /// Defaulted to [`documentless`], which is what keeps documents an addition rather
1363    /// than a break: a source with none needs no edit, keeps working, and says so in the
1364    /// same words every other document-free source does. A source that has documents
1365    /// declares [`Support::Native`](crate::Support::Native) for
1366    /// [`Capabilities::documents`] and owes a real implementation here, because that
1367    /// declaration is what makes the engine ask.
1368    ///
1369    /// # Errors
1370    ///
1371    /// Returns [`SourceError::Refused`] when this source has no documents, and whatever
1372    /// else the source could not answer for.
1373    async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
1374        let _ = id;
1375        Err(documentless(self.kind()))
1376    }
1377
1378    /// One page of the documents matching `query`.
1379    ///
1380    /// Defaulted on exactly the terms of [`get_document`](Self::get_document). A source
1381    /// with no documents refuses rather than answering an empty page: an empty page reads
1382    /// as a source that has documents and holds none matching, which is the one wrong
1383    /// answer this method can give.
1384    ///
1385    /// # Errors
1386    ///
1387    /// As [`get_document`](Self::get_document).
1388    async fn query_documents(
1389        &self,
1390        query: &DocumentQuery,
1391        page: &PageRequest,
1392    ) -> Result<Page<Document>, SourceError> {
1393        let _ = (query, page);
1394        Err(documentless(self.kind()))
1395    }
1396
1397    /// One page of the documents whose [`TaskQuery::ORIGIN_KEY`] entry is a string equal to
1398    /// `origin`, exactly, on the terms of
1399    /// [`query_projects_by_origin`](Self::query_projects_by_origin).
1400    ///
1401    /// Defaulted to [`query_documents`](Self::query_documents) unfiltered, walked and narrowed
1402    /// as that default is — so a source with no documents refuses exactly as its
1403    /// `query_documents` does.
1404    ///
1405    /// # Errors
1406    ///
1407    /// As [`query_documents`](Self::query_documents), and [`SourceError::Refused`] for a
1408    /// cursor the default did not hand out.
1409    async fn query_documents_by_origin(
1410        &self,
1411        origin: &str,
1412        page: &PageRequest,
1413    ) -> Result<Page<Document>, SourceError> {
1414        let wanted = origin_query(origin);
1415        let mut matched = Vec::new();
1416        let mut cursor: Option<crate::Cursor> = None;
1417        // Every cursor the listing handed out, so one cycling through several is caught as
1418        // one repeating the last is.
1419        let mut visited: Vec<String> = Vec::new();
1420        loop {
1421            let listed = self
1422                .query_documents(
1423                    &DocumentQuery::default(),
1424                    &PageRequest {
1425                        cursor: cursor.clone(),
1426                        limit: page.limit,
1427                    },
1428                )
1429                .await?;
1430            overran(listed.items.len(), page.limit)?;
1431            matched.extend(
1432                listed
1433                    .items
1434                    .into_iter()
1435                    .filter(|document| wanted.origin_matches(&document.metadata)),
1436            );
1437            cursor = match listed.next {
1438                None => break,
1439                Some(next) if visited.contains(&next.0) => return Err(repeated_cursor()),
1440                Some(next) => {
1441                    visited.push(next.0.clone());
1442                    Some(next)
1443                }
1444            };
1445        }
1446        page_of_matches(matched, page)
1447    }
1448
1449    /// Create or update one document, on exactly the terms of
1450    /// [`write_task`](Self::write_task).
1451    ///
1452    /// # Errors
1453    ///
1454    /// As [`write_task`](Self::write_task).
1455    async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
1456        let _ = write;
1457        Err(unwritable(self.kind()))
1458    }
1459
1460    /// Remove one document this destination holds, on exactly the terms of
1461    /// [`delete_task`](Self::delete_task).
1462    ///
1463    /// # Errors
1464    ///
1465    /// As [`delete_task`](Self::delete_task).
1466    async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
1467        let _ = id;
1468        Err(unwritable(self.kind()))
1469    }
1470
1471    /// One page of the comments on `task`, oldest first, or `None` when this source holds
1472    /// no such task.
1473    ///
1474    /// Defaulted to [`commentless`], which is what keeps comments an addition rather than a
1475    /// break: a source with none needs no edit and keeps working. A source whose tasks have
1476    /// comments declares [`Support::Native`](crate::Support::Native) for
1477    /// [`Capabilities::comments`] and owes a real implementation of all four comment methods,
1478    /// because that declaration is what makes the engine ask.
1479    ///
1480    /// "No such task" is `None` rather than an error, exactly as it is for
1481    /// [`get_task`](Self::get_task); a task that exists and has no comments is an empty page.
1482    ///
1483    /// # Errors
1484    ///
1485    /// Returns [`SourceError::Refused`] when this source has no comments, and whatever else
1486    /// the source could not answer for.
1487    async fn task_comments(
1488        &self,
1489        task: &NativeId,
1490        page: &PageRequest,
1491    ) -> Result<Option<Page<Comment>>, SourceError> {
1492        let _ = (task, page);
1493        Err(commentless(self.kind()))
1494    }
1495
1496    /// [`get_task_details`](Self::get_task_details) as a copy reads the tasks it carries: each
1497    /// with the first page of its comments `comments` names — and, where the same request can
1498    /// carry them, what this source needs to answer [`task_dependencies`](Self::task_dependencies)
1499    /// for it without another, since a copy reads every task's edges next.
1500    ///
1501    /// Defaulted to `get_task_details(ids, Some(comments))`, which is exactly what it answers.
1502    /// A source whose detail read is priced by what it selects overrides it with a read that
1503    /// also carries the edges, so a copy of a changed task costs its detail read and nothing
1504    /// more; one whose reads are free has no reason to.
1505    async fn get_task_details_for_copy(
1506        &self,
1507        ids: &[NativeId],
1508        comments: &PageRequest,
1509    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
1510        self.get_task_details(ids, Some(comments)).await
1511    }
1512
1513    /// Read the items `ids` names — tasks, projects and documents alike, whatever kind each
1514    /// is — together, as a copy reads the counterparts it is about to write, and hold each for
1515    /// this command so that the next [`get_task`](Self::get_task),
1516    /// [`get_project`](Self::get_project) or [`get_document`](Self::get_document) of it is
1517    /// answered from that read, once, instead of being sent on its own.
1518    ///
1519    /// What is held is exactly what that read by id would have answered — the item's fields,
1520    /// its edges, its asset manifest and its change token — and only until the next read of
1521    /// it, a write naming it, or [`end_command`](Self::end_command), whichever comes first, so
1522    /// a read answered from it is never staler than the read-before-write it stands in for.
1523    ///
1524    /// Defaulted to doing nothing, so every read is sent as it always was: a source whose
1525    /// reads are free has no reason to override it, and one priced per request overrides it
1526    /// with a batched read. An id the batched read finds nothing at is either held as absent —
1527    /// its next read answers `None`, exactly as that read would have — or not held, and its own
1528    /// read answers as it always does.
1529    ///
1530    /// # Errors
1531    ///
1532    /// Returns a [`SourceError`] when the batched read could not be made. Nothing is then
1533    /// held, and each item's own read answers as it would have.
1534    async fn read_ahead_for_copy(&self, ids: &[NativeId]) -> Result<(), SourceError> {
1535        let _ = ids;
1536        Ok(())
1537    }
1538
1539    /// [`read_ahead_for_copy`](Self::read_ahead_for_copy), with what each id is at this source —
1540    /// a task, a project or a document — as the copy knows it: what a source whose reads by id
1541    /// are each of one kind needs to read them together.
1542    ///
1543    /// Defaulted to [`read_ahead_for_copy`](Self::read_ahead_for_copy) of the ids alone, so a
1544    /// source that reads any kind by one id is asked exactly as it was.
1545    ///
1546    /// # Errors
1547    ///
1548    /// As [`read_ahead_for_copy`](Self::read_ahead_for_copy).
1549    async fn read_ahead_records_for_copy(
1550        &self,
1551        records: &[(MetadataRecord, NativeId)],
1552    ) -> Result<(), SourceError> {
1553        let ids: Vec<NativeId> = records.iter().map(|(_, id)| id.clone()).collect();
1554        self.read_ahead_for_copy(&ids).await
1555    }
1556
1557    /// Ask, together, which items were copied from each of `origins` — the qualified ids a copy
1558    /// is about to look for at this destination by the `onetaskgraph.origin` each item records
1559    /// — and hold each answer
1560    /// for this command, so that the next query for the items copied from one of them (a
1561    /// [`TaskQuery::origin`] task query, [`query_projects_by_origin`](Self::query_projects_by_origin)
1562    /// or [`query_documents_by_origin`](Self::query_documents_by_origin)) is answered from it,
1563    /// once, instead of being sent on its own. A source may carry in the same read whatever its
1564    /// creating an item would read first, since a copy finding nothing creates — and its
1565    /// [`designator`](Self::designator), which a copy writing edges asks next: a designator
1566    /// carried in that read answers the next [`designator`](Self::designator) of the command
1567    /// without a request of its own.
1568    ///
1569    /// What is held is exactly what those queries would have answered, and only until the next
1570    /// write or [`end_command`](Self::end_command); a designator, which no write moves, until
1571    /// [`end_command`](Self::end_command). An origin is held as having no counterpart only when
1572    /// the read answered it whole: one whose answer the read could not see the end of is left
1573    /// to its own query. Defaulted to doing nothing, so each query is sent as it always was.
1574    ///
1575    /// # Errors
1576    ///
1577    /// Returns a [`SourceError`] when the read could not be made. Nothing is then held, and each
1578    /// query answers as it would have.
1579    async fn read_ahead_origins_for_copy(&self, origins: &[String]) -> Result<(), SourceError> {
1580        let _ = origins;
1581        Ok(())
1582    }
1583
1584    /// Who may read each member of the project `project` — every task and document filed under
1585    /// it — as the classification and repositories each one's record holds, read by whatever
1586    /// this source holds for this command rather than by its whole records: what a write the
1587    /// public boundary screens reads of a project before it is held to it.
1588    ///
1589    /// `None` is no such read, and is the default: the engine then reads the members as it
1590    /// always has, through [`query_tasks`](Self::query_tasks) narrowed to the project and
1591    /// [`query_documents`](Self::query_documents), so every source answers exactly as before. A
1592    /// source answers `Some` only with every member — a page that says there is more is no
1593    /// answer, and is left to that path — and never with fewer members than those queries
1594    /// would have listed. A source may hold such a page from a read it made beside another,
1595    /// such as the one [`read_ahead_for_copy`](Self::read_ahead_for_copy) names the project to.
1596    ///
1597    /// # Errors
1598    ///
1599    /// Returns a [`SourceError`] when the read could not be made.
1600    async fn member_classifications(
1601        &self,
1602        project: &NativeId,
1603    ) -> Result<Option<Vec<(Classification, Vec<Repository>)>>, SourceError> {
1604        let _ = project;
1605        Ok(None)
1606    }
1607
1608    /// Whether a task this source creates through [`write_tasks`](Self::write_tasks) may carry
1609    /// everything a copy's own write of it would — the copy's record of it among them — so the
1610    /// write a copy then makes of it, naming the same, writes nothing.
1611    ///
1612    /// A copy then creates together only the tasks that depend on no other task of the copy,
1613    /// whose edges are all nameable at their create, and creates each of the others on its own,
1614    /// after what it depends on. Defaulted to `false`: a task created together lands with no
1615    /// record, and the write after it names its edges to the others.
1616    fn records_created_together(&self) -> bool {
1617        false
1618    }
1619
1620    /// How many tasks this source creates in one [`write_tasks`](Self::write_tasks): more than
1621    /// one only for a source that creates several in one request.
1622    ///
1623    /// A copy hands such a source the tasks it creates together, and names each one's edges to
1624    /// the others in a write after they all exist. Defaulted to one, which has a copy write every
1625    /// task on its own, exactly as before.
1626    fn create_batch_limit(&self) -> usize {
1627        1
1628    }
1629
1630    /// Create every task of `writes` — each [`ItemWrite::target`] `None` — answering with the
1631    /// native ids they were created under, in order.
1632    ///
1633    /// All of them or none: a source that cannot create every one takes back each it did create
1634    /// before refusing, on the terms §4.9 of the protocol puts on [`write_task`](Self::write_task).
1635    /// Defaulted to creating them one at a time through [`write_task`](Self::write_task), taking
1636    /// back those created when a later one is refused.
1637    ///
1638    /// # Errors
1639    ///
1640    /// Refused, before anything is written, when a write names an existing target; otherwise
1641    /// whatever [`write_task`](Self::write_task) of one of them refuses with.
1642    // 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.
1643    async fn write_tasks(&self, writes: &[ItemWrite<Task>]) -> Result<Vec<NativeId>, SourceError> {
1644        if let Some(write) = writes.iter().find(|write| write.target.is_some()) {
1645            return Err(SourceError::Refused {
1646                message: format!(
1647                    "write_tasks creates tasks, and the write of {} names an existing target; \
1648                     next: update it with write_task",
1649                    write.item.id
1650                ),
1651            });
1652        }
1653        let mut created = Vec::with_capacity(writes.len());
1654        for write in writes {
1655            match self.write_task(write).await {
1656                Ok(id) => created.push(id),
1657                Err(error) => {
1658                    // The caller is never handed these ids, so one this source will not take
1659                    // back is named here or by nobody.
1660                    let mut left: Vec<&str> = Vec::new();
1661                    for id in &created {
1662                        if self.delete_task(id).await.is_err() {
1663                            left.push(id.0.as_str());
1664                        }
1665                    }
1666                    if left.is_empty() {
1667                        return Err(error);
1668                    }
1669                    return Err(SourceError::Refused {
1670                        message: format!(
1671                            "{error}; this source then refused to take back {}, which this \
1672                             write created and which it still holds; next: delete {} before \
1673                             writing again",
1674                            left.join(", "),
1675                            if left.len() == 1 { "it" } else { "them" }
1676                        ),
1677                    });
1678                }
1679            }
1680        }
1681        Ok(created)
1682    }
1683
1684    /// From here until [`finish_writes`](Self::finish_writes), a source may hold back the part of
1685    /// each write that can land later — a created item's fields and edges — and send it together
1686    /// with the others' when that is called.
1687    ///
1688    /// A caller asks for this only when it will call `finish_writes` before it reads what it
1689    /// wrote from anywhere but this source, or reports it written. Defaulted to holding nothing
1690    /// back, so every write lands whole as it is made.
1691    fn begin_deferred_writes(&self) {}
1692
1693    /// Send whatever this source has held back since [`begin_deferred_writes`](Self::begin_deferred_writes),
1694    /// and hold nothing back after it.
1695    ///
1696    /// All or nothing for the items it created: a source that cannot finish them takes them back
1697    /// before refusing, so a caller undoing its writes finds them gone. Defaulted to doing
1698    /// nothing, since nothing was held.
1699    ///
1700    /// # Errors
1701    ///
1702    /// Whatever sending what was held back was refused with.
1703    async fn finish_writes(&self) -> Result<(), SourceError> {
1704        Ok(())
1705    }
1706
1707    /// Where an item this source wrote in the current command is, when the write's own answer
1708    /// said so: `record` names which kind of item `id` is.
1709    ///
1710    /// Answered only from what a write already returned — never by a request — so a caller may
1711    /// ask it after every write for free. A caller treats `None` as not knowing, and reads the
1712    /// item when it needs its location. Defaulted to `None`.
1713    fn written_location(&self, record: MetadataRecord, id: &NativeId) -> Option<Location> {
1714        let _ = (record, id);
1715        None
1716    }
1717
1718    /// The task `id` as this source holds it after its latest write of it in the current
1719    /// command, when what that write sent and was answered with says so — its status, its
1720    /// priority and its change token among the rest.
1721    ///
1722    /// Answered without a request to a remote party: a hosted source answers from the
1723    /// responses its own write already received, and a source on this machine from what it
1724    /// wrote. Its `version` is `None` where those responses cannot vouch for a token the next
1725    /// read would give. A caller treats `None` as not knowing. Defaulted to `None`.
1726    async fn written_task(&self, id: &NativeId) -> Option<Task> {
1727        let _ = id;
1728        None
1729    }
1730
1731    /// The change token the `record` `id` holds after this source's latest write of it in the
1732    /// current command, on the terms [`Self::written_task`] answers a task's — `None` where the
1733    /// write's own responses cannot vouch for one. Defaulted to `None`.
1734    async fn written_version(&self, record: MetadataRecord, id: &NativeId) -> Option<String> {
1735        let _ = (record, id);
1736        None
1737    }
1738
1739    /// Add one comment to `task`, answering with the comment as the source now holds it, or
1740    /// `None` when this source holds no such task.
1741    ///
1742    /// The body is stored byte for byte. A source that records the author itself refuses a
1743    /// [`NewComment::author`] rather than dropping it, naming why; a source that cannot
1744    /// represent the body refuses it, naming why, rather than escaping it into something
1745    /// else.
1746    ///
1747    /// # Errors
1748    ///
1749    /// Returns [`SourceError::Refused`] when this source has no comments or cannot be
1750    /// written, when it cannot record what it was given, and whatever else it could not do
1751    /// the write for.
1752    async fn add_comment(
1753        &self,
1754        task: &NativeId,
1755        comment: &NewComment,
1756    ) -> Result<Option<Comment>, SourceError> {
1757        let _ = (task, comment);
1758        Err(commentless(self.kind()))
1759    }
1760
1761    /// Add many comments, each on exactly the terms of [`add_comment`](Self::add_comment),
1762    /// answering one [`BatchAnswer`] per comment in the order given.
1763    ///
1764    /// Each comment is its own write, held to its own `if_version`: one answered
1765    /// [`BatchAnswer::VersionMoved`], [`BatchAnswer::Missing`] or an error writes nothing of its
1766    /// own and never writes or refuses another.
1767    ///
1768    /// Defaulted to one [`add_comment`](Self::add_comment) per comment, preceded by one read of
1769    /// the task where its hold needs one. A source whose backend carries several comments in one
1770    /// request overrides it.
1771    async fn add_comments(
1772        &self,
1773        comments: &[crate::BatchComment],
1774    ) -> Vec<Result<crate::BatchAnswer<Comment>, SourceError>> {
1775        crate::batch::comment_each(self, comments).await
1776    }
1777
1778    /// Replace the body of the comment `comment` on `task`, answering with the comment as the
1779    /// source now holds it, or `None` when this source holds no such task or that task has no
1780    /// such comment.
1781    ///
1782    /// Only the body and the time it last changed move: the id, the author and the time it
1783    /// was written are the comment's own.
1784    ///
1785    /// # Errors
1786    ///
1787    /// As [`add_comment`](Self::add_comment).
1788    async fn edit_comment(
1789        &self,
1790        task: &NativeId,
1791        comment: &NativeId,
1792        body: &CommentBody,
1793    ) -> Result<Option<Comment>, SourceError> {
1794        let _ = (task, comment, body);
1795        Err(commentless(self.kind()))
1796    }
1797
1798    /// Remove the comment `comment` from `task`, answering with the id it removed, or `None`
1799    /// when this source holds no such task or that task has no such comment.
1800    ///
1801    /// Unlike [`delete_task`](Self::delete_task), this *is* a verb of the product — a person
1802    /// removes a comment they posted — so a comment that is not there is reported as `None`
1803    /// for the engine to refuse by name, rather than treated as already gone.
1804    ///
1805    /// # Errors
1806    ///
1807    /// As [`add_comment`](Self::add_comment).
1808    async fn delete_comment(
1809        &self,
1810        task: &NativeId,
1811        comment: &NativeId,
1812    ) -> Result<Option<NativeId>, SourceError> {
1813        let _ = (task, comment);
1814        Err(commentless(self.kind()))
1815    }
1816
1817    /// Write one comment a copy carries onto `task`: a new one when `existing` is `None`, and
1818    /// otherwise the comment `existing`, which a copy wrote before, made to say `copy` — or
1819    /// `None` when this source holds no such task or no such comment.
1820    ///
1821    /// The answer reports [`Comment::origin`] as `copy.origin`, however the source keeps it.
1822    ///
1823    /// **Defaulted to the hidden marker**, which is right for every source that records a
1824    /// comment's author and times itself: the body is written through
1825    /// [`add_comment`](Self::add_comment) or [`edit_comment`](Self::edit_comment) with
1826    /// [`CommentOrigin::mark`](crate::CommentOrigin::mark) appended, and read back
1827    /// [`unmarked`](Comment::unmarked). A source that can store the origin natively — and so
1828    /// takes the origin's own id, author and times for the copy — overrides this.
1829    ///
1830    /// # Errors
1831    ///
1832    /// As [`add_comment`](Self::add_comment).
1833    async fn write_comment_copy(
1834        &self,
1835        task: &NativeId,
1836        existing: Option<&NativeId>,
1837        copy: &CommentCopy,
1838    ) -> Result<Option<Comment>, SourceError> {
1839        let body = CommentBody::new(copy.origin.qualified()?.mark(copy.body.as_str()))?;
1840        let written = match existing {
1841            Some(comment) => self.edit_comment(task, comment, &body).await?,
1842            None => {
1843                self.add_comment(task, &NewComment { body, author: None })
1844                    .await?
1845            }
1846        };
1847        Ok(written.map(Comment::unmarked))
1848    }
1849
1850    /// Whether this source keeps template answers beside its items at all.
1851    ///
1852    /// What lets a regenerate tell an item whose answers went missing — a block deleted by
1853    /// hand, which the regenerate writes back — from an item of a source that never keeps any,
1854    /// where a missing answer is no difference. Defaulted to `false`, as
1855    /// [`task_template_answers`](Self::task_template_answers) is defaulted to `None`; a source
1856    /// that keeps answers answers `true` here.
1857    fn keeps_template_answers(&self) -> bool {
1858        false
1859    }
1860
1861    /// The template answers the task `id` was last rendered from, as this source keeps them
1862    /// beside the task — or `None` when it keeps none for it, or holds no such task.
1863    ///
1864    /// Keeping answers is a source's own choice, never an obligation: a source whose items
1865    /// are one record in a hosted system has no room beside the item that is not the item, and
1866    /// answers written into its content or its metadata would duplicate what the content
1867    /// already says. Defaulted to `None`, which is what keeps this an addition rather than a
1868    /// break. A source that keeps them owes three things: they are in neither
1869    /// [`Task::content`] nor [`Task::metadata`], they are written only by
1870    /// [`write_task_rendered`](Self::write_task_rendered) and
1871    /// [`set_task_rendering`](Self::set_task_rendering), and they come back here exactly as
1872    /// they were written, JSON types intact.
1873    ///
1874    /// # Errors
1875    ///
1876    /// Returns a [`SourceError`] when the source could not answer, a record whose answers it
1877    /// cannot read included.
1878    async fn task_template_answers(
1879        &self,
1880        id: &NativeId,
1881    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
1882        let _ = id;
1883        Ok(None)
1884    }
1885
1886    /// The template answers the document `id` was last rendered from, on exactly the terms of
1887    /// [`task_template_answers`](Self::task_template_answers).
1888    ///
1889    /// # Errors
1890    ///
1891    /// As [`task_template_answers`](Self::task_template_answers).
1892    async fn document_template_answers(
1893        &self,
1894        id: &NativeId,
1895    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
1896        let _ = id;
1897        Ok(None)
1898    }
1899
1900    /// The template answers the project `id` was last rendered from, on exactly the terms of
1901    /// [`task_template_answers`](Self::task_template_answers).
1902    ///
1903    /// # Errors
1904    ///
1905    /// As [`task_template_answers`](Self::task_template_answers).
1906    async fn project_template_answers(
1907        &self,
1908        id: &NativeId,
1909    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
1910        let _ = id;
1911        Ok(None)
1912    }
1913
1914    /// Create or update one task exactly as [`write_task`](Self::write_task) does, keeping
1915    /// `answers` — the answers its content was rendered from — beside it in the same write
1916    /// where this source keeps answers at all.
1917    ///
1918    /// The task arrives carrying its provenance under [`MetadataKey::TEMPLATE_KEY`] like any
1919    /// other metadata entry. Defaulted to [`write_task`](Self::write_task) alone: a source that
1920    /// keeps no answers writes the task and nothing beside it, which is the whole of what it
1921    /// owes. A source that keeps them writes the task and the answers together, so a reader
1922    /// never finds one without the other.
1923    ///
1924    /// # Errors
1925    ///
1926    /// As [`write_task`](Self::write_task).
1927    async fn write_task_rendered(
1928        &self,
1929        write: &ItemWrite<Task>,
1930        answers: &BTreeMap<String, Value>,
1931    ) -> Result<NativeId, SourceError> {
1932        let _ = answers;
1933        self.write_task(write).await
1934    }
1935
1936    /// Create or update one document, on exactly the terms of
1937    /// [`write_task_rendered`](Self::write_task_rendered).
1938    ///
1939    /// # Errors
1940    ///
1941    /// As [`write_document`](Self::write_document).
1942    async fn write_document_rendered(
1943        &self,
1944        write: &ItemWrite<Document>,
1945        answers: &BTreeMap<String, Value>,
1946    ) -> Result<NativeId, SourceError> {
1947        let _ = answers;
1948        self.write_document(write).await
1949    }
1950
1951    /// Create or update one project, on exactly the terms of
1952    /// [`write_task_rendered`](Self::write_task_rendered).
1953    ///
1954    /// # Errors
1955    ///
1956    /// As [`write_project`](Self::write_project).
1957    async fn write_project_rendered(
1958        &self,
1959        write: &ItemWrite<Project>,
1960        answers: &BTreeMap<String, Value>,
1961    ) -> Result<NativeId, SourceError> {
1962        let _ = answers;
1963        self.write_project(write).await
1964    }
1965
1966    /// Replace one task's rendering — its content, byte for byte, its
1967    /// [`MetadataKey::TEMPLATE_KEY`] entry, set to `provenance`, and the answers it keeps
1968    /// beside the task where it keeps any — in one write, and change nothing else about it;
1969    /// or answer `None` when this source holds no such task.
1970    ///
1971    /// The content is [`Task::content`] exactly as a later read reports it, on the terms of
1972    /// [`set_task_content`](Self::set_task_content). Title, status, priority, labels, every
1973    /// other metadata entry, repositories, dependencies, [`Task::delivers`],
1974    /// [`Task::delivered_by`], project and comments are left exactly as they are. The write is
1975    /// one write: a reader sees the task as it was or as it is now, never a new content beside
1976    /// the old provenance or the old answers.
1977    ///
1978    /// Defaulted to [`unwritable_field`] on exactly the terms of
1979    /// [`set_task_status`](Self::set_task_status). A source declaring
1980    /// [`WriteSupport::Unsupported`] is never asked.
1981    ///
1982    /// [`Task::delivers`]: crate::Task::delivers
1983    /// [`Task::delivered_by`]: crate::Task::delivered_by
1984    ///
1985    /// # Errors
1986    ///
1987    /// Returns [`SourceError::Refused`] when this source cannot replace a task's rendering on
1988    /// its own, or cannot represent this one; and whatever else the source could not do the
1989    /// write for.
1990    async fn set_task_rendering(
1991        &self,
1992        id: &NativeId,
1993        content: &str,
1994        provenance: &Value,
1995        answers: &BTreeMap<String, Value>,
1996    ) -> Result<Option<()>, SourceError> {
1997        let _ = (id, content, provenance, answers);
1998        Err(unwritable_field(self.kind(), "rendering"))
1999    }
2000
2001    /// Replace one document's rendering, on exactly the terms of
2002    /// [`set_task_rendering`](Self::set_task_rendering). A source declaring
2003    /// [`Capabilities::documents`] unsupported is never asked.
2004    ///
2005    /// # Errors
2006    ///
2007    /// As [`set_task_rendering`](Self::set_task_rendering).
2008    async fn set_document_rendering(
2009        &self,
2010        id: &NativeId,
2011        content: &str,
2012        provenance: &Value,
2013        answers: &BTreeMap<String, Value>,
2014    ) -> Result<Option<()>, SourceError> {
2015        let _ = (id, content, provenance, answers);
2016        Err(SourceError::Refused {
2017            message: format!(
2018                "the {} plugin cannot write a document's rendering on its own",
2019                self.kind()
2020            ),
2021        })
2022    }
2023
2024    /// Replace one project's rendering, on exactly the terms of
2025    /// [`set_task_rendering`](Self::set_task_rendering): its content, its
2026    /// [`MetadataKey::TEMPLATE_KEY`] entry and the answers kept beside it change, and its
2027    /// title, status, labels, every other metadata entry, repositories and dependencies are
2028    /// left exactly as they are.
2029    ///
2030    /// # Errors
2031    ///
2032    /// As [`set_task_rendering`](Self::set_task_rendering).
2033    async fn set_project_rendering(
2034        &self,
2035        id: &NativeId,
2036        content: &str,
2037        provenance: &Value,
2038        answers: &BTreeMap<String, Value>,
2039    ) -> Result<Option<()>, SourceError> {
2040        let _ = (id, content, provenance, answers);
2041        Err(SourceError::Refused {
2042            message: format!(
2043                "the {} plugin cannot write a project's rendering on its own",
2044                self.kind()
2045            ),
2046        })
2047    }
2048
2049    /// The image assets the task `id` holds, or none when it holds none or this source holds
2050    /// no such task.
2051    ///
2052    /// Defaulted to none, which is what keeps assets an addition rather than a break: a source
2053    /// that keeps no assets needs no edit and reports every record as holding none. A source
2054    /// declaring [`Capabilities::assets`] native answers what it holds for the record, in any
2055    /// order — the engine orders them by the content's first reference.
2056    ///
2057    /// # Errors
2058    ///
2059    /// Returns a [`SourceError`] when the source could not answer.
2060    async fn task_assets(&self, id: &NativeId) -> Result<Vec<Asset>, SourceError> {
2061        let _ = id;
2062        Ok(Vec::new())
2063    }
2064
2065    /// The image assets the document `id` holds, on exactly the terms of
2066    /// [`task_assets`](Self::task_assets).
2067    ///
2068    /// # Errors
2069    ///
2070    /// As [`task_assets`](Self::task_assets).
2071    async fn document_assets(&self, id: &NativeId) -> Result<Vec<Asset>, SourceError> {
2072        let _ = id;
2073        Ok(Vec::new())
2074    }
2075
2076    /// The bytes of the asset `name` the task `id` holds, or `None` when it holds no such asset
2077    /// or this source holds no such task.
2078    ///
2079    /// Defaulted to `None`, on the terms of [`task_assets`](Self::task_assets).
2080    ///
2081    /// # Errors
2082    ///
2083    /// Returns a [`SourceError`] when the source could not answer.
2084    async fn task_asset(
2085        &self,
2086        id: &NativeId,
2087        name: &AssetName,
2088    ) -> Result<Option<Vec<u8>>, SourceError> {
2089        let _ = (id, name);
2090        Ok(None)
2091    }
2092
2093    /// The bytes of the asset `name` the document `id` holds, on exactly the terms of
2094    /// [`task_asset`](Self::task_asset).
2095    ///
2096    /// # Errors
2097    ///
2098    /// As [`task_asset`](Self::task_asset).
2099    async fn document_asset(
2100        &self,
2101        id: &NativeId,
2102        name: &AssetName,
2103    ) -> Result<Option<Vec<u8>>, SourceError> {
2104        let _ = (id, name);
2105        Ok(None)
2106    }
2107
2108    /// Create or update one task carrying image assets, in one write: the task as
2109    /// [`write_task`](Self::write_task) writes it — or, with `answers`, as
2110    /// [`write_task_rendered`](Self::write_task_rendered) does — and `assets` as the record's
2111    /// whole asset set, answering with where it landed and the content as stored.
2112    ///
2113    /// Only a source declaring [`Capabilities::assets`] native is asked, and the engine has
2114    /// already checked that every reference in the content names one of `assets` and every one
2115    /// of `assets` is referenced. A source that keeps the bytes beside the record stores each
2116    /// payload under its name, removes every asset the record held that `assets` does not
2117    /// name, and answers the content unchanged. A source that serves them at a URL uploads each
2118    /// payload that carries bytes, reuses the URL [`AssetWrite::recorded_assets`] records for
2119    /// each that does not, and writes the record through
2120    /// [`serve_asset_references`](crate::serve_asset_references) — so its references point at
2121    /// those URLs, its [`MetadataKey::ASSETS_KEY`] records each `{sha256, url}`, and a
2122    /// rendering's `body_digest` stays true of what landed — answering the content it wrote.
2123    ///
2124    /// Defaulted to [`assetless`], which is what a source with no assets answers.
2125    ///
2126    /// # Errors
2127    ///
2128    /// As [`write_task`](Self::write_task), and [`SourceError::Refused`] from a source that
2129    /// keeps no assets.
2130    async fn write_task_with_assets(
2131        &self,
2132        write: &ItemWrite<Task>,
2133        answers: Option<&BTreeMap<String, Value>>,
2134        assets: &AssetWrite,
2135    ) -> Result<AssetsWritten, SourceError> {
2136        let _ = (write, answers, assets);
2137        Err(assetless(self.kind()))
2138    }
2139
2140    /// Create or update one document carrying image assets, on exactly the terms of
2141    /// [`write_task_with_assets`](Self::write_task_with_assets).
2142    ///
2143    /// # Errors
2144    ///
2145    /// As [`write_task_with_assets`](Self::write_task_with_assets).
2146    async fn write_document_with_assets(
2147        &self,
2148        write: &ItemWrite<Document>,
2149        answers: Option<&BTreeMap<String, Value>>,
2150        assets: &AssetWrite,
2151    ) -> Result<AssetsWritten, SourceError> {
2152        let _ = (write, answers, assets);
2153        Err(assetless(self.kind()))
2154    }
2155
2156    /// Replace one task's rendering as [`set_task_rendering`](Self::set_task_rendering) does,
2157    /// and its asset set as [`write_task_with_assets`](Self::write_task_with_assets) does, in
2158    /// one write; or answer `None` when this source holds no such task.
2159    ///
2160    /// Defaulted to [`assetless`].
2161    ///
2162    /// # Errors
2163    ///
2164    /// As [`set_task_rendering`](Self::set_task_rendering), and [`SourceError::Refused`] from a
2165    /// source that keeps no assets.
2166    async fn set_task_rendering_with_assets(
2167        &self,
2168        id: &NativeId,
2169        content: &str,
2170        provenance: &Value,
2171        answers: &BTreeMap<String, Value>,
2172        assets: &AssetWrite,
2173    ) -> Result<Option<AssetsWritten>, SourceError> {
2174        let _ = (id, content, provenance, answers, assets);
2175        Err(assetless(self.kind()))
2176    }
2177
2178    /// Replace one document's rendering and its asset set, on exactly the terms of
2179    /// [`set_task_rendering_with_assets`](Self::set_task_rendering_with_assets).
2180    ///
2181    /// # Errors
2182    ///
2183    /// As [`set_task_rendering_with_assets`](Self::set_task_rendering_with_assets).
2184    async fn set_document_rendering_with_assets(
2185        &self,
2186        id: &NativeId,
2187        content: &str,
2188        provenance: &Value,
2189        answers: &BTreeMap<String, Value>,
2190        assets: &AssetWrite,
2191    ) -> Result<Option<AssetsWritten>, SourceError> {
2192        let _ = (id, content, provenance, answers, assets);
2193        Err(assetless(self.kind()))
2194    }
2195
2196    /// What this source has sent to its backend since it was built and what that spent, or
2197    /// `None` when it does not meter its own requests.
2198    ///
2199    /// Defaulted to `None`, which is what keeps metering an addition rather than a break: a
2200    /// source that does not count its requests needs no edit, and is reported as not
2201    /// metering rather than as having spent nothing. A source that answers owes a running
2202    /// total — see [`Metering`] — because what one command spent is read as the difference
2203    /// between two readings.
2204    ///
2205    /// # Errors
2206    ///
2207    /// Returns a [`SourceError`] when the reading itself could not be taken. A caller
2208    /// reports such a source as not metering; what a command cost is never a reason for the
2209    /// command to fail.
2210    async fn metering(&self) -> Result<Option<Metering>, SourceError> {
2211        Ok(None)
2212    }
2213
2214    /// What this source's backend says is left of each rate-limit window it meters this
2215    /// source's credential by — one [`QuotaReading`] per window, each as
2216    /// the backend reported it and never merged with another.
2217    ///
2218    /// Defaulted to empty, which is what a source with nothing to report — a folder of
2219    /// Markdown, an in-memory source — answers. A source asks its backend afresh each time
2220    /// rather than answering from anything it holds, and a reading costs nothing
2221    /// [`metering`](Self::metering) counts: what the store reports is the reading, and what it
2222    /// means is the caller's.
2223    ///
2224    /// # Errors
2225    ///
2226    /// Returns a [`SourceError`] when the reading itself could not be taken.
2227    async fn quota(&self) -> Result<Vec<QuotaReading>, SourceError> {
2228        Ok(Vec::new())
2229    }
2230
2231    /// End one command: drop everything held that a person can change.
2232    ///
2233    /// A command is one unit of work — one invocation of the binary, or whatever a caller
2234    /// holding one engine for many units of work calls between them. Within a command a
2235    /// source may hold what it read and reuse it; across this call it may not. After it
2236    /// returns, a source answers no read and bases no write on item content, statuses, board
2237    /// contents or search results it held before the call. It may keep only identifiers and
2238    /// vocabulary that stay valid in normal use — a repository's node id, a team's workflow
2239    /// states — and only where a lookup that misses one re-reads rather than refusing.
2240    ///
2241    /// Defaulted to doing nothing, which is right for a source that holds nothing between
2242    /// calls or holds only what the rule above lets it keep. A source that holds more owes
2243    /// an override. Never called by the engine on its own: the binary's one command is its
2244    /// whole process, so only a caller that outlives a command calls it.
2245    ///
2246    /// # Errors
2247    ///
2248    /// Returns a [`SourceError`] when the source could not be sure it dropped what it held —
2249    /// ordinarily a hosted plugin that did not answer. A caller should not go on to the next
2250    /// command on that source's earlier reads.
2251    async fn end_command(&self) -> Result<(), SourceError> {
2252        Ok(())
2253    }
2254
2255    /// Rewrite every item of this source whose stored form is one this source no longer writes
2256    /// into the form it writes now, changing nothing else about it. Under `dry_run`, send reads only
2257    /// and report what would be rewritten.
2258    ///
2259    /// What a read of each item gives back — its content, its metadata, every other field — is
2260    /// the same before and after: only the spelling the backend holds it in moves. An item already
2261    /// in the current form is counted in [`StoredFormMigration::current`] and sent nothing, so a
2262    /// second sweep rewrites nothing. An item the backend refuses is reported in
2263    /// [`StoredFormMigration::failed`] and the sweep goes on to the next.
2264    ///
2265    /// Defaulted to rewriting nothing, which is the answer of a source that has only ever written
2266    /// one form — and of a plugin served over the stdio protocol, which declares no such write and
2267    /// is never asked.
2268    ///
2269    /// # Errors
2270    ///
2271    /// Returns a [`SourceError`] when the source's items could not be listed, so the sweep could
2272    /// not say which of them it would have rewritten.
2273    async fn migrate_stored_forms(
2274        &self,
2275        dry_run: bool,
2276    ) -> Result<StoredFormMigration, SourceError> {
2277        let _ = dry_run;
2278        Ok(StoredFormMigration::default())
2279    }
2280
2281    /// Who can read where `target` lands, read live from the backend.
2282    ///
2283    /// This is the destination's reality, which the engine holds a declaration against
2284    /// before it lets a write through: a source a configuration declares private receives an
2285    /// item that may only be written somewhere private only while this answers
2286    /// [`Visibility::Private`]. The engine asks before the write it is about. A source must
2287    /// not answer from anything it read for an earlier write unless its backend's visibility
2288    /// cannot change in between — or the read was taken while the engine held this source's
2289    /// reads for one operation ([`hold_visibility`](Self::hold_visibility)), which a copy
2290    /// does so each destination is read once for the whole copy rather than once per write.
2291    ///
2292    /// Defaulted to [`Visibility::Unknown`], which is the answer of a source that cannot say
2293    /// and is never treated as private. A source on this machine answers `Private` — what it
2294    /// writes stays on the host — and a hosted source reads its backend.
2295    ///
2296    /// # Errors
2297    ///
2298    /// Returns a [`SourceError`] when the backend could not be asked or would not answer —
2299    /// a credential lacking the scope the read needs among them. An unreadable visibility is
2300    /// never guessed: the engine refuses the write.
2301    async fn visibility(&self, target: &WriteTarget<'_>) -> Result<Visibility, SourceError> {
2302        let _ = target;
2303        Ok(Visibility::Unknown)
2304    }
2305
2306    /// The repository a create of `target` would file its issue in, as a normalized origin,
2307    /// by the same rule the create itself applies — or `None` for a source that files no
2308    /// issue in a repository.
2309    ///
2310    /// Read-only: it writes nothing, and reads only what that rule reads — for a source whose
2311    /// rule looks at the project a new item is filed under, that project, and only when
2312    /// `target` names one. It answers where a *create* would file, so an
2313    /// [`WriteTarget::Existing`] target, which no create makes, answers `None`.
2314    ///
2315    /// Defaulted to `None`, the answer of every source that files no issue in a repository.
2316    ///
2317    /// # Errors
2318    ///
2319    /// Returns a [`SourceError`] when the create would be refused — refused as the create
2320    /// would refuse it — or the read the rule needs failed.
2321    async fn creation_repository(
2322        &self,
2323        target: &WriteTarget<'_>,
2324    ) -> Result<Option<Repository>, SourceError> {
2325        let _ = target;
2326        Ok(None)
2327    }
2328
2329    /// Take this source's exclusive, cross-process hold on the `record` `id`, waiting for a
2330    /// holder that is still at work and taking over one a dead process left — `true` once it is
2331    /// held, `false` for a source that offers no such hold. A caller releases it with
2332    /// [`Self::release_item`], always.
2333    ///
2334    /// What a copy decides its intent to create under: on a source that answers `true`, exactly
2335    /// one attempt on one host owns a create of the item. A hosted source has no lock to offer,
2336    /// and its intents are advisory. Defaulted to `false`.
2337    ///
2338    /// # Errors
2339    ///
2340    /// Returns a [`SourceError`] when the hold could not be taken.
2341    fn hold_item(&self, record: MetadataRecord, id: &NativeId) -> Result<bool, SourceError> {
2342        let _ = (record, id);
2343        Ok(false)
2344    }
2345
2346    /// Release the hold [`Self::hold_item`] took on the `record` `id`. Defaulted to nothing.
2347    fn release_item(&self, record: MetadataRecord, id: &NativeId) {
2348        let _ = (record, id);
2349    }
2350
2351    /// The `record` `id` exactly as this source stores it, byte for byte, when it can give that
2352    /// back with [`Self::restore_item`] — `None` otherwise. Read off this machine, never a
2353    /// request. Defaulted to `None`.
2354    fn item_snapshot(&self, record: MetadataRecord, id: &NativeId) -> Option<Vec<u8>> {
2355        let _ = (record, id);
2356        None
2357    }
2358
2359    /// Put the `record` `id` back to `snapshot`, byte for byte, under its hold: what a copy that
2360    /// took every write back leaves of an item it recorded an intent on. Defaulted to doing
2361    /// nothing, since a source answering no snapshot is never asked.
2362    ///
2363    /// # Errors
2364    ///
2365    /// Returns a [`SourceError`] when the item could not be put back.
2366    fn restore_item(
2367        &self,
2368        record: MetadataRecord,
2369        id: &NativeId,
2370        snapshot: &[u8],
2371    ) -> Result<(), SourceError> {
2372        let _ = (record, id, snapshot);
2373        Ok(())
2374    }
2375
2376    /// Remove one key of the metadata of the `record` `id` and change nothing else, answering
2377    /// the record's version token once it is gone — `Some(None)` when this source spells none —
2378    /// or `None` when this source holds no such record. Removing a key the record does not hold
2379    /// writes nothing.
2380    ///
2381    /// What a copy asks to take its intent to create — [`MetadataKey::CREATING_KEY`] — off a
2382    /// project or a document once the counterpart is linked. Defaulted for a task to
2383    /// [`Self::update_task`] removing the key, and for a project or a document to the refusal
2384    /// a source writing no metadata answers, which the engine meets by writing the record
2385    /// back whole without the key. A source that can take one key off narrowly owes an
2386    /// override.
2387    ///
2388    /// # Errors
2389    ///
2390    /// Returns [`SourceError::Refused`] when this source cannot remove the key on its own, and
2391    /// whatever else the source could not do the write for.
2392    async fn remove_record_metadata(
2393        &self,
2394        record: MetadataRecord,
2395        id: &NativeId,
2396        key: &MetadataKey,
2397    ) -> Result<Option<Option<String>>, SourceError> {
2398        if record != MetadataRecord::Task {
2399            return Err(crate::metadata::unwritable_metadata(self.kind(), record));
2400        }
2401        let mut update = TaskUpdate::default();
2402        update.metadata_remove.insert(key.clone());
2403        Ok(self
2404            .update_task(id, &update)
2405            .await?
2406            .map(|outcome| outcome.task.version))
2407    }
2408
2409    /// Every `record` this source holds whose create carried the create key `key` — see
2410    /// [`MetadataKey::CREATE_KEY`] — created at or after `since` when that is given: what a
2411    /// retried copy asks to find the item its earlier attempt created. `target` is the create
2412    /// the key was taken for, so a source filing creates in more than one place looks where
2413    /// that one would have landed.
2414    ///
2415    /// Read-only, and never through a search index: a source answers from where its creates
2416    /// land, by the key, so the answer is as fresh as [`Self::create_key_lags`] says. Defaulted
2417    /// to none, the answer of a source that keeps no such key — a retried copy then creates
2418    /// again, as it always did.
2419    ///
2420    /// # Errors
2421    ///
2422    /// Returns a [`SourceError`] when the lookup could not be made.
2423    async fn created_with_key(
2424        &self,
2425        record: MetadataRecord,
2426        key: &str,
2427        since: Option<chrono::DateTime<chrono::Utc>>,
2428        target: &WriteTarget<'_>,
2429    ) -> Result<Vec<NativeId>, SourceError> {
2430        let _ = (record, key, since, target);
2431        Ok(Vec::new())
2432    }
2433
2434    /// Whether [`Self::created_with_key`] can miss an item created moments ago — a hosted
2435    /// backend that lists a new item only after a delay — so a retry waits out the source's
2436    /// quiescence window before believing it absent. Defaulted to `false`.
2437    fn create_key_lags(&self) -> bool {
2438        false
2439    }
2440
2441    /// Why this source's own policy on where it creates would refuse a create of `target`,
2442    /// or `None` when it would not — asked before anything of the create is written, and by a
2443    /// read-only answer of where a copy would land.
2444    ///
2445    /// A refusal here is the source's configured restriction on the place a create would file
2446    /// in — a GitHub Projects source's `creation_owners` — and never a refusal of the item
2447    /// itself, which [`Self::check_task_write`] answers. It is answered rather than returned
2448    /// as an error so a caller that only reports where a create would go can say so without
2449    /// failing. Read-only, as [`Self::creation_repository`] is, and reading only what that
2450    /// rule reads; a source with no such restriction reads nothing at all.
2451    ///
2452    /// Defaulted to `None`, the answer of every source with no such policy.
2453    ///
2454    /// # Errors
2455    ///
2456    /// Returns a [`SourceError`] when the rule deciding where the create would file could not
2457    /// be applied — refused as the create would refuse it, or a read it needs failed.
2458    async fn creation_refusal(
2459        &self,
2460        target: &WriteTarget<'_>,
2461    ) -> Result<Option<String>, SourceError> {
2462        let _ = target;
2463        Ok(None)
2464    }
2465
2466    /// Read a create's visibility under a project this copy will create or update.
2467    ///
2468    /// `project` names the destination project, including a create whose id does not exist
2469    /// yet. Backends whose placement depends on its repository predict that repository
2470    /// with the same rule as the actual create. Other backends use `visibility` unchanged.
2471    ///
2472    /// # Errors
2473    /// Returns the same failures as [`visibility`](Self::visibility).
2474    async fn visibility_with_project(
2475        &self,
2476        target: &WriteTarget<'_>,
2477        project: &WriteTarget<'_>,
2478    ) -> Result<Visibility, SourceError> {
2479        let _ = project;
2480        self.visibility(target).await
2481    }
2482
2483    /// Told, once the configuration is read, who the configuration declares can read this
2484    /// source: [`Visibility::Private`] for a source declared `visibility: private`,
2485    /// [`Visibility::Public`] for one declared public, and [`Visibility::Unknown`] for one
2486    /// that declares nothing.
2487    ///
2488    /// A declaration, never the backend's reality, which [`visibility`](Self::visibility)
2489    /// reads. A source whose backend places a new item somewhere decided per item may place
2490    /// it differently on a source declared private — a GitHub board files an issue whose one
2491    /// named repository reads public in a private repository instead — and must place it
2492    /// exactly as before on every other. Defaulted to ignoring it, which is what every source
2493    /// that places an item the same way whoever may read it does.
2494    fn declare_visibility(&self, declared: Visibility) {
2495        let _ = declared;
2496    }
2497
2498    /// Run an operation with isolated visibility reads, including when operations overlap.
2499    ///
2500    /// The default executes the future unchanged. Backends that hold visibility reads may
2501    /// scope them to this future rather than sharing them with another operation.
2502    fn scope_visibility<'a>(
2503        &'a self,
2504        operation: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>>,
2505    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>> {
2506        operation
2507    }
2508
2509    /// Begin one engine operation's hold on what [`visibility`](Self::visibility) reads: from
2510    /// now until the matching [`release_visibility`](Self::release_visibility), a source may
2511    /// answer each destination from its first read in that hold rather than reading it again.
2512    ///
2513    /// Holds nest: only the release matching the outermost hold ends it, and that release
2514    /// drops everything read. A copy holds every source for the length of the copy, so a
2515    /// destination whose visibility changes during one copy is seen by the next. Defaulted to
2516    /// doing nothing, which is right for a source that reads nothing to answer.
2517    fn hold_visibility(&self) {}
2518
2519    /// End the hold [`hold_visibility`](Self::hold_visibility) began, dropping every
2520    /// visibility read in it once the outermost hold ends. Defaulted to doing nothing.
2521    fn release_visibility(&self) {}
2522}
2523
2524/// The factory that turns one configuration block into a live [`TaskSource`].
2525///
2526/// Having the compile-time registry and the subprocess seam be the same shape is
2527/// the whole reason this is a trait rather than a free function.
2528pub trait SourcePlugin: Send + Sync + 'static {
2529    /// The name a configuration document's `plugin:` field names.
2530    fn kind(&self) -> &'static str;
2531
2532    /// The JSON Schema for this plugin's own `config:` block.
2533    fn config_schema(&self) -> Schema;
2534
2535    /// Build a live source from one configuration block.
2536    ///
2537    /// `name` is the configured source's name, for error messages only — a
2538    /// plugin never learns it for any other purpose.
2539    ///
2540    /// # Errors
2541    ///
2542    /// Returns [`SourceError::Config`] when `config` is not valid for this
2543    /// plugin, or [`SourceError::Auth`] when a named credential is absent.
2544    fn build(
2545        &self,
2546        name: &SourceName,
2547        config: &serde_json::Value,
2548        secrets: &dyn SecretResolver,
2549    ) -> Result<Box<dyn TaskSource>, SourceError>;
2550
2551    /// Build a live source from one configuration block, handing it the clock it paces and
2552    /// backs off on.
2553    ///
2554    /// The binary builds every in-process source through this, with the process's one
2555    /// [`SharedClock`] — [`system_clock`](crate::system_clock) unless a test asked for
2556    /// simulated time. Defaulted to [`build`](Self::build), which ignores the clock: a plugin
2557    /// that never waits needs no edit, and one that does overrides this and routes its waits
2558    /// through `clock`.
2559    ///
2560    /// # Errors
2561    ///
2562    /// As [`build`](Self::build).
2563    fn build_with_clock(
2564        &self,
2565        name: &SourceName,
2566        config: &serde_json::Value,
2567        secrets: &dyn SecretResolver,
2568        clock: SharedClock,
2569    ) -> Result<Box<dyn TaskSource>, SourceError> {
2570        let _ = clock;
2571        self.build(name, config, secrets)
2572    }
2573
2574    /// The fields of this plugin's `config:` block that name a filesystem path, as dotted
2575    /// paths into that block.
2576    ///
2577    /// A relative value at one of these, **supplied by a configuration document**, is
2578    /// resolved against the directory holding that document before [`Self::build`] sees it;
2579    /// supplied through the environment or a flag it keeps resolving against the process
2580    /// working directory, because there is no document to rebase it on. A plugin is handed
2581    /// values and no origins, so this declaration is the only way it can say which of its
2582    /// own fields that rule reaches.
2583    ///
2584    /// Defaulted to none, which is what keeps this an addition rather than a break: a
2585    /// plugin whose block holds no path needs no edit, and a caller asks every plugin
2586    /// rather than keeping a table of which ones answer.
2587    // llmlint: ignore[invalid_states_unrepresentable] The identity of a configuration field
2588    // is a name, and no type can make a wrong one unrepresentable here: every string is a
2589    // syntactically valid dotted path, so a newtype would validate nothing and would only
2590    // move where a name that is not a field of *this* plugin is accepted. What decides that
2591    // is whether the name is a property of the schema `config_schema` publishes — a
2592    // per-plugin fact no shared type can hold — so the gate is per plugin and executable:
2593    // `document_relative_fields_are_fields_this_plugin_declares` in
2594    // `onetaskgraph-local-md/tests/plugin.rs`, which a plugin adding a declaration owes its
2595    // own copy of.
2596    fn document_relative_paths(&self) -> &'static [&'static str] {
2597        &[]
2598    }
2599
2600    /// What names the remote store a source built from `config` reads — a board's owner and
2601    /// number, a Linear endpoint and team — or `None` for a source with no remote.
2602    ///
2603    /// The store's local cache of a remote source lives under a digest of this, so every
2604    /// process configuring the same remote shares one cache and no two remotes share one.
2605    /// Defaulted to `None`, which is what a source keeping its work on this machine — a
2606    /// folder of Markdown — answers: it has nothing to cache, and its cache setting is
2607    /// ignored. A `config` this plugin would refuse answers `None` too.
2608    fn remote_identity(&self, config: &serde_json::Value) -> Option<String> {
2609        let _ = config;
2610        None
2611    }
2612}
2613
2614/// How a plugin reads the credential its configuration names.
2615///
2616/// A configuration document never carries a credential value, only the name of
2617/// the environment variable holding it.
2618pub trait SecretResolver: Send + Sync {
2619    /// The value of `var`, or `None` when nothing defines it.
2620    ///
2621    /// The returned value is never logged and never appears in `Debug` output.
2622    fn get(&self, var: &str) -> Option<SecretString>;
2623}