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 schemars::{JsonSchema, Schema};
4use secrecy::SecretString;
5use serde::{Deserialize, Serialize};
6
7use crate::{
8    Capabilities, Comment, CommentBody, DependencyEdge, Direction, Document, DocumentQuery,
9    ItemWrite, Label, Metering, NativeId, NewComment, Page, PageRequest, Project, ProjectQuery,
10    SourceError, SourceName, Status, StatusCategory, Task, TaskQuery, TaskRef, WriteSupport,
11    commentless, documentless, unwritable, unwritable_field,
12};
13
14/// Whether a source is answering right now.
15///
16/// # Placement is an open contract question
17///
18/// This type lives here because [`TaskSource::health`] returns it and the trait
19/// lives here: placing it in `onetaskgraph-core` would make this crate depend on
20/// the engine and invert the one direction the crate split exists to establish.
21/// The approved contract enumerates this crate's contents exhaustively and does
22/// not name `Health`, so the enumeration and the trait as written cannot both
23/// stand. Compiling forces the placement below; the resolution — add it to the
24/// enumeration, or redesign `health` so no such type crosses the boundary —
25/// belongs to the contract's owner, not to this crate. See `AGENTS.md`.
26#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
27// 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.
28pub struct Health {
29    /// Whether the source answered.
30    ///
31    /// A bare `bool` beside an untyped `detail` cannot say that an unreachable source
32    /// must explain itself, or keep "reachable with a warning" apart from "reachable";
33    /// an enum carrying the detail in its unreachable variant would.
34    // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this
35    // restates at this field the justification already recorded at
36    // `Capabilities.max_page_size` (capability.rs), `PageRequest.limit` (query.rs), this
37    // type's own doc comment above, and AGENTS.md's "Open contract question — `Health`":
38    // `Health`'s shape is approved contract text that `TaskSource::health` returns, so an
39    // enum here would change the serialized form and the trait six undispatched nodes
40    // implement. That is the contract owner's call, not this crate's.
41    // 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`".
42    pub reachable: bool,
43    /// What the source said, when it said anything useful.
44    pub detail: Option<String>,
45}
46
47/// One configured source, as the engine drives it.
48///
49/// Dyn-compatible through `async_trait` because the engine holds
50/// `Vec<Box<dyn TaskSource>>` over heterogeneous plugins.
51///
52/// Three rules bind every implementation, and the engine's compensation is only
53/// correct while all three hold:
54///
55/// 1. **Apply** every predicate you declare [`Support::Native`](crate::Support::Native).
56/// 2. **Ignore** every [`Support`](crate::Support)-typed predicate you declare
57///    `Unsupported` — return the *wider* result set, never a narrower one.
58///    Silently dropping rows for a predicate you did not declare is the one
59///    failure no test above the plugin can catch.
60/// 3. Never return a silently empty dependency read. Rule 2 reaches the
61///    `Support`-typed *predicates* alone; a dependency read is always real, and so is a
62///    document read — [`Capabilities::documents`] says whether this source has documents
63///    at all, and a source that says it has none is never asked for one rather than
64///    answering an empty page.
65#[async_trait::async_trait]
66pub trait TaskSource: Send + Sync {
67    /// The plugin kind that built this source, for display and for plan output.
68    fn kind(&self) -> &'static str;
69
70    /// What this source applies itself. Read once per query by the engine.
71    fn capabilities(&self) -> Capabilities;
72
73    /// Whether the source is answering right now.
74    ///
75    /// # Errors
76    ///
77    /// Returns a [`SourceError`] when the check itself could not be made.
78    async fn health(&self) -> Result<Health, SourceError>;
79
80    /// Fetch one task by its native id, or `None` when there is no such task.
81    ///
82    /// # Errors
83    ///
84    /// Returns a [`SourceError`] when the source could not answer.
85    async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError>;
86
87    /// Fetch one project by its native id, or `None` when there is no such project.
88    ///
89    /// # Errors
90    ///
91    /// Returns a [`SourceError`] when the source could not answer.
92    async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError>;
93
94    /// One page of the tasks matching `query`.
95    ///
96    /// # Errors
97    ///
98    /// Returns a [`SourceError`] when the source could not answer.
99    async fn query_tasks(
100        &self,
101        query: &TaskQuery,
102        page: &PageRequest,
103    ) -> Result<Page<Task>, SourceError>;
104
105    /// One page of the projects matching `query`.
106    ///
107    /// # Errors
108    ///
109    /// Returns a [`SourceError`] when the source could not answer.
110    async fn query_projects(
111        &self,
112        query: &ProjectQuery,
113        page: &PageRequest,
114    ) -> Result<Page<Project>, SourceError>;
115
116    /// One page of every label this source knows.
117    ///
118    /// # Errors
119    ///
120    /// Returns a [`SourceError`] when the source could not answer.
121    async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError>;
122
123    /// One page of the task dependency edges at `id`, in `direction`.
124    ///
125    /// # Errors
126    ///
127    /// Returns a [`SourceError`] when the source could not answer.
128    async fn task_dependencies(
129        &self,
130        id: &NativeId,
131        direction: Direction,
132        page: &PageRequest,
133    ) -> Result<Page<DependencyEdge>, SourceError>;
134
135    /// One page of the project dependency edges at `id`, in `direction`.
136    ///
137    /// # Errors
138    ///
139    /// Returns a [`SourceError`] when the source could not answer.
140    async fn project_dependencies(
141        &self,
142        id: &NativeId,
143        direction: Direction,
144        page: &PageRequest,
145    ) -> Result<Page<DependencyEdge>, SourceError>;
146
147    /// Whether this source can be written through at all.
148    ///
149    /// Defaulted to [`WriteSupport::Unsupported`], which is what keeps this a read
150    /// interface for every source that has nothing to write into: one that cannot be
151    /// written needs no edit and keeps working. Read before a write is attempted, so a
152    /// copy naming such a source as its destination is refused before anything is read.
153    fn writes(&self) -> WriteSupport {
154        WriteSupport::Unsupported
155    }
156
157    /// Create or update one task, answering with the native id the destination holds it
158    /// under.
159    ///
160    /// A source declaring [`WriteSupport::Supported`] owes three things here. It refuses,
161    /// naming the field, anything it cannot represent rather than dropping it — including
162    /// a metadata key it cannot carry, which it names. It writes every other field it was
163    /// given. And it never creates when [`ItemWrite::target`] names an item it does not
164    /// hold.
165    ///
166    /// # Errors
167    ///
168    /// Returns [`SourceError::Refused`] when this source has no write side, when a field
169    /// or a metadata key cannot be represented, or when `target` names nothing here; and
170    /// whatever else the source could not do the write for.
171    async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
172        let _ = write;
173        Err(unwritable(self.kind()))
174    }
175
176    /// Create or update one project, on exactly the terms of
177    /// [`write_task`](Self::write_task).
178    ///
179    /// # Errors
180    ///
181    /// As [`write_task`](Self::write_task).
182    async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
183        let _ = write;
184        Err(unwritable(self.kind()))
185    }
186
187    /// Set the status of one task this source holds, and change nothing else about it,
188    /// answering with the status as this source now reads it — or `None` when this source
189    /// holds no such task.
190    ///
191    /// The category lands where this source's own mapping sends it, exactly as a
192    /// [`write_task`](Self::write_task) of a task in that category would: a category this
193    /// source has disabled is refused in the words a write of it is refused with. Title,
194    /// content, labels, metadata, dependencies, [`Task::delivers`], [`Task::delivered_by`],
195    /// project and comments are left exactly as they are.
196    ///
197    /// Defaulted to [`unwritable_field`], which is what keeps this an addition rather than a
198    /// break: a source that cannot write a status on its own needs no edit and refuses by
199    /// saying so. A source declaring [`WriteSupport::Unsupported`] is never asked.
200    ///
201    /// [`Task::delivers`]: crate::Task::delivers
202    /// [`Task::delivered_by`]: crate::Task::delivered_by
203    ///
204    /// # Errors
205    ///
206    /// Returns [`SourceError::Refused`] when this source cannot write a status, or cannot
207    /// write this one; and whatever else the source could not do the write for.
208    async fn set_task_status(
209        &self,
210        id: &NativeId,
211        category: StatusCategory,
212    ) -> Result<Option<Status>, SourceError> {
213        let _ = (id, category);
214        Err(unwritable_field(self.kind(), "status"))
215    }
216
217    /// Replace the [`Task::delivered_by`] of one task this source holds, and change nothing
218    /// else about it — or answer `None` when this source holds no such task.
219    ///
220    /// Every entry is a qualified id, and the list is the whole of it: what the task held
221    /// there before is replaced, not merged. It is the store's to keep in step — the engine
222    /// calls this whenever it writes a task's [`Task::delivers`] — and nothing a person types
223    /// reaches it directly.
224    ///
225    /// Defaulted to [`unwritable_field`] on exactly the terms of
226    /// [`set_task_status`](Self::set_task_status).
227    ///
228    /// [`Task::delivers`]: crate::Task::delivers
229    /// [`Task::delivered_by`]: crate::Task::delivered_by
230    ///
231    /// # Errors
232    ///
233    /// Returns [`SourceError::Refused`] when this source cannot hold the list, and whatever
234    /// else it could not do the write for.
235    async fn set_delivered_by(
236        &self,
237        id: &NativeId,
238        delivered_by: &[TaskRef],
239    ) -> Result<Option<()>, SourceError> {
240        let _ = (id, delivered_by);
241        Err(unwritable_field(self.kind(), "delivered_by"))
242    }
243
244    /// Remove one task this destination holds, so a copy that could not finish can put
245    /// the destination back the way it found it.
246    ///
247    /// This is not a verb of the product: nothing a user types deletes anything, and a
248    /// copy never deletes an item it did not itself create in the run that is failing.
249    /// It exists because a copy is either complete or it never happened — a half-written
250    /// project has to be run again, and the re-run is the mutation burst that trips a
251    /// hosted destination's rate limiter. Undoing this run's own creates is what removes
252    /// that retry at source.
253    ///
254    /// A source declaring [`WriteSupport::Supported`] owes a real implementation, for the
255    /// reason it owes [`write_task`](Self::write_task) one: the engine will create items
256    /// there, so it has to be able to remove the ones it created. An `id` naming nothing
257    /// is **not** an error — the item is already gone, which is the state this asks for.
258    ///
259    /// # Errors
260    ///
261    /// Returns [`SourceError::Refused`] when this source has no write side, and whatever
262    /// else the source could not remove the item for.
263    async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
264        let _ = id;
265        Err(unwritable(self.kind()))
266    }
267
268    /// Remove one project this destination holds, on exactly the terms of
269    /// [`delete_task`](Self::delete_task).
270    ///
271    /// # Errors
272    ///
273    /// As [`delete_task`](Self::delete_task).
274    async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
275        let _ = id;
276        Err(unwritable(self.kind()))
277    }
278
279    /// Fetch one document by its native id, or `None` when there is no such document.
280    ///
281    /// Defaulted to [`documentless`], which is what keeps documents an addition rather
282    /// than a break: a source with none needs no edit, keeps working, and says so in the
283    /// same words every other document-free source does. A source that has documents
284    /// declares [`Support::Native`](crate::Support::Native) for
285    /// [`Capabilities::documents`] and owes a real implementation here, because that
286    /// declaration is what makes the engine ask.
287    ///
288    /// # Errors
289    ///
290    /// Returns [`SourceError::Refused`] when this source has no documents, and whatever
291    /// else the source could not answer for.
292    async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
293        let _ = id;
294        Err(documentless(self.kind()))
295    }
296
297    /// One page of the documents matching `query`.
298    ///
299    /// Defaulted on exactly the terms of [`get_document`](Self::get_document). A source
300    /// with no documents refuses rather than answering an empty page: an empty page reads
301    /// as a source that has documents and holds none matching, which is the one wrong
302    /// answer this method can give.
303    ///
304    /// # Errors
305    ///
306    /// As [`get_document`](Self::get_document).
307    async fn query_documents(
308        &self,
309        query: &DocumentQuery,
310        page: &PageRequest,
311    ) -> Result<Page<Document>, SourceError> {
312        let _ = (query, page);
313        Err(documentless(self.kind()))
314    }
315
316    /// Create or update one document, on exactly the terms of
317    /// [`write_task`](Self::write_task).
318    ///
319    /// # Errors
320    ///
321    /// As [`write_task`](Self::write_task).
322    async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
323        let _ = write;
324        Err(unwritable(self.kind()))
325    }
326
327    /// Remove one document this destination holds, on exactly the terms of
328    /// [`delete_task`](Self::delete_task).
329    ///
330    /// # Errors
331    ///
332    /// As [`delete_task`](Self::delete_task).
333    async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
334        let _ = id;
335        Err(unwritable(self.kind()))
336    }
337
338    /// One page of the comments on `task`, oldest first, or `None` when this source holds
339    /// no such task.
340    ///
341    /// Defaulted to [`commentless`], which is what keeps comments an addition rather than a
342    /// break: a source with none needs no edit and keeps working. A source whose tasks have
343    /// comments declares [`Support::Native`](crate::Support::Native) for
344    /// [`Capabilities::comments`] and owes a real implementation of all four comment methods,
345    /// because that declaration is what makes the engine ask.
346    ///
347    /// "No such task" is `None` rather than an error, exactly as it is for
348    /// [`get_task`](Self::get_task); a task that exists and has no comments is an empty page.
349    ///
350    /// # Errors
351    ///
352    /// Returns [`SourceError::Refused`] when this source has no comments, and whatever else
353    /// the source could not answer for.
354    async fn task_comments(
355        &self,
356        task: &NativeId,
357        page: &PageRequest,
358    ) -> Result<Option<Page<Comment>>, SourceError> {
359        let _ = (task, page);
360        Err(commentless(self.kind()))
361    }
362
363    /// Add one comment to `task`, answering with the comment as the source now holds it, or
364    /// `None` when this source holds no such task.
365    ///
366    /// The body is stored byte for byte. A source that records the author itself refuses a
367    /// [`NewComment::author`] rather than dropping it, naming why; a source that cannot
368    /// represent the body refuses it, naming why, rather than escaping it into something
369    /// else.
370    ///
371    /// # Errors
372    ///
373    /// Returns [`SourceError::Refused`] when this source has no comments or cannot be
374    /// written, when it cannot record what it was given, and whatever else it could not do
375    /// the write for.
376    async fn add_comment(
377        &self,
378        task: &NativeId,
379        comment: &NewComment,
380    ) -> Result<Option<Comment>, SourceError> {
381        let _ = (task, comment);
382        Err(commentless(self.kind()))
383    }
384
385    /// Replace the body of the comment `comment` on `task`, answering with the comment as the
386    /// source now holds it, or `None` when this source holds no such task or that task has no
387    /// such comment.
388    ///
389    /// Only the body and the time it last changed move: the id, the author and the time it
390    /// was written are the comment's own.
391    ///
392    /// # Errors
393    ///
394    /// As [`add_comment`](Self::add_comment).
395    async fn edit_comment(
396        &self,
397        task: &NativeId,
398        comment: &NativeId,
399        body: &CommentBody,
400    ) -> Result<Option<Comment>, SourceError> {
401        let _ = (task, comment, body);
402        Err(commentless(self.kind()))
403    }
404
405    /// Remove the comment `comment` from `task`, answering with the id it removed, or `None`
406    /// when this source holds no such task or that task has no such comment.
407    ///
408    /// Unlike [`delete_task`](Self::delete_task), this *is* a verb of the product — a person
409    /// removes a comment they posted — so a comment that is not there is reported as `None`
410    /// for the engine to refuse by name, rather than treated as already gone.
411    ///
412    /// # Errors
413    ///
414    /// As [`add_comment`](Self::add_comment).
415    async fn delete_comment(
416        &self,
417        task: &NativeId,
418        comment: &NativeId,
419    ) -> Result<Option<NativeId>, SourceError> {
420        let _ = (task, comment);
421        Err(commentless(self.kind()))
422    }
423
424    /// What this source has sent to its backend since it was built and what that spent, or
425    /// `None` when it does not meter its own requests.
426    ///
427    /// Defaulted to `None`, which is what keeps metering an addition rather than a break: a
428    /// source that does not count its requests needs no edit, and is reported as not
429    /// metering rather than as having spent nothing. A source that answers owes a running
430    /// total — see [`Metering`] — because what one command spent is read as the difference
431    /// between two readings.
432    ///
433    /// # Errors
434    ///
435    /// Returns a [`SourceError`] when the reading itself could not be taken. A caller
436    /// reports such a source as not metering; what a command cost is never a reason for the
437    /// command to fail.
438    async fn metering(&self) -> Result<Option<Metering>, SourceError> {
439        Ok(None)
440    }
441}
442
443/// The factory that turns one configuration block into a live [`TaskSource`].
444///
445/// Having the compile-time registry and the subprocess seam be the same shape is
446/// the whole reason this is a trait rather than a free function.
447pub trait SourcePlugin: Send + Sync + 'static {
448    /// The name a configuration document's `plugin:` field names.
449    fn kind(&self) -> &'static str;
450
451    /// The JSON Schema for this plugin's own `config:` block.
452    fn config_schema(&self) -> Schema;
453
454    /// Build a live source from one configuration block.
455    ///
456    /// `name` is the configured source's name, for error messages only — a
457    /// plugin never learns it for any other purpose.
458    ///
459    /// # Errors
460    ///
461    /// Returns [`SourceError::Config`] when `config` is not valid for this
462    /// plugin, or [`SourceError::Auth`] when a named credential is absent.
463    fn build(
464        &self,
465        name: &SourceName,
466        config: &serde_json::Value,
467        secrets: &dyn SecretResolver,
468    ) -> Result<Box<dyn TaskSource>, SourceError>;
469
470    /// The fields of this plugin's `config:` block that name a filesystem path, as dotted
471    /// paths into that block.
472    ///
473    /// A relative value at one of these, **supplied by a configuration document**, is
474    /// resolved against the directory holding that document before [`Self::build`] sees it;
475    /// supplied through the environment or a flag it keeps resolving against the process
476    /// working directory, because there is no document to rebase it on. A plugin is handed
477    /// values and no origins, so this declaration is the only way it can say which of its
478    /// own fields that rule reaches.
479    ///
480    /// Defaulted to none, which is what keeps this an addition rather than a break: a
481    /// plugin whose block holds no path needs no edit, and a caller asks every plugin
482    /// rather than keeping a table of which ones answer.
483    // llmlint: ignore[invalid_states_unrepresentable] The identity of a configuration field
484    // is a name, and no type can make a wrong one unrepresentable here: every string is a
485    // syntactically valid dotted path, so a newtype would validate nothing and would only
486    // move where a name that is not a field of *this* plugin is accepted. What decides that
487    // is whether the name is a property of the schema `config_schema` publishes — a
488    // per-plugin fact no shared type can hold — so the gate is per plugin and executable:
489    // `document_relative_fields_are_fields_this_plugin_declares` in
490    // `onetaskgraph-local-md/tests/plugin.rs`, which a plugin adding a declaration owes its
491    // own copy of.
492    fn document_relative_paths(&self) -> &'static [&'static str] {
493        &[]
494    }
495}
496
497/// How a plugin reads the credential its configuration names.
498///
499/// A configuration document never carries a credential value, only the name of
500/// the environment variable holding it.
501pub trait SecretResolver: Send + Sync {
502    /// The value of `var`, or `None` when nothing defines it.
503    ///
504    /// The returned value is never logged and never appears in `Debug` output.
505    fn get(&self, var: &str) -> Option<SecretString>;
506}