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::collections::BTreeMap;
4
5use schemars::{JsonSchema, Schema};
6use secrecy::SecretString;
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10use crate::{
11    Capabilities, Comment, CommentBody, DependencyEdge, Direction, Document, DocumentQuery,
12    ItemKind, ItemWrite, Label, MetadataKey, MetadataRecord, Metering, NativeId, NewComment, Page,
13    PageRequest, Priority, Project, ProjectQuery, SourceError, SourceName, Status, StatusCategory,
14    Task, TaskDetailRead, TaskQuery, TaskRef, TaskUpdate, TaskUpdateOutcome, WriteSupport,
15    commentless, documentless, unwritable, unwritable_field, unwritable_metadata,
16};
17
18/// Whether a source is answering right now.
19///
20/// # Placement is an open contract question
21///
22/// This type lives here because [`TaskSource::health`] returns it and the trait
23/// lives here: placing it in `onetaskgraph-core` would make this crate depend on
24/// the engine and invert the one direction the crate split exists to establish.
25/// The approved contract enumerates this crate's contents exhaustively and does
26/// not name `Health`, so the enumeration and the trait as written cannot both
27/// stand. Compiling forces the placement below; the resolution — add it to the
28/// enumeration, or redesign `health` so no such type crosses the boundary —
29/// belongs to the contract's owner, not to this crate. See `AGENTS.md`.
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
31// 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.
32pub struct Health {
33    /// Whether the source answered.
34    ///
35    /// A bare `bool` beside an untyped `detail` cannot say that an unreachable source
36    /// must explain itself, or keep "reachable with a warning" apart from "reachable";
37    /// an enum carrying the detail in its unreachable variant would.
38    // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this
39    // restates at this field the justification already recorded at
40    // `Capabilities.max_page_size` (capability.rs), `PageRequest.limit` (query.rs), this
41    // type's own doc comment above, and AGENTS.md's "Open contract question — `Health`":
42    // `Health`'s shape is approved contract text that `TaskSource::health` returns, so an
43    // enum here would change the serialized form and the trait six undispatched nodes
44    // implement. That is the contract owner's call, not this crate's.
45    // 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`".
46    pub reachable: bool,
47    /// What the source said, when it said anything useful.
48    pub detail: Option<String>,
49}
50
51/// One configured source, as the engine drives it.
52///
53/// Dyn-compatible through `async_trait` because the engine holds
54/// `Vec<Box<dyn TaskSource>>` over heterogeneous plugins.
55///
56/// Three rules bind every implementation, and the engine's compensation is only
57/// correct while all three hold:
58///
59/// 1. **Apply** every predicate you declare [`Support::Native`](crate::Support::Native).
60/// 2. **Ignore** every [`Support`](crate::Support)-typed predicate you declare
61///    `Unsupported` — return the *wider* result set, never a narrower one.
62///    Silently dropping rows for a predicate you did not declare is the one
63///    failure no test above the plugin can catch.
64/// 3. Never return a silently empty dependency read. Rule 2 reaches the
65///    `Support`-typed *predicates* alone; a dependency read is always real, and so is a
66///    document read — [`Capabilities::documents`] says whether this source has documents
67///    at all, and a source that says it has none is never asked for one rather than
68///    answering an empty page.
69#[async_trait::async_trait]
70pub trait TaskSource: Send + Sync {
71    /// The plugin kind that built this source, for display and for plan output.
72    fn kind(&self) -> &'static str;
73
74    /// What this source applies itself. Read once per query by the engine.
75    fn capabilities(&self) -> Capabilities;
76
77    /// Whether the source is answering right now.
78    ///
79    /// # Errors
80    ///
81    /// Returns a [`SourceError`] when the check itself could not be made.
82    async fn health(&self) -> Result<Health, SourceError>;
83
84    /// Fetch one task by its native id, or `None` when there is no such task.
85    ///
86    /// # Errors
87    ///
88    /// Returns a [`SourceError`] when the source could not answer.
89    async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError>;
90
91    /// Fetch several tasks by their native ids, each with the first page of its comments
92    /// when `comments` names the page to read — one answer per id, in the order they were
93    /// given.
94    ///
95    /// Each answer is what [`get_task`](Self::get_task) answers for that id, so a task that
96    /// is not there is `Ok(None)` and a read that failed fails that id alone. Its
97    /// [`TaskDetailRead::comments`] is what [`task_comments`](Self::task_comments) answers
98    /// for `comments`. The engine passes `comments` only to a source declaring
99    /// [`Capabilities::comments`](crate::Capabilities::comments) native.
100    ///
101    /// Defaulted to exactly those calls, item by item, so a source that implements nothing
102    /// here answers as it always did. A source that can read many items — or an item and its
103    /// comments — in fewer requests than that overrides it, which is the whole reason it
104    /// exists: a caller holding twenty ids pays for one batch rather than forty reads.
105    async fn get_task_details(
106        &self,
107        ids: &[NativeId],
108        comments: Option<&PageRequest>,
109    ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
110        let mut read = Vec::with_capacity(ids.len());
111        for id in ids {
112            read.push(match self.get_task(id).await {
113                Ok(Some(task)) => {
114                    let comments = match comments {
115                        Some(page) => Some(self.task_comments(id, page).await),
116                        None => None,
117                    };
118                    Ok(Some(TaskDetailRead { task, comments }))
119                }
120                Ok(None) => Ok(None),
121                Err(error) => Err(error),
122            });
123        }
124        read
125    }
126
127    /// Fetch one project by its native id, or `None` when there is no such project.
128    ///
129    /// # Errors
130    ///
131    /// Returns a [`SourceError`] when the source could not answer.
132    async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError>;
133
134    /// One page of the tasks matching `query`.
135    ///
136    /// # Errors
137    ///
138    /// Returns a [`SourceError`] when the source could not answer.
139    async fn query_tasks(
140        &self,
141        query: &TaskQuery,
142        page: &PageRequest,
143    ) -> Result<Page<Task>, SourceError>;
144
145    /// One page of the projects matching `query`.
146    ///
147    /// # Errors
148    ///
149    /// Returns a [`SourceError`] when the source could not answer.
150    async fn query_projects(
151        &self,
152        query: &ProjectQuery,
153        page: &PageRequest,
154    ) -> Result<Page<Project>, SourceError>;
155
156    /// One page of every label this source knows.
157    ///
158    /// # Errors
159    ///
160    /// Returns a [`SourceError`] when the source could not answer.
161    async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError>;
162
163    /// One page of the task dependency edges at `id`, in `direction`.
164    ///
165    /// # Errors
166    ///
167    /// Returns a [`SourceError`] when the source could not answer.
168    async fn task_dependencies(
169        &self,
170        id: &NativeId,
171        direction: Direction,
172        page: &PageRequest,
173    ) -> Result<Page<DependencyEdge>, SourceError>;
174
175    /// One page of the project dependency edges at `id`, in `direction`.
176    ///
177    /// # Errors
178    ///
179    /// Returns a [`SourceError`] when the source could not answer.
180    async fn project_dependencies(
181        &self,
182        id: &NativeId,
183        direction: Direction,
184        page: &PageRequest,
185    ) -> Result<Page<DependencyEdge>, SourceError>;
186
187    /// Whether this source can be written through at all.
188    ///
189    /// Defaulted to [`WriteSupport::Unsupported`], which is what keeps this a read
190    /// interface for every source that has nothing to write into: one that cannot be
191    /// written needs no edit and keeps working. Read before a write is attempted, so a
192    /// copy naming such a source as its destination is refused before anything is read.
193    fn writes(&self) -> WriteSupport {
194        WriteSupport::Unsupported
195    }
196
197    /// Create or update one task, answering with the native id the destination holds it
198    /// under.
199    ///
200    /// A source declaring [`WriteSupport::Supported`] owes three things here. It refuses,
201    /// naming the field, anything it cannot represent rather than dropping it — including
202    /// a metadata key it cannot carry, which it names. It writes every other field it was
203    /// given. And it never creates when [`ItemWrite::target`] names an item it does not
204    /// hold.
205    ///
206    /// # Errors
207    ///
208    /// Returns [`SourceError::Refused`] when this source has no write side, when a field
209    /// or a metadata key cannot be represented, or when `target` names nothing here; and
210    /// whatever else the source could not do the write for.
211    async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
212        let _ = write;
213        Err(unwritable(self.kind()))
214    }
215
216    /// Create or update one project, on exactly the terms of
217    /// [`write_task`](Self::write_task).
218    ///
219    /// # Errors
220    ///
221    /// As [`write_task`](Self::write_task).
222    async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
223        let _ = write;
224        Err(unwritable(self.kind()))
225    }
226
227    /// Whether a write of an item of `kind` at `category` — over the item `target` names, or
228    /// creating one when it is `None` — would have a status to write, asked before the write
229    /// and changing nothing.
230    ///
231    /// A caller that has to put an item back when a later write of it fails — a copy, whose
232    /// journal records what an item held before overwriting it — asks this first, so a status
233    /// this source has no name for is refused while nothing has been recorded or written, and
234    /// nothing has to be put back. It answers what the write itself would refuse a status
235    /// with, in the same words, and sends no request a write of that status would not have
236    /// sent anyway: what it reads to answer, it holds for the write that follows.
237    ///
238    /// Defaulted to `Ok(())`: a source that does not answer it in advance still refuses the
239    /// status in its write, exactly as before.
240    ///
241    /// # Errors
242    ///
243    /// Returns [`SourceError::Refused`] naming the kind, the category and what is missing
244    /// when this source has no name for that status; and whatever else kept it from finding
245    /// out.
246    async fn check_status_write(
247        &self,
248        kind: ItemKind,
249        category: StatusCategory,
250        target: Option<&NativeId>,
251    ) -> Result<(), SourceError> {
252        let _ = (kind, category, target);
253        Ok(())
254    }
255
256    /// Set the status of one task this source holds, and change nothing else about it,
257    /// answering with the status as this source now reads it — or `None` when this source
258    /// holds no such task.
259    ///
260    /// The category lands where this source's own mapping sends it, exactly as a
261    /// [`write_task`](Self::write_task) of a task in that category would: a category this
262    /// source has disabled is refused in the words a write of it is refused with. Title,
263    /// content, labels, metadata, dependencies, [`Task::delivers`], [`Task::delivered_by`],
264    /// project and comments are left exactly as they are.
265    ///
266    /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
267    /// break: a source that cannot write a status on its own needs no edit and refuses by
268    /// saying so. A source declaring [`WriteSupport::Unsupported`] is never asked.
269    ///
270    /// [`Task::delivers`]: crate::Task::delivers
271    /// [`Task::delivered_by`]: crate::Task::delivered_by
272    ///
273    /// # Errors
274    ///
275    /// Returns [`SourceError::Refused`] when this source cannot write a status, or cannot
276    /// write this one; and whatever else the source could not do the write for.
277    async fn set_task_status(
278        &self,
279        id: &NativeId,
280        category: StatusCategory,
281    ) -> Result<Option<Status>, SourceError> {
282        let _ = (id, category);
283        Err(unwritable_field(self.kind(), "status"))
284    }
285
286    /// Set the status of one task this source holds, as [`set_task_status`](Self::set_task_status)
287    /// does, and answer with the whole task as this source now reads it — its
288    /// [`Task::delivers`] among what a caller keeping delivered tasks in step needs — or `None`
289    /// when this source holds no such task.
290    ///
291    /// Defaulted to exactly the two calls a caller would otherwise make: [`get_task`] first,
292    /// answering `None` with nothing written when it does, then `set_task_status`, the status
293    /// it answers put on the task read. A source whose status write answers the whole task in
294    /// the same round trip overrides it to save the read.
295    ///
296    /// [`Task::delivers`]: crate::Task::delivers
297    /// [`get_task`]: Self::get_task
298    ///
299    /// # Errors
300    ///
301    /// As [`get_task`](Self::get_task) and [`set_task_status`](Self::set_task_status).
302    async fn set_task_status_reading(
303        &self,
304        id: &NativeId,
305        category: StatusCategory,
306    ) -> Result<Option<Task>, SourceError> {
307        let Some(mut task) = self.get_task(id).await? else {
308            return Ok(None);
309        };
310        let Some(status) = self.set_task_status(id, category).await? else {
311            return Ok(None);
312        };
313        task.status = status;
314        Ok(Some(task))
315    }
316
317    /// Set the priority of one task this source holds, and change nothing else about it,
318    /// answering with the priority as this source now reads it — or `None` when this source
319    /// holds no such task.
320    ///
321    /// [`Priority::None`] clears the priority. Title, content, status, labels, metadata,
322    /// repositories, dependencies and comments are left exactly as they are. Nothing about
323    /// the task's status moves, so the engine re-evaluates no delivered task after it.
324    ///
325    /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
326    /// break. A source declaring [`WriteSupport::Unsupported`], or declaring
327    /// [`Capabilities::priority`] unsupported, is never asked.
328    ///
329    /// # Errors
330    ///
331    /// Returns [`SourceError::Refused`] when this source cannot write a priority, or cannot
332    /// write this one — a board with no option for it, naming the option; and whatever else
333    /// the source could not do the write for.
334    async fn set_task_priority(
335        &self,
336        id: &NativeId,
337        priority: Priority,
338    ) -> Result<Option<Priority>, SourceError> {
339        let _ = (id, priority);
340        Err(unwritable_field(self.kind(), "priority"))
341    }
342
343    /// Replace the content of one task this source holds with `content`, byte for byte, and
344    /// change nothing else about it — or answer `None` when this source holds no such task.
345    ///
346    /// The content is [`Task::content`] exactly as this source reports it: what a later read
347    /// answers there is `content`. Where the source keeps something else inside the same
348    /// backend field — a metadata block in an issue body — that is kept as it was, and so is
349    /// every other member: title, status, priority, labels, metadata, repositories,
350    /// dependencies, project and comments. Nothing about the task's status moves, so the
351    /// engine re-evaluates no delivered task after it.
352    ///
353    /// Defaulted to [`unwritable_field`] on exactly the terms of
354    /// [`set_task_status`](Self::set_task_status). A source declaring
355    /// [`WriteSupport::Unsupported`] is never asked.
356    ///
357    /// # Errors
358    ///
359    /// Returns [`SourceError::Refused`] when this source cannot write a task's content on its
360    /// own, or cannot represent this one; and whatever else the source could not do the write
361    /// for.
362    async fn set_task_content(
363        &self,
364        id: &NativeId,
365        content: &str,
366    ) -> Result<Option<()>, SourceError> {
367        let _ = (id, content);
368        Err(unwritable_field(self.kind(), "content"))
369    }
370
371    /// Replace the [`Task::delivered_by`] of one task this source holds, and change nothing
372    /// else about it — or answer `None` when this source holds no such task.
373    ///
374    /// Every entry is a qualified id, and the list is the whole of it: what the task held
375    /// there before is replaced, not merged. It is the store's to keep in step — the engine
376    /// calls this whenever it writes a task's [`Task::delivers`] — and nothing a person types
377    /// reaches it directly.
378    ///
379    /// Defaulted to [`unwritable_field`] on exactly the terms of
380    /// [`set_task_status`](Self::set_task_status).
381    ///
382    /// [`Task::delivers`]: crate::Task::delivers
383    /// [`Task::delivered_by`]: crate::Task::delivered_by
384    ///
385    /// # Errors
386    ///
387    /// Returns [`SourceError::Refused`] when this source cannot hold the list, and whatever
388    /// else it could not do the write for.
389    async fn set_delivered_by(
390        &self,
391        id: &NativeId,
392        delivered_by: &[TaskRef],
393    ) -> Result<Option<()>, SourceError> {
394        let _ = (id, delivered_by);
395        Err(unwritable_field(self.kind(), "delivered_by"))
396    }
397
398    /// Set one key of the metadata of one task this source holds, and change nothing else
399    /// about it, answering with the task as this source reads it back after the write — or
400    /// `None` when this source holds no such task.
401    ///
402    /// The key is added when the task does not hold it and replaced when it does; every other
403    /// metadata key, and every other field of the task, is left exactly as it was. A `value`
404    /// the task already holds under `key` is a write that changes nothing, and a source owes
405    /// it no write at all. The answer is a read, not an echo: what the engine reports as the
406    /// value is what the returned task holds under `key`.
407    ///
408    /// Nothing about the task's status or its [`Task::delivers`] moves, so the engine
409    /// re-evaluates no delivered task after this write.
410    ///
411    /// Defaulted to [`unwritable_metadata`] on exactly the terms of
412    /// [`set_task_status`](Self::set_task_status): a source that cannot write one key on its
413    /// own needs no edit and refuses by saying so. A source declaring
414    /// [`WriteSupport::Unsupported`] is never asked.
415    ///
416    /// [`Task::delivers`]: crate::Task::delivers
417    ///
418    /// # Errors
419    ///
420    /// Returns [`SourceError::Refused`] when this source cannot write one key of a task's
421    /// metadata on its own, or cannot write this one without changing something else; and
422    /// whatever else the source could not do the write for.
423    async fn set_task_metadata(
424        &self,
425        id: &NativeId,
426        key: &MetadataKey,
427        value: &Value,
428    ) -> Result<Option<Task>, SourceError> {
429        let _ = (id, key, value);
430        Err(unwritable_metadata(self.kind(), MetadataRecord::Task))
431    }
432
433    /// Apply a targeted update to one task this source holds — every field `update` names, and
434    /// nothing else — answering with a [`TaskUpdateOutcome`], or `None` when this source holds
435    /// no such task.
436    ///
437    /// The outcome is everything the engine reports about the call, so it reads nothing of its
438    /// own: the task as this source reads it once the update landed — from the one read it made
439    /// and what it then wrote, where its backend answers a write with what it holds — the
440    /// fields it actually wrote, and the `delivers` the task held before.
441    ///
442    /// A field already holding the requested value is sent no write, and an update in which
443    /// nothing differs sends no write at all. Every field `update` leaves unnamed — labels,
444    /// repositories, project, [`Task::delivered_by`] and comments always among them — is left
445    /// exactly as it is. An update naming one metadata key both to set and to remove is refused
446    /// before anything is written, in the words of [`TaskUpdate::consistent`].
447    ///
448    /// Defaulted to [`TaskUpdate::rewrite`]: read the task, apply the update, and — only when
449    /// anything differs — [`write_task`](Self::write_task) it with its `target` set. That keeps
450    /// this an addition rather than a break, and a source that predates it behaves correctly and
451    /// is merely not minimal; one whose backend can take a field on its own owes an override
452    /// that sends only what differs. A source declaring [`WriteSupport::Unsupported`] is never
453    /// asked.
454    ///
455    /// [`Task::delivered_by`]: crate::Task::delivered_by
456    ///
457    /// # Errors
458    ///
459    /// Returns [`SourceError::Refused`] when the update contradicts itself, when a field it
460    /// names cannot be represented here — a category this source has disabled included — and
461    /// whatever else the source could not do the write for.
462    async fn update_task(
463        &self,
464        id: &NativeId,
465        update: &TaskUpdate,
466    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
467        update.rewrite(self, id).await
468    }
469
470    /// Set one key of the metadata of one project this source holds, on exactly the terms of
471    /// [`set_task_metadata`](Self::set_task_metadata).
472    ///
473    /// # Errors
474    ///
475    /// As [`set_task_metadata`](Self::set_task_metadata).
476    async fn set_project_metadata(
477        &self,
478        id: &NativeId,
479        key: &MetadataKey,
480        value: &Value,
481    ) -> Result<Option<Project>, SourceError> {
482        let _ = (id, key, value);
483        Err(unwritable_metadata(self.kind(), MetadataRecord::Project))
484    }
485
486    /// Set one key of the metadata of one document this source holds, on exactly the terms of
487    /// [`set_task_metadata`](Self::set_task_metadata).
488    ///
489    /// A source declaring [`Capabilities::documents`] unsupported is never asked, exactly as
490    /// it is never asked for a document read.
491    ///
492    /// # Errors
493    ///
494    /// As [`set_task_metadata`](Self::set_task_metadata).
495    async fn set_document_metadata(
496        &self,
497        id: &NativeId,
498        key: &MetadataKey,
499        value: &Value,
500    ) -> Result<Option<Document>, SourceError> {
501        let _ = (id, key, value);
502        Err(unwritable_metadata(self.kind(), MetadataRecord::Document))
503    }
504
505    /// Remove one task this destination holds, so a copy that could not finish can put
506    /// the destination back the way it found it.
507    ///
508    /// This is not a verb of the product: nothing a user types deletes anything, and a
509    /// copy never deletes an item it did not itself create in the run that is failing.
510    /// It exists because a copy is either complete or it never happened — a half-written
511    /// project has to be run again, and the re-run is the mutation burst that trips a
512    /// hosted destination's rate limiter. Undoing this run's own creates is what removes
513    /// that retry at source.
514    ///
515    /// A source declaring [`WriteSupport::Supported`] owes a real implementation, for the
516    /// reason it owes [`write_task`](Self::write_task) one: the engine will create items
517    /// there, so it has to be able to remove the ones it created. An `id` naming nothing
518    /// is **not** an error — the item is already gone, which is the state this asks for.
519    ///
520    /// # Errors
521    ///
522    /// Returns [`SourceError::Refused`] when this source has no write side, and whatever
523    /// else the source could not remove the item for.
524    async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
525        let _ = id;
526        Err(unwritable(self.kind()))
527    }
528
529    /// Remove one project this destination holds, on exactly the terms of
530    /// [`delete_task`](Self::delete_task).
531    ///
532    /// # Errors
533    ///
534    /// As [`delete_task`](Self::delete_task).
535    async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
536        let _ = id;
537        Err(unwritable(self.kind()))
538    }
539
540    /// Fetch one document by its native id, or `None` when there is no such document.
541    ///
542    /// Defaulted to [`documentless`], which is what keeps documents an addition rather
543    /// than a break: a source with none needs no edit, keeps working, and says so in the
544    /// same words every other document-free source does. A source that has documents
545    /// declares [`Support::Native`](crate::Support::Native) for
546    /// [`Capabilities::documents`] and owes a real implementation here, because that
547    /// declaration is what makes the engine ask.
548    ///
549    /// # Errors
550    ///
551    /// Returns [`SourceError::Refused`] when this source has no documents, and whatever
552    /// else the source could not answer for.
553    async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
554        let _ = id;
555        Err(documentless(self.kind()))
556    }
557
558    /// One page of the documents matching `query`.
559    ///
560    /// Defaulted on exactly the terms of [`get_document`](Self::get_document). A source
561    /// with no documents refuses rather than answering an empty page: an empty page reads
562    /// as a source that has documents and holds none matching, which is the one wrong
563    /// answer this method can give.
564    ///
565    /// # Errors
566    ///
567    /// As [`get_document`](Self::get_document).
568    async fn query_documents(
569        &self,
570        query: &DocumentQuery,
571        page: &PageRequest,
572    ) -> Result<Page<Document>, SourceError> {
573        let _ = (query, page);
574        Err(documentless(self.kind()))
575    }
576
577    /// Create or update one document, on exactly the terms of
578    /// [`write_task`](Self::write_task).
579    ///
580    /// # Errors
581    ///
582    /// As [`write_task`](Self::write_task).
583    async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
584        let _ = write;
585        Err(unwritable(self.kind()))
586    }
587
588    /// Remove one document this destination holds, on exactly the terms of
589    /// [`delete_task`](Self::delete_task).
590    ///
591    /// # Errors
592    ///
593    /// As [`delete_task`](Self::delete_task).
594    async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
595        let _ = id;
596        Err(unwritable(self.kind()))
597    }
598
599    /// One page of the comments on `task`, oldest first, or `None` when this source holds
600    /// no such task.
601    ///
602    /// Defaulted to [`commentless`], which is what keeps comments an addition rather than a
603    /// break: a source with none needs no edit and keeps working. A source whose tasks have
604    /// comments declares [`Support::Native`](crate::Support::Native) for
605    /// [`Capabilities::comments`] and owes a real implementation of all four comment methods,
606    /// because that declaration is what makes the engine ask.
607    ///
608    /// "No such task" is `None` rather than an error, exactly as it is for
609    /// [`get_task`](Self::get_task); a task that exists and has no comments is an empty page.
610    ///
611    /// # Errors
612    ///
613    /// Returns [`SourceError::Refused`] when this source has no comments, and whatever else
614    /// the source could not answer for.
615    async fn task_comments(
616        &self,
617        task: &NativeId,
618        page: &PageRequest,
619    ) -> Result<Option<Page<Comment>>, SourceError> {
620        let _ = (task, page);
621        Err(commentless(self.kind()))
622    }
623
624    /// Add one comment to `task`, answering with the comment as the source now holds it, or
625    /// `None` when this source holds no such task.
626    ///
627    /// The body is stored byte for byte. A source that records the author itself refuses a
628    /// [`NewComment::author`] rather than dropping it, naming why; a source that cannot
629    /// represent the body refuses it, naming why, rather than escaping it into something
630    /// else.
631    ///
632    /// # Errors
633    ///
634    /// Returns [`SourceError::Refused`] when this source has no comments or cannot be
635    /// written, when it cannot record what it was given, and whatever else it could not do
636    /// the write for.
637    async fn add_comment(
638        &self,
639        task: &NativeId,
640        comment: &NewComment,
641    ) -> Result<Option<Comment>, SourceError> {
642        let _ = (task, comment);
643        Err(commentless(self.kind()))
644    }
645
646    /// Replace the body of the comment `comment` on `task`, answering with the comment as the
647    /// source now holds it, or `None` when this source holds no such task or that task has no
648    /// such comment.
649    ///
650    /// Only the body and the time it last changed move: the id, the author and the time it
651    /// was written are the comment's own.
652    ///
653    /// # Errors
654    ///
655    /// As [`add_comment`](Self::add_comment).
656    async fn edit_comment(
657        &self,
658        task: &NativeId,
659        comment: &NativeId,
660        body: &CommentBody,
661    ) -> Result<Option<Comment>, SourceError> {
662        let _ = (task, comment, body);
663        Err(commentless(self.kind()))
664    }
665
666    /// Remove the comment `comment` from `task`, answering with the id it removed, or `None`
667    /// when this source holds no such task or that task has no such comment.
668    ///
669    /// Unlike [`delete_task`](Self::delete_task), this *is* a verb of the product — a person
670    /// removes a comment they posted — so a comment that is not there is reported as `None`
671    /// for the engine to refuse by name, rather than treated as already gone.
672    ///
673    /// # Errors
674    ///
675    /// As [`add_comment`](Self::add_comment).
676    async fn delete_comment(
677        &self,
678        task: &NativeId,
679        comment: &NativeId,
680    ) -> Result<Option<NativeId>, SourceError> {
681        let _ = (task, comment);
682        Err(commentless(self.kind()))
683    }
684
685    /// Whether this source keeps template answers beside its items at all.
686    ///
687    /// What lets a regenerate tell an item whose answers went missing — a block deleted by
688    /// hand, which the regenerate writes back — from an item of a source that never keeps any,
689    /// where a missing answer is no difference. Defaulted to `false`, as
690    /// [`task_template_answers`](Self::task_template_answers) is defaulted to `None`; a source
691    /// that keeps answers answers `true` here.
692    fn keeps_template_answers(&self) -> bool {
693        false
694    }
695
696    /// The template answers the task `id` was last rendered from, as this source keeps them
697    /// beside the task — or `None` when it keeps none for it, or holds no such task.
698    ///
699    /// Keeping answers is a source's own choice, never an obligation: a source whose items
700    /// are one record in a hosted system has no room beside the item that is not the item, and
701    /// answers written into its content or its metadata would duplicate what the content
702    /// already says. Defaulted to `None`, which is what keeps this an addition rather than a
703    /// break. A source that keeps them owes three things: they are in neither
704    /// [`Task::content`] nor [`Task::metadata`], they are written only by
705    /// [`write_task_rendered`](Self::write_task_rendered) and
706    /// [`set_task_rendering`](Self::set_task_rendering), and they come back here exactly as
707    /// they were written, JSON types intact.
708    ///
709    /// # Errors
710    ///
711    /// Returns a [`SourceError`] when the source could not answer, a record whose answers it
712    /// cannot read included.
713    async fn task_template_answers(
714        &self,
715        id: &NativeId,
716    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
717        let _ = id;
718        Ok(None)
719    }
720
721    /// The template answers the document `id` was last rendered from, on exactly the terms of
722    /// [`task_template_answers`](Self::task_template_answers).
723    ///
724    /// # Errors
725    ///
726    /// As [`task_template_answers`](Self::task_template_answers).
727    async fn document_template_answers(
728        &self,
729        id: &NativeId,
730    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
731        let _ = id;
732        Ok(None)
733    }
734
735    /// Create or update one task exactly as [`write_task`](Self::write_task) does, keeping
736    /// `answers` — the answers its content was rendered from — beside it in the same write
737    /// where this source keeps answers at all.
738    ///
739    /// The task arrives carrying its provenance under [`MetadataKey::TEMPLATE_KEY`] like any
740    /// other metadata entry. Defaulted to [`write_task`](Self::write_task) alone: a source that
741    /// keeps no answers writes the task and nothing beside it, which is the whole of what it
742    /// owes. A source that keeps them writes the task and the answers together, so a reader
743    /// never finds one without the other.
744    ///
745    /// # Errors
746    ///
747    /// As [`write_task`](Self::write_task).
748    async fn write_task_rendered(
749        &self,
750        write: &ItemWrite<Task>,
751        answers: &BTreeMap<String, Value>,
752    ) -> Result<NativeId, SourceError> {
753        let _ = answers;
754        self.write_task(write).await
755    }
756
757    /// Create or update one document, on exactly the terms of
758    /// [`write_task_rendered`](Self::write_task_rendered).
759    ///
760    /// # Errors
761    ///
762    /// As [`write_document`](Self::write_document).
763    async fn write_document_rendered(
764        &self,
765        write: &ItemWrite<Document>,
766        answers: &BTreeMap<String, Value>,
767    ) -> Result<NativeId, SourceError> {
768        let _ = answers;
769        self.write_document(write).await
770    }
771
772    /// Replace one task's rendering — its content, byte for byte, its
773    /// [`MetadataKey::TEMPLATE_KEY`] entry, set to `provenance`, and the answers it keeps
774    /// beside the task where it keeps any — in one write, and change nothing else about it;
775    /// or answer `None` when this source holds no such task.
776    ///
777    /// The content is [`Task::content`] exactly as a later read reports it, on the terms of
778    /// [`set_task_content`](Self::set_task_content). Title, status, priority, labels, every
779    /// other metadata entry, repositories, dependencies, [`Task::delivers`],
780    /// [`Task::delivered_by`], project and comments are left exactly as they are. The write is
781    /// one write: a reader sees the task as it was or as it is now, never a new content beside
782    /// the old provenance or the old answers.
783    ///
784    /// Defaulted to [`unwritable_field`] on exactly the terms of
785    /// [`set_task_status`](Self::set_task_status). A source declaring
786    /// [`WriteSupport::Unsupported`] is never asked.
787    ///
788    /// [`Task::delivers`]: crate::Task::delivers
789    /// [`Task::delivered_by`]: crate::Task::delivered_by
790    ///
791    /// # Errors
792    ///
793    /// Returns [`SourceError::Refused`] when this source cannot replace a task's rendering on
794    /// its own, or cannot represent this one; and whatever else the source could not do the
795    /// write for.
796    async fn set_task_rendering(
797        &self,
798        id: &NativeId,
799        content: &str,
800        provenance: &Value,
801        answers: &BTreeMap<String, Value>,
802    ) -> Result<Option<()>, SourceError> {
803        let _ = (id, content, provenance, answers);
804        Err(unwritable_field(self.kind(), "rendering"))
805    }
806
807    /// Replace one document's rendering, on exactly the terms of
808    /// [`set_task_rendering`](Self::set_task_rendering). A source declaring
809    /// [`Capabilities::documents`] unsupported is never asked.
810    ///
811    /// # Errors
812    ///
813    /// As [`set_task_rendering`](Self::set_task_rendering).
814    async fn set_document_rendering(
815        &self,
816        id: &NativeId,
817        content: &str,
818        provenance: &Value,
819        answers: &BTreeMap<String, Value>,
820    ) -> Result<Option<()>, SourceError> {
821        let _ = (id, content, provenance, answers);
822        Err(SourceError::Refused {
823            message: format!(
824                "the {} plugin cannot write a document's rendering on its own",
825                self.kind()
826            ),
827        })
828    }
829
830    /// What this source has sent to its backend since it was built and what that spent, or
831    /// `None` when it does not meter its own requests.
832    ///
833    /// Defaulted to `None`, which is what keeps metering an addition rather than a break: a
834    /// source that does not count its requests needs no edit, and is reported as not
835    /// metering rather than as having spent nothing. A source that answers owes a running
836    /// total — see [`Metering`] — because what one command spent is read as the difference
837    /// between two readings.
838    ///
839    /// # Errors
840    ///
841    /// Returns a [`SourceError`] when the reading itself could not be taken. A caller
842    /// reports such a source as not metering; what a command cost is never a reason for the
843    /// command to fail.
844    async fn metering(&self) -> Result<Option<Metering>, SourceError> {
845        Ok(None)
846    }
847}
848
849/// The factory that turns one configuration block into a live [`TaskSource`].
850///
851/// Having the compile-time registry and the subprocess seam be the same shape is
852/// the whole reason this is a trait rather than a free function.
853pub trait SourcePlugin: Send + Sync + 'static {
854    /// The name a configuration document's `plugin:` field names.
855    fn kind(&self) -> &'static str;
856
857    /// The JSON Schema for this plugin's own `config:` block.
858    fn config_schema(&self) -> Schema;
859
860    /// Build a live source from one configuration block.
861    ///
862    /// `name` is the configured source's name, for error messages only — a
863    /// plugin never learns it for any other purpose.
864    ///
865    /// # Errors
866    ///
867    /// Returns [`SourceError::Config`] when `config` is not valid for this
868    /// plugin, or [`SourceError::Auth`] when a named credential is absent.
869    fn build(
870        &self,
871        name: &SourceName,
872        config: &serde_json::Value,
873        secrets: &dyn SecretResolver,
874    ) -> Result<Box<dyn TaskSource>, SourceError>;
875
876    /// The fields of this plugin's `config:` block that name a filesystem path, as dotted
877    /// paths into that block.
878    ///
879    /// A relative value at one of these, **supplied by a configuration document**, is
880    /// resolved against the directory holding that document before [`Self::build`] sees it;
881    /// supplied through the environment or a flag it keeps resolving against the process
882    /// working directory, because there is no document to rebase it on. A plugin is handed
883    /// values and no origins, so this declaration is the only way it can say which of its
884    /// own fields that rule reaches.
885    ///
886    /// Defaulted to none, which is what keeps this an addition rather than a break: a
887    /// plugin whose block holds no path needs no edit, and a caller asks every plugin
888    /// rather than keeping a table of which ones answer.
889    // llmlint: ignore[invalid_states_unrepresentable] The identity of a configuration field
890    // is a name, and no type can make a wrong one unrepresentable here: every string is a
891    // syntactically valid dotted path, so a newtype would validate nothing and would only
892    // move where a name that is not a field of *this* plugin is accepted. What decides that
893    // is whether the name is a property of the schema `config_schema` publishes — a
894    // per-plugin fact no shared type can hold — so the gate is per plugin and executable:
895    // `document_relative_fields_are_fields_this_plugin_declares` in
896    // `onetaskgraph-local-md/tests/plugin.rs`, which a plugin adding a declaration owes its
897    // own copy of.
898    fn document_relative_paths(&self) -> &'static [&'static str] {
899        &[]
900    }
901}
902
903/// How a plugin reads the credential its configuration names.
904///
905/// A configuration document never carries a credential value, only the name of
906/// the environment variable holding it.
907pub trait SecretResolver: Send + Sync {
908    /// The value of `var`, or `None` when nothing defines it.
909    ///
910    /// The returned value is never logged and never appears in `Debug` output.
911    fn get(&self, var: &str) -> Option<SecretString>;
912}