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    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    /// Set the status of one task this source holds, and change nothing else about it,
228    /// answering with the status as this source now reads it — or `None` when this source
229    /// holds no such task.
230    ///
231    /// The category lands where this source's own mapping sends it, exactly as a
232    /// [`write_task`](Self::write_task) of a task in that category would: a category this
233    /// source has disabled is refused in the words a write of it is refused with. Title,
234    /// content, labels, metadata, dependencies, [`Task::delivers`], [`Task::delivered_by`],
235    /// project and comments are left exactly as they are.
236    ///
237    /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
238    /// break: a source that cannot write a status on its own needs no edit and refuses by
239    /// saying so. A source declaring [`WriteSupport::Unsupported`] is never asked.
240    ///
241    /// [`Task::delivers`]: crate::Task::delivers
242    /// [`Task::delivered_by`]: crate::Task::delivered_by
243    ///
244    /// # Errors
245    ///
246    /// Returns [`SourceError::Refused`] when this source cannot write a status, or cannot
247    /// write this one; and whatever else the source could not do the write for.
248    async fn set_task_status(
249        &self,
250        id: &NativeId,
251        category: StatusCategory,
252    ) -> Result<Option<Status>, SourceError> {
253        let _ = (id, category);
254        Err(unwritable_field(self.kind(), "status"))
255    }
256
257    /// Set the priority of one task this source holds, and change nothing else about it,
258    /// answering with the priority as this source now reads it — or `None` when this source
259    /// holds no such task.
260    ///
261    /// [`Priority::None`] clears the priority. Title, content, status, labels, metadata,
262    /// repositories, dependencies and comments are left exactly as they are. Nothing about
263    /// the task's status moves, so the engine re-evaluates no delivered task after it.
264    ///
265    /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
266    /// break. A source declaring [`WriteSupport::Unsupported`], or declaring
267    /// [`Capabilities::priority`] unsupported, is never asked.
268    ///
269    /// # Errors
270    ///
271    /// Returns [`SourceError::Refused`] when this source cannot write a priority, or cannot
272    /// write this one — a board with no option for it, naming the option; and whatever else
273    /// the source could not do the write for.
274    async fn set_task_priority(
275        &self,
276        id: &NativeId,
277        priority: Priority,
278    ) -> Result<Option<Priority>, SourceError> {
279        let _ = (id, priority);
280        Err(unwritable_field(self.kind(), "priority"))
281    }
282
283    /// Replace the content of one task this source holds with `content`, byte for byte, and
284    /// change nothing else about it — or answer `None` when this source holds no such task.
285    ///
286    /// The content is [`Task::content`] exactly as this source reports it: what a later read
287    /// answers there is `content`. Where the source keeps something else inside the same
288    /// backend field — a metadata block in an issue body — that is kept as it was, and so is
289    /// every other member: title, status, priority, labels, metadata, repositories,
290    /// dependencies, project and comments. Nothing about the task's status moves, so the
291    /// engine re-evaluates no delivered task after it.
292    ///
293    /// Defaulted to [`unwritable_field`] on exactly the terms of
294    /// [`set_task_status`](Self::set_task_status). A source declaring
295    /// [`WriteSupport::Unsupported`] is never asked.
296    ///
297    /// # Errors
298    ///
299    /// Returns [`SourceError::Refused`] when this source cannot write a task's content on its
300    /// own, or cannot represent this one; and whatever else the source could not do the write
301    /// for.
302    async fn set_task_content(
303        &self,
304        id: &NativeId,
305        content: &str,
306    ) -> Result<Option<()>, SourceError> {
307        let _ = (id, content);
308        Err(unwritable_field(self.kind(), "content"))
309    }
310
311    /// Replace the [`Task::delivered_by`] of one task this source holds, and change nothing
312    /// else about it — or answer `None` when this source holds no such task.
313    ///
314    /// Every entry is a qualified id, and the list is the whole of it: what the task held
315    /// there before is replaced, not merged. It is the store's to keep in step — the engine
316    /// calls this whenever it writes a task's [`Task::delivers`] — and nothing a person types
317    /// reaches it directly.
318    ///
319    /// Defaulted to [`unwritable_field`] on exactly the terms of
320    /// [`set_task_status`](Self::set_task_status).
321    ///
322    /// [`Task::delivers`]: crate::Task::delivers
323    /// [`Task::delivered_by`]: crate::Task::delivered_by
324    ///
325    /// # Errors
326    ///
327    /// Returns [`SourceError::Refused`] when this source cannot hold the list, and whatever
328    /// else it could not do the write for.
329    async fn set_delivered_by(
330        &self,
331        id: &NativeId,
332        delivered_by: &[TaskRef],
333    ) -> Result<Option<()>, SourceError> {
334        let _ = (id, delivered_by);
335        Err(unwritable_field(self.kind(), "delivered_by"))
336    }
337
338    /// Set one key of the metadata of one task this source holds, and change nothing else
339    /// about it, answering with the task as this source reads it back after the write — or
340    /// `None` when this source holds no such task.
341    ///
342    /// The key is added when the task does not hold it and replaced when it does; every other
343    /// metadata key, and every other field of the task, is left exactly as it was. A `value`
344    /// the task already holds under `key` is a write that changes nothing, and a source owes
345    /// it no write at all. The answer is a read, not an echo: what the engine reports as the
346    /// value is what the returned task holds under `key`.
347    ///
348    /// Nothing about the task's status or its [`Task::delivers`] moves, so the engine
349    /// re-evaluates no delivered task after this write.
350    ///
351    /// Defaulted to [`unwritable_metadata`] on exactly the terms of
352    /// [`set_task_status`](Self::set_task_status): a source that cannot write one key on its
353    /// own needs no edit and refuses by saying so. A source declaring
354    /// [`WriteSupport::Unsupported`] is never asked.
355    ///
356    /// [`Task::delivers`]: crate::Task::delivers
357    ///
358    /// # Errors
359    ///
360    /// Returns [`SourceError::Refused`] when this source cannot write one key of a task's
361    /// metadata on its own, or cannot write this one without changing something else; and
362    /// whatever else the source could not do the write for.
363    async fn set_task_metadata(
364        &self,
365        id: &NativeId,
366        key: &MetadataKey,
367        value: &Value,
368    ) -> Result<Option<Task>, SourceError> {
369        let _ = (id, key, value);
370        Err(unwritable_metadata(self.kind(), MetadataRecord::Task))
371    }
372
373    /// Apply a targeted update to one task this source holds — every field `update` names, and
374    /// nothing else — answering with a [`TaskUpdateOutcome`], or `None` when this source holds
375    /// no such task.
376    ///
377    /// The outcome is everything the engine reports about the call, so it reads nothing of its
378    /// own: the task as this source reads it once the update landed — from the one read it made
379    /// and what it then wrote, where its backend answers a write with what it holds — the
380    /// fields it actually wrote, and the `delivers` the task held before.
381    ///
382    /// A field already holding the requested value is sent no write, and an update in which
383    /// nothing differs sends no write at all. Every field `update` leaves unnamed — labels,
384    /// repositories, project, [`Task::delivered_by`] and comments always among them — is left
385    /// exactly as it is. An update naming one metadata key both to set and to remove is refused
386    /// before anything is written, in the words of [`TaskUpdate::consistent`].
387    ///
388    /// Defaulted to [`TaskUpdate::rewrite`]: read the task, apply the update, and — only when
389    /// anything differs — [`write_task`](Self::write_task) it with its `target` set. That keeps
390    /// this an addition rather than a break, and a source that predates it behaves correctly and
391    /// is merely not minimal; one whose backend can take a field on its own owes an override
392    /// that sends only what differs. A source declaring [`WriteSupport::Unsupported`] is never
393    /// asked.
394    ///
395    /// [`Task::delivered_by`]: crate::Task::delivered_by
396    ///
397    /// # Errors
398    ///
399    /// Returns [`SourceError::Refused`] when the update contradicts itself, when a field it
400    /// names cannot be represented here — a category this source has disabled included — and
401    /// whatever else the source could not do the write for.
402    async fn update_task(
403        &self,
404        id: &NativeId,
405        update: &TaskUpdate,
406    ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
407        update.rewrite(self, id).await
408    }
409
410    /// Set one key of the metadata of one project this source holds, on exactly the terms of
411    /// [`set_task_metadata`](Self::set_task_metadata).
412    ///
413    /// # Errors
414    ///
415    /// As [`set_task_metadata`](Self::set_task_metadata).
416    async fn set_project_metadata(
417        &self,
418        id: &NativeId,
419        key: &MetadataKey,
420        value: &Value,
421    ) -> Result<Option<Project>, SourceError> {
422        let _ = (id, key, value);
423        Err(unwritable_metadata(self.kind(), MetadataRecord::Project))
424    }
425
426    /// Set one key of the metadata of one document this source holds, on exactly the terms of
427    /// [`set_task_metadata`](Self::set_task_metadata).
428    ///
429    /// A source declaring [`Capabilities::documents`] unsupported is never asked, exactly as
430    /// it is never asked for a document read.
431    ///
432    /// # Errors
433    ///
434    /// As [`set_task_metadata`](Self::set_task_metadata).
435    async fn set_document_metadata(
436        &self,
437        id: &NativeId,
438        key: &MetadataKey,
439        value: &Value,
440    ) -> Result<Option<Document>, SourceError> {
441        let _ = (id, key, value);
442        Err(unwritable_metadata(self.kind(), MetadataRecord::Document))
443    }
444
445    /// Remove one task this destination holds, so a copy that could not finish can put
446    /// the destination back the way it found it.
447    ///
448    /// This is not a verb of the product: nothing a user types deletes anything, and a
449    /// copy never deletes an item it did not itself create in the run that is failing.
450    /// It exists because a copy is either complete or it never happened — a half-written
451    /// project has to be run again, and the re-run is the mutation burst that trips a
452    /// hosted destination's rate limiter. Undoing this run's own creates is what removes
453    /// that retry at source.
454    ///
455    /// A source declaring [`WriteSupport::Supported`] owes a real implementation, for the
456    /// reason it owes [`write_task`](Self::write_task) one: the engine will create items
457    /// there, so it has to be able to remove the ones it created. An `id` naming nothing
458    /// is **not** an error — the item is already gone, which is the state this asks for.
459    ///
460    /// # Errors
461    ///
462    /// Returns [`SourceError::Refused`] when this source has no write side, and whatever
463    /// else the source could not remove the item for.
464    async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
465        let _ = id;
466        Err(unwritable(self.kind()))
467    }
468
469    /// Remove one project this destination holds, on exactly the terms of
470    /// [`delete_task`](Self::delete_task).
471    ///
472    /// # Errors
473    ///
474    /// As [`delete_task`](Self::delete_task).
475    async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
476        let _ = id;
477        Err(unwritable(self.kind()))
478    }
479
480    /// Fetch one document by its native id, or `None` when there is no such document.
481    ///
482    /// Defaulted to [`documentless`], which is what keeps documents an addition rather
483    /// than a break: a source with none needs no edit, keeps working, and says so in the
484    /// same words every other document-free source does. A source that has documents
485    /// declares [`Support::Native`](crate::Support::Native) for
486    /// [`Capabilities::documents`] and owes a real implementation here, because that
487    /// declaration is what makes the engine ask.
488    ///
489    /// # Errors
490    ///
491    /// Returns [`SourceError::Refused`] when this source has no documents, and whatever
492    /// else the source could not answer for.
493    async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
494        let _ = id;
495        Err(documentless(self.kind()))
496    }
497
498    /// One page of the documents matching `query`.
499    ///
500    /// Defaulted on exactly the terms of [`get_document`](Self::get_document). A source
501    /// with no documents refuses rather than answering an empty page: an empty page reads
502    /// as a source that has documents and holds none matching, which is the one wrong
503    /// answer this method can give.
504    ///
505    /// # Errors
506    ///
507    /// As [`get_document`](Self::get_document).
508    async fn query_documents(
509        &self,
510        query: &DocumentQuery,
511        page: &PageRequest,
512    ) -> Result<Page<Document>, SourceError> {
513        let _ = (query, page);
514        Err(documentless(self.kind()))
515    }
516
517    /// Create or update one document, on exactly the terms of
518    /// [`write_task`](Self::write_task).
519    ///
520    /// # Errors
521    ///
522    /// As [`write_task`](Self::write_task).
523    async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
524        let _ = write;
525        Err(unwritable(self.kind()))
526    }
527
528    /// Remove one document this destination holds, on exactly the terms of
529    /// [`delete_task`](Self::delete_task).
530    ///
531    /// # Errors
532    ///
533    /// As [`delete_task`](Self::delete_task).
534    async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
535        let _ = id;
536        Err(unwritable(self.kind()))
537    }
538
539    /// One page of the comments on `task`, oldest first, or `None` when this source holds
540    /// no such task.
541    ///
542    /// Defaulted to [`commentless`], which is what keeps comments an addition rather than a
543    /// break: a source with none needs no edit and keeps working. A source whose tasks have
544    /// comments declares [`Support::Native`](crate::Support::Native) for
545    /// [`Capabilities::comments`] and owes a real implementation of all four comment methods,
546    /// because that declaration is what makes the engine ask.
547    ///
548    /// "No such task" is `None` rather than an error, exactly as it is for
549    /// [`get_task`](Self::get_task); a task that exists and has no comments is an empty page.
550    ///
551    /// # Errors
552    ///
553    /// Returns [`SourceError::Refused`] when this source has no comments, and whatever else
554    /// the source could not answer for.
555    async fn task_comments(
556        &self,
557        task: &NativeId,
558        page: &PageRequest,
559    ) -> Result<Option<Page<Comment>>, SourceError> {
560        let _ = (task, page);
561        Err(commentless(self.kind()))
562    }
563
564    /// Add one comment to `task`, answering with the comment as the source now holds it, or
565    /// `None` when this source holds no such task.
566    ///
567    /// The body is stored byte for byte. A source that records the author itself refuses a
568    /// [`NewComment::author`] rather than dropping it, naming why; a source that cannot
569    /// represent the body refuses it, naming why, rather than escaping it into something
570    /// else.
571    ///
572    /// # Errors
573    ///
574    /// Returns [`SourceError::Refused`] when this source has no comments or cannot be
575    /// written, when it cannot record what it was given, and whatever else it could not do
576    /// the write for.
577    async fn add_comment(
578        &self,
579        task: &NativeId,
580        comment: &NewComment,
581    ) -> Result<Option<Comment>, SourceError> {
582        let _ = (task, comment);
583        Err(commentless(self.kind()))
584    }
585
586    /// Replace the body of the comment `comment` on `task`, answering with the comment as the
587    /// source now holds it, or `None` when this source holds no such task or that task has no
588    /// such comment.
589    ///
590    /// Only the body and the time it last changed move: the id, the author and the time it
591    /// was written are the comment's own.
592    ///
593    /// # Errors
594    ///
595    /// As [`add_comment`](Self::add_comment).
596    async fn edit_comment(
597        &self,
598        task: &NativeId,
599        comment: &NativeId,
600        body: &CommentBody,
601    ) -> Result<Option<Comment>, SourceError> {
602        let _ = (task, comment, body);
603        Err(commentless(self.kind()))
604    }
605
606    /// Remove the comment `comment` from `task`, answering with the id it removed, or `None`
607    /// when this source holds no such task or that task has no such comment.
608    ///
609    /// Unlike [`delete_task`](Self::delete_task), this *is* a verb of the product — a person
610    /// removes a comment they posted — so a comment that is not there is reported as `None`
611    /// for the engine to refuse by name, rather than treated as already gone.
612    ///
613    /// # Errors
614    ///
615    /// As [`add_comment`](Self::add_comment).
616    async fn delete_comment(
617        &self,
618        task: &NativeId,
619        comment: &NativeId,
620    ) -> Result<Option<NativeId>, SourceError> {
621        let _ = (task, comment);
622        Err(commentless(self.kind()))
623    }
624
625    /// Whether this source keeps template answers beside its items at all.
626    ///
627    /// What lets a regenerate tell an item whose answers went missing — a block deleted by
628    /// hand, which the regenerate writes back — from an item of a source that never keeps any,
629    /// where a missing answer is no difference. Defaulted to `false`, as
630    /// [`task_template_answers`](Self::task_template_answers) is defaulted to `None`; a source
631    /// that keeps answers answers `true` here.
632    fn keeps_template_answers(&self) -> bool {
633        false
634    }
635
636    /// The template answers the task `id` was last rendered from, as this source keeps them
637    /// beside the task — or `None` when it keeps none for it, or holds no such task.
638    ///
639    /// Keeping answers is a source's own choice, never an obligation: a source whose items
640    /// are one record in a hosted system has no room beside the item that is not the item, and
641    /// answers written into its content or its metadata would duplicate what the content
642    /// already says. Defaulted to `None`, which is what keeps this an addition rather than a
643    /// break. A source that keeps them owes three things: they are in neither
644    /// [`Task::content`] nor [`Task::metadata`], they are written only by
645    /// [`write_task_rendered`](Self::write_task_rendered) and
646    /// [`set_task_rendering`](Self::set_task_rendering), and they come back here exactly as
647    /// they were written, JSON types intact.
648    ///
649    /// # Errors
650    ///
651    /// Returns a [`SourceError`] when the source could not answer, a record whose answers it
652    /// cannot read included.
653    async fn task_template_answers(
654        &self,
655        id: &NativeId,
656    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
657        let _ = id;
658        Ok(None)
659    }
660
661    /// The template answers the document `id` was last rendered from, on exactly the terms of
662    /// [`task_template_answers`](Self::task_template_answers).
663    ///
664    /// # Errors
665    ///
666    /// As [`task_template_answers`](Self::task_template_answers).
667    async fn document_template_answers(
668        &self,
669        id: &NativeId,
670    ) -> Result<Option<BTreeMap<String, Value>>, SourceError> {
671        let _ = id;
672        Ok(None)
673    }
674
675    /// Create or update one task exactly as [`write_task`](Self::write_task) does, keeping
676    /// `answers` — the answers its content was rendered from — beside it in the same write
677    /// where this source keeps answers at all.
678    ///
679    /// The task arrives carrying its provenance under [`MetadataKey::TEMPLATE_KEY`] like any
680    /// other metadata entry. Defaulted to [`write_task`](Self::write_task) alone: a source that
681    /// keeps no answers writes the task and nothing beside it, which is the whole of what it
682    /// owes. A source that keeps them writes the task and the answers together, so a reader
683    /// never finds one without the other.
684    ///
685    /// # Errors
686    ///
687    /// As [`write_task`](Self::write_task).
688    async fn write_task_rendered(
689        &self,
690        write: &ItemWrite<Task>,
691        answers: &BTreeMap<String, Value>,
692    ) -> Result<NativeId, SourceError> {
693        let _ = answers;
694        self.write_task(write).await
695    }
696
697    /// Create or update one document, on exactly the terms of
698    /// [`write_task_rendered`](Self::write_task_rendered).
699    ///
700    /// # Errors
701    ///
702    /// As [`write_document`](Self::write_document).
703    async fn write_document_rendered(
704        &self,
705        write: &ItemWrite<Document>,
706        answers: &BTreeMap<String, Value>,
707    ) -> Result<NativeId, SourceError> {
708        let _ = answers;
709        self.write_document(write).await
710    }
711
712    /// Replace one task's rendering — its content, byte for byte, its
713    /// [`MetadataKey::TEMPLATE_KEY`] entry, set to `provenance`, and the answers it keeps
714    /// beside the task where it keeps any — in one write, and change nothing else about it;
715    /// or answer `None` when this source holds no such task.
716    ///
717    /// The content is [`Task::content`] exactly as a later read reports it, on the terms of
718    /// [`set_task_content`](Self::set_task_content). Title, status, priority, labels, every
719    /// other metadata entry, repositories, dependencies, [`Task::delivers`],
720    /// [`Task::delivered_by`], project and comments are left exactly as they are. The write is
721    /// one write: a reader sees the task as it was or as it is now, never a new content beside
722    /// the old provenance or the old answers.
723    ///
724    /// Defaulted to [`unwritable_field`] on exactly the terms of
725    /// [`set_task_status`](Self::set_task_status). A source declaring
726    /// [`WriteSupport::Unsupported`] is never asked.
727    ///
728    /// [`Task::delivers`]: crate::Task::delivers
729    /// [`Task::delivered_by`]: crate::Task::delivered_by
730    ///
731    /// # Errors
732    ///
733    /// Returns [`SourceError::Refused`] when this source cannot replace a task's rendering on
734    /// its own, or cannot represent this one; and whatever else the source could not do the
735    /// write for.
736    async fn set_task_rendering(
737        &self,
738        id: &NativeId,
739        content: &str,
740        provenance: &Value,
741        answers: &BTreeMap<String, Value>,
742    ) -> Result<Option<()>, SourceError> {
743        let _ = (id, content, provenance, answers);
744        Err(unwritable_field(self.kind(), "rendering"))
745    }
746
747    /// Replace one document's rendering, on exactly the terms of
748    /// [`set_task_rendering`](Self::set_task_rendering). A source declaring
749    /// [`Capabilities::documents`] unsupported is never asked.
750    ///
751    /// # Errors
752    ///
753    /// As [`set_task_rendering`](Self::set_task_rendering).
754    async fn set_document_rendering(
755        &self,
756        id: &NativeId,
757        content: &str,
758        provenance: &Value,
759        answers: &BTreeMap<String, Value>,
760    ) -> Result<Option<()>, SourceError> {
761        let _ = (id, content, provenance, answers);
762        Err(SourceError::Refused {
763            message: format!(
764                "the {} plugin cannot write a document's rendering on its own",
765                self.kind()
766            ),
767        })
768    }
769
770    /// What this source has sent to its backend since it was built and what that spent, or
771    /// `None` when it does not meter its own requests.
772    ///
773    /// Defaulted to `None`, which is what keeps metering an addition rather than a break: a
774    /// source that does not count its requests needs no edit, and is reported as not
775    /// metering rather than as having spent nothing. A source that answers owes a running
776    /// total — see [`Metering`] — because what one command spent is read as the difference
777    /// between two readings.
778    ///
779    /// # Errors
780    ///
781    /// Returns a [`SourceError`] when the reading itself could not be taken. A caller
782    /// reports such a source as not metering; what a command cost is never a reason for the
783    /// command to fail.
784    async fn metering(&self) -> Result<Option<Metering>, SourceError> {
785        Ok(None)
786    }
787}
788
789/// The factory that turns one configuration block into a live [`TaskSource`].
790///
791/// Having the compile-time registry and the subprocess seam be the same shape is
792/// the whole reason this is a trait rather than a free function.
793pub trait SourcePlugin: Send + Sync + 'static {
794    /// The name a configuration document's `plugin:` field names.
795    fn kind(&self) -> &'static str;
796
797    /// The JSON Schema for this plugin's own `config:` block.
798    fn config_schema(&self) -> Schema;
799
800    /// Build a live source from one configuration block.
801    ///
802    /// `name` is the configured source's name, for error messages only — a
803    /// plugin never learns it for any other purpose.
804    ///
805    /// # Errors
806    ///
807    /// Returns [`SourceError::Config`] when `config` is not valid for this
808    /// plugin, or [`SourceError::Auth`] when a named credential is absent.
809    fn build(
810        &self,
811        name: &SourceName,
812        config: &serde_json::Value,
813        secrets: &dyn SecretResolver,
814    ) -> Result<Box<dyn TaskSource>, SourceError>;
815
816    /// The fields of this plugin's `config:` block that name a filesystem path, as dotted
817    /// paths into that block.
818    ///
819    /// A relative value at one of these, **supplied by a configuration document**, is
820    /// resolved against the directory holding that document before [`Self::build`] sees it;
821    /// supplied through the environment or a flag it keeps resolving against the process
822    /// working directory, because there is no document to rebase it on. A plugin is handed
823    /// values and no origins, so this declaration is the only way it can say which of its
824    /// own fields that rule reaches.
825    ///
826    /// Defaulted to none, which is what keeps this an addition rather than a break: a
827    /// plugin whose block holds no path needs no edit, and a caller asks every plugin
828    /// rather than keeping a table of which ones answer.
829    // llmlint: ignore[invalid_states_unrepresentable] The identity of a configuration field
830    // is a name, and no type can make a wrong one unrepresentable here: every string is a
831    // syntactically valid dotted path, so a newtype would validate nothing and would only
832    // move where a name that is not a field of *this* plugin is accepted. What decides that
833    // is whether the name is a property of the schema `config_schema` publishes — a
834    // per-plugin fact no shared type can hold — so the gate is per plugin and executable:
835    // `document_relative_fields_are_fields_this_plugin_declares` in
836    // `onetaskgraph-local-md/tests/plugin.rs`, which a plugin adding a declaration owes its
837    // own copy of.
838    fn document_relative_paths(&self) -> &'static [&'static str] {
839        &[]
840    }
841}
842
843/// How a plugin reads the credential its configuration names.
844///
845/// A configuration document never carries a credential value, only the name of
846/// the environment variable holding it.
847pub trait SecretResolver: Send + Sync {
848    /// The value of `var`, or `None` when nothing defines it.
849    ///
850    /// The returned value is never logged and never appears in `Debug` output.
851    fn get(&self, var: &str) -> Option<SecretString>;
852}