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