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