Skip to main content

onetaskgraph_plugin_api/
source.rs

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