checkpoint

⚒️ Generated with [Fabro](https://fabro.sh)
This commit is contained in:
Fabro 2026-05-24 21:01:43 -04:00
parent eea6420ea4
commit fb40fe9787
6 changed files with 2200 additions and 14 deletions

568
run.json

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,882 @@
diff --git a/Cargo.lock b/Cargo.lock
index 5949b1eca..be8dfb7eb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1769,7 +1769,6 @@ dependencies = [
name = "fabro-automation"
version = "0.243.0-nightly.1"
dependencies = [
- "chrono",
"croner",
"hex",
"serde",
diff --git a/lib/crates/fabro-api/tests/automation_round_trip.rs b/lib/crates/fabro-api/tests/automation_round_trip.rs
index 0e8c738ca..5f228c525 100644
--- a/lib/crates/fabro-api/tests/automation_round_trip.rs
+++ b/lib/crates/fabro-api/tests/automation_round_trip.rs
@@ -27,7 +27,7 @@ fn automation_api_reuses_domain_types() {
fn automation_json_matches_openapi_shape() {
let automation = Automation {
id: "nightly-deps".parse().unwrap(),
- revision: AutomationRevision::from_str("abc123").unwrap(),
+ revision: AutomationRevision::from_raw("abc123"),
name: "Nightly dependency update".to_string(),
description: Some("Open a PR for dependency updates.".to_string()),
enabled: true,
diff --git a/lib/crates/fabro-automation/Cargo.toml b/lib/crates/fabro-automation/Cargo.toml
index b25a2c5a8..bcbf8c371 100644
--- a/lib/crates/fabro-automation/Cargo.toml
+++ b/lib/crates/fabro-automation/Cargo.toml
@@ -13,11 +13,11 @@ doctest = false
workspace = true
[dependencies]
-chrono.workspace = true
croner = "3.0.1"
hex.workspace = true
serde.workspace = true
sha2.workspace = true
+tempfile = "3"
thiserror.workspace = true
tokio.workspace = true
toml.workspace = true
diff --git a/lib/crates/fabro-automation/src/error.rs b/lib/crates/fabro-automation/src/error.rs
index 4fd45049e..01d72ab44 100644
--- a/lib/crates/fabro-automation/src/error.rs
+++ b/lib/crates/fabro-automation/src/error.rs
@@ -37,8 +37,6 @@ pub enum AutomationStoreError {
NotFound(AutomationId),
#[error("automation already exists: {0}")]
AlreadyExists(AutomationId),
- #[error("missing automation revision")]
- MissingRevision,
#[error("automation revision mismatch")]
RevisionMismatch {
expected: AutomationRevision,
@@ -51,6 +49,8 @@ pub enum AutomationStoreError {
path: PathBuf,
source: TomlDeError,
},
+ #[error("failed to serialize automation TOML: {0}")]
+ Serialize(String),
#[error("I/O error at {}: {source}", path.display())]
Io {
path: PathBuf,
diff --git a/lib/crates/fabro-automation/src/lib.rs b/lib/crates/fabro-automation/src/lib.rs
index 64c64111c..2d62318bd 100644
--- a/lib/crates/fabro-automation/src/lib.rs
+++ b/lib/crates/fabro-automation/src/lib.rs
@@ -1,7 +1,6 @@
-pub mod error;
-pub mod id;
-pub mod model;
-
+mod error;
+mod id;
+mod model;
mod store;
pub use error::{AutomationStoreError, AutomationValidationError};
diff --git a/lib/crates/fabro-automation/src/model.rs b/lib/crates/fabro-automation/src/model.rs
index 0d40084aa..29538b35f 100644
--- a/lib/crates/fabro-automation/src/model.rs
+++ b/lib/crates/fabro-automation/src/model.rs
@@ -127,6 +127,14 @@ impl AutomationRevision {
Self(hex::encode(Sha256::digest(bytes)))
}
+ /// Wrap a client-supplied revision string (e.g. from an `If-Match`
+ /// header). The value is compared bytewise against a stored revision; no
+ /// validation is performed here.
+ #[must_use]
+ pub fn from_raw(value: impl Into<String>) -> Self {
+ Self(value.into())
+ }
+
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
@@ -165,28 +173,28 @@ impl Automation {
pub fn from_toml_bytes(id: AutomationId, bytes: &[u8]) -> Result<Self, TomlDeError> {
let source = std::str::from_utf8(bytes).map_err(TomlDeError::custom)?;
let persisted = toml::from_str::<PersistedAutomation>(source)?;
- // serde has already validated newtypes and trigger shapes. This call
- // checks cross-field invariants.
- persisted
- .into_automation(id, AutomationRevision::from_bytes(bytes))
- .map_err(TomlDeError::custom)
+ let revision = AutomationRevision::from_bytes(bytes);
+ Self::assemble(id, revision, persisted.into_replace()).map_err(TomlDeError::custom)
}
- pub fn from_draft(
- draft: AutomationDraft,
+ /// Build, validate, and assign a revision to an `Automation` in one
+ /// step. Used by the store immediately after persisting canonical TOML
+ /// bytes so the in-memory revision always matches what is on disk.
+ pub(crate) fn assemble(
+ id: AutomationId,
revision: AutomationRevision,
+ replace: AutomationReplace,
) -> Result<Self, AutomationValidationError> {
- let automation = Self {
- id: draft.id,
+ validate_common(&replace.name, &replace.triggers)?;
+ Ok(Self {
+ id,
revision,
- name: draft.name,
- description: draft.description,
- enabled: draft.enabled.unwrap_or(true),
- target: draft.target,
- triggers: draft.triggers,
- };
- automation.validate()?;
- Ok(automation)
+ name: replace.name,
+ description: replace.description,
+ enabled: replace.enabled,
+ target: replace.target,
+ triggers: replace.triggers,
+ })
}
#[must_use]
@@ -200,15 +208,6 @@ impl Automation {
}
}
- pub fn to_toml_bytes(&self) -> Result<Vec<u8>, TomlEditSerError> {
- let persisted = PersistedAutomation::from(self);
- to_document(&persisted).map(|document| document.to_string().into_bytes())
- }
-
- pub fn validate(&self) -> Result<(), AutomationValidationError> {
- validate_common(&self.name, &self.triggers)
- }
-
#[must_use]
pub fn api_trigger(&self) -> Option<&ApiTrigger> {
self.triggers.iter().find_map(|trigger| match trigger {
@@ -218,23 +217,29 @@ impl Automation {
}
}
-impl AutomationReplace {
- pub(crate) fn into_automation(
- self,
- id: AutomationId,
- revision: AutomationRevision,
- ) -> Result<Automation, AutomationValidationError> {
- let automation = Automation {
- id,
- revision,
- name: self.name,
+impl AutomationDraft {
+ /// Drop the `id` (which becomes the storage filename) and surface the
+ /// remaining fields in the canonical replace shape, applying the
+ /// `enabled` default.
+ #[must_use]
+ pub fn into_replace(self) -> AutomationReplace {
+ AutomationReplace {
+ name: self.name,
description: self.description,
- enabled: self.enabled,
- target: self.target,
- triggers: self.triggers,
- };
- automation.validate()?;
- Ok(automation)
+ enabled: self.enabled.unwrap_or(true),
+ target: self.target,
+ triggers: self.triggers,
+ }
+ }
+}
+
+impl AutomationReplace {
+ /// Serialize this replace value into canonical TOML bytes. The
+ /// representation matches `PersistedAutomation` so on-disk and in-memory
+ /// shapes stay aligned without an extra clone.
+ pub(crate) fn to_toml_bytes(&self) -> Result<Vec<u8>, TomlEditSerError> {
+ to_document(&PersistedAutomationRef::from(self))
+ .map(|document| document.to_string().into_bytes())
}
}
@@ -253,33 +258,36 @@ impl AutomationPatch {
}
impl PersistedAutomation {
- pub(crate) fn into_automation(
- self,
- id: AutomationId,
- revision: AutomationRevision,
- ) -> Result<Automation, AutomationValidationError> {
- let automation = Automation {
- id,
- revision,
- name: self.name,
+ fn into_replace(self) -> AutomationReplace {
+ AutomationReplace {
+ name: self.name,
description: self.description,
- enabled: self.enabled,
- target: self.target,
- triggers: self.triggers,
- };
- automation.validate()?;
- Ok(automation)
+ enabled: self.enabled,
+ target: self.target,
+ triggers: self.triggers,
+ }
}
}
-impl From<&Automation> for PersistedAutomation {
- fn from(value: &Automation) -> Self {
+#[derive(Debug, Serialize)]
+struct PersistedAutomationRef<'a> {
+ name: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ description: Option<&'a str>,
+ enabled: bool,
+ target: &'a AutomationTarget,
+ #[serde(default, skip_serializing_if = "<[_]>::is_empty")]
+ triggers: &'a [AutomationTrigger],
+}
+
+impl<'a> From<&'a AutomationReplace> for PersistedAutomationRef<'a> {
+ fn from(value: &'a AutomationReplace) -> Self {
Self {
- name: value.name.clone(),
- description: value.description.clone(),
+ name: &value.name,
+ description: value.description.as_deref(),
enabled: value.enabled,
- target: value.target.clone(),
- triggers: value.triggers.clone(),
+ target: &value.target,
+ triggers: &value.triggers,
}
}
}
@@ -458,14 +466,6 @@ impl fmt::Display for AutomationRevision {
}
}
-impl FromStr for AutomationRevision {
- type Err = AutomationValidationError;
-
- fn from_str(value: &str) -> Result<Self, Self::Err> {
- Ok(Self(value.to_string()))
- }
-}
-
impl Serialize for AutomationRevision {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
@@ -680,7 +680,14 @@ expression = "0 3 * * *"
"#,
))
.expect("draft should deserialize");
- assert!(Automation::from_draft(draft, AutomationRevision::from_bytes(b"")).is_err());
+ assert!(
+ Automation::assemble(
+ draft.id.clone(),
+ AutomationRevision::from_bytes(b""),
+ draft.into_replace(),
+ )
+ .is_err()
+ );
}
#[test]
@@ -698,7 +705,14 @@ type = "api"
"#,
))
.expect("draft should deserialize");
- assert!(Automation::from_draft(draft, AutomationRevision::from_bytes(b"")).is_err());
+ assert!(
+ Automation::assemble(
+ draft.id.clone(),
+ AutomationRevision::from_bytes(b""),
+ draft.into_replace(),
+ )
+ .is_err()
+ );
}
#[test]
@@ -725,7 +739,14 @@ expression = "* * * * * *"
"#,
))
.expect("draft should deserialize");
- assert!(Automation::from_draft(draft, AutomationRevision::from_bytes(b"")).is_err());
+ assert!(
+ Automation::assemble(
+ draft.id.clone(),
+ AutomationRevision::from_bytes(b""),
+ draft.into_replace(),
+ )
+ .is_err()
+ );
}
#[test]
diff --git a/lib/crates/fabro-automation/src/store.rs b/lib/crates/fabro-automation/src/store.rs
index 90fac75e7..d61ed22f8 100644
--- a/lib/crates/fabro-automation/src/store.rs
+++ b/lib/crates/fabro-automation/src/store.rs
@@ -1,11 +1,14 @@
use std::collections::BTreeMap;
-use std::path::{Path, PathBuf};
-use std::sync::atomic::{AtomicU64, Ordering};
-use std::time::{SystemTime, UNIX_EPOCH};
-
-use tokio::fs::{self, OpenOptions};
-use tokio::io::AsyncWriteExt as _;
+#[expect(
+ clippy::disallowed_types,
+ reason = "atomic_write writes through spawn_blocking + NamedTempFile, which only exposes std::io::Write."
+)]
+use std::io::Write as _;
+use std::path::PathBuf;
+
+use tempfile::NamedTempFile;
use tokio::sync::RwLock;
+use tokio::{fs, task};
use crate::error::{AutomationStoreError, AutomationValidationError};
use crate::id::AutomationId;
@@ -114,9 +117,7 @@ impl AutomationStore {
if items.contains_key(&id) {
return Err(AutomationStoreError::AlreadyExists(id));
}
-
- let automation = Automation::from_draft(draft, AutomationRevision::from_bytes(b""))?;
- let automation = self.persist_with_revision(automation).await?;
+ let automation = self.persist(id.clone(), draft.into_replace()).await?;
items.insert(id, automation.clone());
Ok(automation)
}
@@ -132,9 +133,7 @@ impl AutomationStore {
.get(id)
.ok_or_else(|| AutomationStoreError::NotFound(id.clone()))?;
ensure_revision(current, expected)?;
-
- let automation = draft.into_automation(id.clone(), AutomationRevision::from_bytes(b""))?;
- let automation = self.persist_with_revision(automation).await?;
+ let automation = self.persist(id.clone(), draft).await?;
items.insert(id.clone(), automation.clone());
Ok(automation)
}
@@ -150,10 +149,8 @@ impl AutomationStore {
.get(id)
.ok_or_else(|| AutomationStoreError::NotFound(id.clone()))?;
ensure_revision(current, expected)?;
-
- let draft = patch.apply_to(current);
- let automation = draft.into_automation(id.clone(), AutomationRevision::from_bytes(b""))?;
- let automation = self.persist_with_revision(automation).await?;
+ let replace = patch.apply_to(current);
+ let automation = self.persist(id.clone(), replace).await?;
items.insert(id.clone(), automation.clone());
Ok(automation)
}
@@ -179,19 +176,22 @@ impl AutomationStore {
Ok(())
}
- async fn persist_with_revision(
+ /// Validate the replace value, render canonical TOML, write atomically,
+ /// and return the assembled `Automation` whose revision matches the
+ /// bytes that landed on disk.
+ async fn persist(
&self,
- automation: Automation,
+ id: AutomationId,
+ replace: AutomationReplace,
) -> Result<Automation, AutomationStoreError> {
- let bytes = automation
+ let bytes = replace
.to_toml_bytes()
- .map_err(|err| AutomationValidationError::InvalidWorkflowSelector(err.to_string()))?;
- atomic_write(&self.dir, &self.path_for(&automation.id), &bytes).await?;
+ .map_err(|err| AutomationStoreError::Serialize(err.to_string()))?;
let revision = AutomationRevision::from_bytes(&bytes);
- Ok(Automation {
- revision,
- ..automation
- })
+ let automation = Automation::assemble(id, revision, replace)?;
+ let path = self.path_for(&automation.id);
+ atomic_write(&self.dir, &path, bytes).await?;
+ Ok(automation)
}
fn path_for(&self, id: &AutomationId) -> PathBuf {
@@ -214,53 +214,34 @@ fn ensure_revision(
}
async fn atomic_write(
- dir: &Path,
- final_path: &Path,
- bytes: &[u8],
+ dir: &std::path::Path,
+ final_path: &std::path::Path,
+ bytes: Vec<u8>,
) -> Result<(), AutomationStoreError> {
fs::create_dir_all(dir)
.await
.map_err(|err| AutomationStoreError::io(dir, err))?;
- let temp_path = temp_path_for(dir, final_path);
- let mut file = OpenOptions::new()
- .write(true)
- .create_new(true)
- .open(&temp_path)
- .await
- .map_err(|err| AutomationStoreError::io(&temp_path, err))?;
- let write_result = async {
- file.write_all(bytes).await?;
- file.flush().await?;
- file.sync_all().await
- }
- .await;
- if let Err(err) = write_result {
- let _ = fs::remove_file(&temp_path).await;
- return Err(AutomationStoreError::io(&temp_path, err));
- }
- drop(file);
-
- if let Err(err) = fs::rename(&temp_path, final_path).await {
- let _ = fs::remove_file(&temp_path).await;
- return Err(AutomationStoreError::io(final_path, err));
- }
+ let dir = dir.to_path_buf();
+ let final_path = final_path.to_path_buf();
+ let join_dir = dir.clone();
+ task::spawn_blocking(move || -> Result<(), AutomationStoreError> {
+ let mut temp =
+ NamedTempFile::new_in(&dir).map_err(|err| AutomationStoreError::io(&dir, err))?;
+ temp.write_all(&bytes)
+ .map_err(|err| AutomationStoreError::io(temp.path(), err))?;
+ temp.as_file()
+ .sync_all()
+ .map_err(|err| AutomationStoreError::io(temp.path(), err))?;
+ temp.persist(&final_path)
+ .map_err(|err| AutomationStoreError::io(final_path, err.error))?;
+ Ok(())
+ })
+ .await
+ .map_err(|err| AutomationStoreError::io(join_dir, std::io::Error::other(err)))??;
Ok(())
}
-fn temp_path_for(dir: &Path, final_path: &Path) -> PathBuf {
- static COUNTER: AtomicU64 = AtomicU64::new(0);
- let stem = final_path
- .file_name()
- .and_then(|name| name.to_str())
- .unwrap_or("automation.toml");
- let now = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .map_or(0, |duration| duration.as_nanos());
- let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
- dir.join(format!(".{stem}.{now}.{counter}.tmp"))
-}
-
#[cfg(test)]
mod tests {
use tokio::fs;
diff --git a/lib/crates/fabro-server/src/automation_materializer.rs b/lib/crates/fabro-server/src/automation_materializer.rs
index ad090632d..36970cb13 100644
--- a/lib/crates/fabro-server/src/automation_materializer.rs
+++ b/lib/crates/fabro-server/src/automation_materializer.rs
@@ -4,15 +4,16 @@ use std::time::Duration;
use async_trait::async_trait;
use fabro_api::types::RunManifest;
-use fabro_automation::{AutomationId, AutomationTarget};
+use fabro_automation::AutomationTarget;
use fabro_config::Storage;
+use fabro_redact::DisplaySafeUrl;
+use fabro_sandbox::redact::redact_auth_url;
use fabro_types::RunId;
use tokio::process::Command;
use tokio::time::timeout;
use tokio::{fs, task};
pub(crate) struct AutomationRunMaterializeInput {
- pub automation_id: AutomationId,
pub target: AutomationTarget,
pub run_id: RunId,
pub user_settings_path: PathBuf,
@@ -31,8 +32,6 @@ pub(crate) enum AutomationRunMaterializeError {
InvalidTarget(String),
#[error("failed to clone automation repository: {0}")]
CloneFailed(String),
- #[error("failed to resolve automation workflow: {0}")]
- WorkflowNotFound(String),
#[error("failed to build run manifest: {0}")]
Manifest(String),
}
@@ -80,9 +79,10 @@ impl AutomationRunMaterializer for GitAutomationRunMaterializer {
));
}
let sanitized_clone_url = github_clone_url(owner, repo);
- let clone_url = self
- .authenticated_clone_url(owner, repo, &sanitized_clone_url)
- .await?;
+ let auth_url = self.authenticated_clone_url(&sanitized_clone_url).await?;
+ let clone_url = auth_url
+ .as_ref()
+ .map_or_else(|| sanitized_clone_url.clone(), DisplaySafeUrl::raw_string);
fs::create_dir_all(&input.temp_root).await.map_err(|err| {
AutomationRunMaterializeError::CloneFailed(format!(
@@ -91,38 +91,38 @@ impl AutomationRunMaterializer for GitAutomationRunMaterializer {
))
})?;
let checkout_dir = input.temp_root.join(input.run_id.to_string());
- run_git(
- git_clone_args(&clone_url, &checkout_dir),
- self.git_timeout,
- "git clone",
- )
- .await?;
- run_git(
- git_remote_set_url_args(&checkout_dir, &sanitized_clone_url),
- self.git_timeout,
- "git remote set-url origin",
- )
- .await?;
- run_git(
- git_checkout_args(&checkout_dir, input.target.ref_.as_str()),
- self.git_timeout,
- "git checkout",
- )
- .await?;
-
- build_manifest_from_checkout(input, checkout_dir).await
+ let result = self
+ .run_checkout(
+ &input,
+ &checkout_dir,
+ &clone_url,
+ &sanitized_clone_url,
+ auth_url.as_ref(),
+ )
+ .await;
+ // Always clean up the materialized clone: callers don't need the
+ // working tree after the manifest is built, and a failed clone
+ // (e.g. partial fetch) should not leak gigabytes into scratch.
+ if let Err(err) = fs::remove_dir_all(&checkout_dir).await {
+ if err.kind() != std::io::ErrorKind::NotFound {
+ tracing::warn!(
+ error = %err,
+ path = %checkout_dir.display(),
+ "Failed to clean up automation checkout",
+ );
+ }
+ }
+ result
}
}
impl GitAutomationRunMaterializer {
async fn authenticated_clone_url(
&self,
- owner: &str,
- repo: &str,
sanitized_clone_url: &str,
- ) -> Result<String, AutomationRunMaterializeError> {
+ ) -> Result<Option<DisplaySafeUrl>, AutomationRunMaterializeError> {
let Some(credentials) = self.github_credentials.as_ref() else {
- return Ok(sanitized_clone_url.to_string());
+ return Ok(None);
};
let ctx = match self.http_client.clone() {
Some(client) => fabro_github::GitHubContext::with_http_client(
@@ -132,15 +132,42 @@ impl GitAutomationRunMaterializer {
),
None => fabro_github::GitHubContext::new(credentials, &self.github_api_base_url),
};
- let (_username, token) = fabro_github::resolve_clone_credentials(&ctx, owner, repo)
+ fabro_github::resolve_authenticated_url(&ctx, sanitized_clone_url)
.await
- .map_err(|err| AutomationRunMaterializeError::CloneFailed(err.to_string()))?;
- match token {
- Some(token) => fabro_github::embed_token_in_url(sanitized_clone_url, &token)
- .map(|url| url.raw_string())
- .map_err(|err| AutomationRunMaterializeError::CloneFailed(err.to_string())),
- None => Ok(sanitized_clone_url.to_string()),
- }
+ .map(Some)
+ .map_err(|err| AutomationRunMaterializeError::CloneFailed(err.to_string()))
+ }
+
+ async fn run_checkout(
+ &self,
+ input: &AutomationRunMaterializeInput,
+ checkout_dir: &Path,
+ clone_url: &str,
+ sanitized_clone_url: &str,
+ auth_url: Option<&DisplaySafeUrl>,
+ ) -> Result<AutomationRunMaterialized, AutomationRunMaterializeError> {
+ run_git(
+ git_clone_args(clone_url, checkout_dir),
+ self.git_timeout,
+ "git clone",
+ auth_url,
+ )
+ .await?;
+ run_git(
+ git_remote_set_url_args(checkout_dir, sanitized_clone_url),
+ self.git_timeout,
+ "git remote set-url origin",
+ auth_url,
+ )
+ .await?;
+ run_git(
+ git_checkout_args(checkout_dir, input.target.ref_.as_str()),
+ self.git_timeout,
+ "git checkout",
+ auth_url,
+ )
+ .await?;
+ build_manifest_from_checkout(input, checkout_dir).await
}
}
@@ -187,6 +214,7 @@ async fn run_git(
args: Vec<OsString>,
git_timeout: Duration,
label: &'static str,
+ auth_url: Option<&DisplaySafeUrl>,
) -> Result<(), AutomationRunMaterializeError> {
let mut command = Command::new("git");
command.args(&args);
@@ -200,45 +228,40 @@ async fn run_git(
git_timeout.as_secs()
))
})?
- .map_err(|err| AutomationRunMaterializeError::CloneFailed(format!("{label}: {err}")))?;
+ .map_err(|err| {
+ AutomationRunMaterializeError::CloneFailed(redact_auth_url(
+ &format!("{label}: {err}"),
+ auth_url,
+ ))
+ })?;
if output.status.success() {
return Ok(());
}
- let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
- let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
- let detail = if stderr.is_empty() { stdout } else { stderr };
- Err(AutomationRunMaterializeError::CloneFailed(format!(
- "{label} exited with status {}: {}",
- output.status,
- redact_command_output(&detail)
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let detail = if stderr.trim().is_empty() {
+ stdout.trim()
+ } else {
+ stderr.trim()
+ };
+ Err(AutomationRunMaterializeError::CloneFailed(redact_auth_url(
+ &format!("{label} exited with status {}: {detail}", output.status),
+ auth_url,
)))
}
-fn redact_command_output(value: &str) -> String {
- value
- .split_whitespace()
- .map(redact_url_token)
- .collect::<Vec<_>>()
- .join(" ")
-}
-
-fn redact_url_token(value: &str) -> String {
- fabro_redact::DisplaySafeUrl::parse(value)
- .map_or_else(|_| value.to_string(), |url| url.redacted_string())
-}
-
async fn build_manifest_from_checkout(
- input: AutomationRunMaterializeInput,
- checkout_dir: PathBuf,
+ input: &AutomationRunMaterializeInput,
+ checkout_dir: &Path,
) -> Result<AutomationRunMaterialized, AutomationRunMaterializeError> {
let workflow = PathBuf::from(input.target.workflow.as_str());
- let user_settings_path = input.user_settings_path;
+ let user_settings_path = input.user_settings_path.clone();
let run_id = input.run_id;
- let automation_id = input.automation_id.to_string();
+ let cwd = checkout_dir.to_path_buf();
let built = task::spawn_blocking(move || {
fabro_manifest::build_run_manifest(fabro_manifest::ManifestBuildInput {
workflow,
- cwd: checkout_dir,
+ cwd,
run_id: Some(run_id),
user_settings_path: Some(user_settings_path),
..fabro_manifest::ManifestBuildInput::default()
@@ -246,7 +269,7 @@ async fn build_manifest_from_checkout(
})
.await
.map_err(|err| AutomationRunMaterializeError::Manifest(err.to_string()))?
- .map_err(|err| classify_manifest_error(&automation_id, &err))?;
+ .map_err(|err| AutomationRunMaterializeError::Manifest(err.to_string()))?;
let submitted_manifest_bytes = serde_json::to_vec(&built.manifest)
.map_err(|err| AutomationRunMaterializeError::Manifest(err.to_string()))?;
Ok(AutomationRunMaterialized {
@@ -255,21 +278,6 @@ async fn build_manifest_from_checkout(
})
}
-fn classify_manifest_error(
- automation_id: &str,
- err: &anyhow::Error,
-) -> AutomationRunMaterializeError {
- let message = err.to_string();
- if err
- .chain()
- .any(|cause| cause.to_string().contains("workflow") && cause.to_string().contains("not"))
- {
- AutomationRunMaterializeError::WorkflowNotFound(format!("{automation_id}: {message}"))
- } else {
- AutomationRunMaterializeError::Manifest(message)
- }
-}
-
#[cfg(any(test, feature = "test-support"))]
pub(crate) struct StaticAutomationRunMaterializer {
result: Result<AutomationRunMaterialized, AutomationRunMaterializeError>,
@@ -305,7 +313,7 @@ impl AutomationRunMaterializer for StaticAutomationRunMaterializer {
mod tests {
use std::str::FromStr as _;
- use fabro_automation::{AutomationId, GitRefSelector, RepositorySlug, WorkflowSlug};
+ use fabro_automation::{GitRefSelector, RepositorySlug, WorkflowSlug};
use super::*;
@@ -318,12 +326,17 @@ mod tests {
}
#[test]
- fn redact_command_output_strips_credentials() {
- let redacted = redact_command_output(
- "fatal: https://x-access-token:ghs_secret@github.com/acme/widgets.git failed",
+ fn redact_auth_url_strips_credentials_from_stderr() {
+ let auth_url =
+ DisplaySafeUrl::parse("https://x-access-token:ghs_secret@github.com/acme/widgets.git")
+ .expect("auth url should parse");
+ let redacted = redact_auth_url(
+ "fatal: https://x-access-token:ghs_secret@github.com/acme/widgets.git\nremote: denied",
+ Some(&auth_url),
);
- assert!(redacted.contains("https://x-access-token:***@github.com/acme/widgets.git"));
assert!(!redacted.contains("ghs_secret"));
+ // Newlines are preserved (unlike a whitespace-collapse redactor).
+ assert!(redacted.contains('\n'));
}
#[test]
@@ -359,14 +372,13 @@ mod tests {
};
let run_id = RunId::new();
let input = AutomationRunMaterializeInput {
- automation_id: AutomationId::from_str("nightly").unwrap(),
target,
run_id,
user_settings_path: dir.path().join("settings.toml"),
temp_root: dir.path().join("tmp"),
};
- let materialized = build_manifest_from_checkout(input, dir.path().to_path_buf())
+ let materialized = build_manifest_from_checkout(&input, dir.path())
.await
.expect("manifest should build");
diff --git a/lib/crates/fabro-server/src/server/handler/automations.rs b/lib/crates/fabro-server/src/server/handler/automations.rs
index 8978881bf..117c6d6cb 100644
--- a/lib/crates/fabro-server/src/server/handler/automations.rs
+++ b/lib/crates/fabro-server/src/server/handler/automations.rs
@@ -1,5 +1,4 @@
use std::collections::BTreeMap;
-use std::str::FromStr as _;
use std::sync::Arc;
use axum::body::Bytes;
@@ -149,8 +148,9 @@ fn default_true() -> bool {
}
async fn list_automations(_auth: RequiredUser, State(state): State<Arc<AppState>>) -> Response {
- let mut automations = state.automation_store().list().await;
- automations.sort_by(|left, right| left.id.cmp(&right.id));
+ // `AutomationStore::list` already yields entries in `AutomationId` order
+ // (BTreeMap iteration); no additional sort is required.
+ let automations = state.automation_store().list().await;
let total = automations.len() as u64;
(
StatusCode::OK,
@@ -367,7 +367,6 @@ async fn create_automation_run(
let materialized = match state
.automation_materializer()
.materialize(AutomationRunMaterializeInput {
- automation_id: id.clone(),
target: automation.target.clone(),
run_id,
user_settings_path: state.active_config_path().to_path_buf(),
@@ -441,8 +440,7 @@ fn parse_if_match(headers: &HeaderMap) -> Result<AutomationRevision, ApiError> {
"If-Match revision must not be empty.",
));
}
- Ok(AutomationRevision::from_str(revision)
- .expect("AutomationRevision accepts any non-empty string"))
+ Ok(AutomationRevision::from_raw(revision))
}
fn with_etag(status: StatusCode, automation: Automation) -> Response {
@@ -461,29 +459,22 @@ fn store_error(err: AutomationStoreError) -> ApiError {
AutomationStoreError::AlreadyExists(_) => {
ApiError::new(StatusCode::CONFLICT, "Automation already exists.")
}
- AutomationStoreError::MissingRevision => ApiError::new(
- StatusCode::PRECONDITION_REQUIRED,
- "If-Match header is required.",
- ),
AutomationStoreError::RevisionMismatch { .. } => {
ApiError::new(StatusCode::CONFLICT, "Automation revision mismatch.")
}
AutomationStoreError::Validation(err) => validation_error(&err),
- AutomationStoreError::Parse { .. } | AutomationStoreError::Io { .. } => {
+ AutomationStoreError::Parse { .. }
+ | AutomationStoreError::Serialize(_)
+ | AutomationStoreError::Io { .. } => {
ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
}
}
}
fn materialize_error(err: &AutomationRunMaterializeError) -> ApiError {
- match err {
- AutomationRunMaterializeError::InvalidTarget(_)
- | AutomationRunMaterializeError::CloneFailed(_)
- | AutomationRunMaterializeError::WorkflowNotFound(_)
- | AutomationRunMaterializeError::Manifest(_) => {
- ApiError::new(StatusCode::UNPROCESSABLE_ENTITY, err.to_string())
- }
- }
+ // All current variants surface as 422 — they describe automation
+ // misconfiguration or repository state that the caller can correct.
+ ApiError::new(StatusCode::UNPROCESSABLE_ENTITY, err.to_string())
}
impl TryFrom<RawAutomationTarget> for AutomationTarget {

View file

@ -0,0 +1,6 @@
{
"outcome": "succeeded",
"notes": "Stage completed: simplify_opus",
"failure_reason": null,
"timestamp": "2026-05-25T00:56:11.647363Z"
}

View file

@ -0,0 +1,737 @@
Goal: # Automations Backend API Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Build the backend data model and REST API for creating, editing, deleting, starting, and listing runs for Automations.
**Architecture:** Automations are server-owned runnable bindings stored as one canonical TOML file per automation in `dirname(active_config_path)/automations/<id>.toml`. The server loads those files into an in-memory store at startup, persists API mutations atomically, and attaches an automation reference to runs created through the automation API. Schedule triggers are stored and validated, but no cron scheduler or background trigger loop is added in this plan.
**Tech Stack:** Rust, serde, toml, toml_edit, sha2, hex, croner for schedule validation only, Axum, OpenAPI/progenitor, existing Fabro run manifest and run creation pipeline.
---
## Locked Decisions
- Backend only: do not add web UI routes/components and do not add CLI commands.
- Storage root: `dirname(active_config_path)/automations`.
- File layout: one automation per file, `automations/<id>.toml`.
- Canonical ID: the filename stem. The TOML file does not repeat `id`.
- Automation ID format: `[a-z0-9][a-z0-9-]{0,62}`.
- Trigger ID format: `[a-z0-9][a-z0-9_-]{0,62}`.
- Trigger IDs are required, user-visible, editable, and unique within one automation.
- Triggers are an array from v1.
- The API trigger type is `api`, not `manual_api`. Trigger IDs remain user-visible and editable; examples use `id = "api"` but startability is based on `type = "api"`.
- At most one trigger with `type = "api"` is allowed per automation.
- Multiple `schedule` triggers are allowed.
- Unknown trigger types, including future `event` shapes, return `422` in v1. Handlers must not let unknown trigger discriminators fail as JSON parse errors.
- If an automation is disabled, or it has no enabled trigger with `type = "api"`, `POST /automations/{id}/runs` returns `409` and does not create a run.
- API writes canonicalize TOML and may discard comments in automation files.
- No runtime automation state store or derived automation status API is added in V1. Run history is available through `GET /automations/{id}/runs`; schedule expressions are validated but not evaluated for scheduling.
## File Structure
Create:
- `lib/crates/fabro-automation/Cargo.toml` - domain crate manifest.
- `lib/crates/fabro-automation/src/lib.rs` - public exports.
- `lib/crates/fabro-automation/src/error.rs` - validation and persistence errors.
- `lib/crates/fabro-automation/src/id.rs` - `AutomationId` and `AutomationTriggerId`.
- `lib/crates/fabro-automation/src/model.rs` - automation domain and serde/TOML model.
- `lib/crates/fabro-automation/src/store.rs` - in-memory file-backed automation store.
- `lib/crates/fabro-server/src/automation_materializer.rs` - GitHub target materialization and manifest building for automation runs.
- `lib/crates/fabro-server/src/server/handler/automations.rs` - REST handlers and router.
- `lib/crates/fabro-server/tests/it/api/automations.rs` - server API integration tests.
- `lib/crates/fabro-server/tests/it/api/mod.rs` - wire the automations integration test module.
Modify:
- `lib/crates/fabro-server/Cargo.toml` - add `fabro-automation`.
- `lib/crates/fabro-api/Cargo.toml` - add `fabro-automation` so OpenAPI can reuse matching automation domain types.
- `lib/crates/fabro-types/src/run_summary.rs` - extend `AutomationRef` with `trigger_id`.
- `lib/crates/fabro-types/src/run.rs` - add `automation: Option<AutomationRef>` to `RunSpec`.
- `lib/crates/fabro-types/src/run_event/run.rs` - add `automation: Option<AutomationRef>` to `RunCreatedProps`.
- `lib/crates/fabro-workflow/src/operations/create.rs` - carry automation metadata through `CreateRunInput`, persistence options, `RunSpec`, and `run.created`.
- `lib/crates/fabro-workflow/src/event/convert.rs` - preserve automation metadata in any legacy-to-current event conversion path that constructs `RunCreatedProps`.
- `lib/crates/fabro-store/src/run_state.rs` - project `RunSpec.automation` into `Run.automation`.
- `lib/crates/fabro-server/src/server.rs` - load the automation store into `AppState` and expose crate-private accessors.
- `lib/crates/fabro-server/src/server/handler/mod.rs` - merge real automation routes.
- `lib/crates/fabro-server/src/test_support.rs` - create temp automation storage by active config path and allow test-only materializer injection.
- `docs/public/api-reference/fabro-api.yaml` - add automation paths and schemas.
- `lib/crates/fabro-api/build.rs` - add replacement mappings only for domain types with identical wire shape.
- `lib/crates/fabro-api/tests/*` - add JSON parity tests for reused automation types.
- `lib/packages/fabro-api-client` - regenerate generated TypeScript client files only; do not import them from the web UI.
Do not modify:
- `apps/fabro-web/**`, except generated API package consumers are not touched.
- CLI command modules.
- Scheduler services or background run loops.
## Public API Shape
Add these OpenAPI paths under `/api/v1`:
```http
GET /automations
POST /automations
GET /automations/{id}
PUT /automations/{id}
PATCH /automations/{id}
DELETE /automations/{id}
GET /automations/{id}/runs
POST /automations/{id}/runs
```
Use this response model:
```ts
type Automation = {
id: string;
revision: string;
name: string;
description: string | null;
enabled: boolean;
target: AutomationTarget;
triggers: AutomationTrigger[];
};
type AutomationTarget = {
repository: string; // GitHub owner/repo
ref: string;
workflow: string;
};
type AutomationTrigger =
| { id: string; type: "api"; enabled: boolean }
| { id: string; type: "schedule"; enabled: boolean; expression: string };
```
Request models:
```ts
type CreateAutomationRequest = {
id: string;
name: string;
description?: string | null;
enabled?: boolean;
target: AutomationTarget;
triggers: AutomationTrigger[];
};
type ReplaceAutomationRequest = {
name: string;
description?: string | null;
enabled: boolean;
target: AutomationTarget;
triggers: AutomationTrigger[];
};
type PatchAutomationRequest = {
name?: string;
description?: string | null;
enabled?: boolean;
target?: AutomationTarget;
triggers?: AutomationTrigger[];
};
```
`GET /automations/{id}/runs` returns the existing paginated run list envelope:
```json
{
"data": [],
"meta": { "has_more": false, "total": 0 }
}
```
It accepts `page[limit]` and `page[offset]`, sorts newest first, filters by `Run.automation.id`, and returns `404` if the automation definition no longer exists.
`POST /automations/{id}/runs` returns the existing `Run` response shape with `automation` populated:
```json
{
"automation": {
"id": "nightly-deps",
"name": "Nightly dependency update",
"trigger_id": "api"
}
}
```
## TOML Shape
Persist this canonical TOML:
```toml
name = "Nightly dependency update"
description = "Open a PR for dependency updates."
enabled = true
[target]
repository = "fabro-sh/fabro"
ref = "main"
workflow = "dependency-update"
[[triggers]]
id = "api"
type = "api"
enabled = false
[[triggers]]
id = "nightly"
type = "schedule"
enabled = true
expression = "0 3 * * *"
```
Defaults:
- `enabled` defaults to `true` when omitted in TOML or create requests.
- `description` defaults to `null`.
- Trigger `enabled` defaults to `true` when omitted in TOML or create requests.
- `schedule.expression` must be a non-empty five-field cron expression accepted by `croner`.
- `target.repository` must be a GitHub `owner/repo` slug using the existing server slug validation rules: owner max 39 chars, repo max 100 chars, no path traversal or separators inside either segment.
- `target.ref` must be a non-empty branch, tag, or SHA selector and must not start with `-`, contain ASCII control characters, or contain shell/path traversal metacharacters that would make git argv ambiguous.
- `target.workflow` is a Fabro workflow selector resolved inside the cloned repository with `WorkflowLocation::resolve`; it may be a workflow slug such as `dependency-update` or a relative workflow path, but absolute paths and `..` path traversal are invalid.
## Task 1: Add Domain Crate And Model Tests
**Files:**
- Create: `lib/crates/fabro-automation/Cargo.toml`
- Create: `lib/crates/fabro-automation/src/lib.rs`
- Create: `lib/crates/fabro-automation/src/error.rs`
- Create: `lib/crates/fabro-automation/src/id.rs`
- Create: `lib/crates/fabro-automation/src/model.rs`
- [ ] Read `docs/internal/testing-strategy.md` and `docs/internal/error-handling-strategy.md` before adding tests and error types.
- [ ] Create the crate. Because the workspace uses `members = ["lib/crates/*"]`, no root workspace member edit is required.
- [ ] Add dependencies in `lib/crates/fabro-automation/Cargo.toml`: `chrono`, `croner`, `hex`, `serde`, `sha2`, `thiserror`, `tokio`, `toml`, and `toml_edit`. Add dev-dependencies: `tempfile`.
- [ ] Define `AutomationId` and `AutomationTriggerId` newtypes with `TryFrom<String>`, `AsRef<str>`, `Display`, `Serialize`, and `Deserialize`.
- [ ] Define the domain model with this public shape:
```rust
pub struct AutomationRevision(String);
pub struct RepositorySlug(String);
pub struct GitRefSelector(String);
pub struct WorkflowSlug(String);
pub struct Automation {
pub id: AutomationId,
pub revision: AutomationRevision,
pub name: String,
pub description: Option<String>,
pub enabled: bool,
pub target: AutomationTarget,
pub triggers: Vec<AutomationTrigger>,
}
pub struct AutomationTarget {
pub repository: RepositorySlug,
pub ref_: GitRefSelector,
pub workflow: WorkflowSlug,
}
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AutomationTrigger {
Api(ApiTrigger),
Schedule(ScheduleTrigger),
}
pub struct ApiTrigger {
pub id: AutomationTriggerId,
pub enabled: bool,
}
pub struct ScheduleTrigger {
pub id: AutomationTriggerId,
pub enabled: bool,
pub expression: String,
}
pub struct AutomationDraft {
pub id: AutomationId,
pub name: String,
pub description: Option<String>,
pub enabled: Option<bool>,
pub target: AutomationTarget,
pub triggers: Vec<AutomationTrigger>,
}
pub struct AutomationReplace {
pub name: String,
pub description: Option<String>,
pub enabled: bool,
pub target: AutomationTarget,
pub triggers: Vec<AutomationTrigger>,
}
pub struct AutomationPatch {
pub name: Option<String>,
pub description: Option<Option<String>>,
pub enabled: Option<bool>,
pub target: Option<AutomationTarget>,
pub triggers: Option<Vec<AutomationTrigger>>,
}
```
- [ ] Use `#[serde(rename = "ref")]` for the Rust field `ref_`.
- [ ] Keep `revision` out of the persisted TOML model; compute it from raw file bytes.
- [ ] Reject empty names, invalid GitHub repository slugs, invalid refs, invalid workflow selectors, duplicate trigger IDs, and more than one trigger with `type = "api"`.
- [ ] Add unit tests for valid TOML, defaults, invalid automation IDs, invalid trigger IDs, duplicate trigger IDs, two `api` triggers, invalid repository slug, and invalid schedule expression.
- [ ] Run `cargo nextest run -p fabro-automation`.
- [ ] Commit:
```bash
git add lib/crates/fabro-automation
git commit -m "feat: add automation domain model"
```
## Task 2: Implement File-Backed Automation Store
**Files:**
- Create: `lib/crates/fabro-automation/src/store.rs`
- Modify: `lib/crates/fabro-automation/src/lib.rs`
- [ ] Implement `AutomationStore` as an in-memory map guarded by `tokio::sync::RwLock`.
- [ ] Load files from a configured directory with this behavior:
- Missing directory means an empty store.
- Non-`.toml` files are ignored.
- Invalid filenames fail load.
- Invalid TOML or invalid automation data fails load.
- [ ] Compute `AutomationRevision` as lowercase hex SHA-256 of the exact TOML bytes read from disk.
- [ ] Expose these async methods:
```rust
pub async fn load(dir: impl Into<PathBuf>) -> Result<Self, AutomationStoreError>;
pub async fn list(&self) -> Vec<Automation>;
pub async fn get(&self, id: &AutomationId) -> Option<Automation>;
pub async fn create(&self, draft: AutomationDraft) -> Result<Automation, AutomationStoreError>;
pub async fn replace(
&self,
id: &AutomationId,
expected: &AutomationRevision,
draft: AutomationReplace,
) -> Result<Automation, AutomationStoreError>;
pub async fn patch(
&self,
id: &AutomationId,
expected: &AutomationRevision,
patch: AutomationPatch,
) -> Result<Automation, AutomationStoreError>;
pub async fn delete(
&self,
id: &AutomationId,
expected: &AutomationRevision,
) -> Result<(), AutomationStoreError>;
```
- [ ] Make create/update writes atomic by serializing to canonical TOML, writing a temp file in the automation directory, flushing it, and renaming it over the final path.
- [ ] Create the automation directory on first write.
- [ ] Map store errors into precise variants: not found, already exists, missing revision, revision mismatch, validation, parse, and I/O.
- [ ] Add tests using `tempfile` for empty load, create writes file, replace changes revision, patch keeps unchanged fields, stale revision fails, delete removes file, and startup fails on malformed TOML.
- [ ] Run `cargo nextest run -p fabro-automation`.
- [ ] Commit:
```bash
git add lib/crates/fabro-automation
git commit -m "feat: persist automations as TOML files"
```
## Task 3: Carry Automation Metadata Through Runs
**Files:**
- Modify: `lib/crates/fabro-types/src/run_summary.rs`
- Modify: `lib/crates/fabro-types/src/run.rs`
- Modify: `lib/crates/fabro-types/src/run_event/run.rs`
- Modify: `lib/crates/fabro-workflow/src/operations/create.rs`
- Modify: `lib/crates/fabro-workflow/src/event/convert.rs`
- Modify: `lib/crates/fabro-store/src/run_state.rs`
- Modify tests that construct `RunSpec` or `RunCreatedProps`
- [ ] Extend `AutomationRef`:
```rust
pub struct AutomationRef {
pub id: String,
#[serde(default)]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trigger_id: Option<String>,
}
```
- [ ] Add `automation: Option<AutomationRef>` to `RunSpec` with `#[serde(default, skip_serializing_if = "Option::is_none")]`.
- [ ] Add `automation: Option<AutomationRef>` to `RunCreatedProps` with the same serde behavior.
- [ ] Add `automation: Option<AutomationRef>` to `fabro_workflow::operations::CreateRunInput`.
- [ ] Thread the field through `PersistCreateOptions`, the `RunSpec` built in `persist_validated`, and the `Event::RunCreated` emitted in `persist_created_run`.
- [ ] In `fabro-store/src/run_state.rs`, set `Run.automation` from `state.spec.automation.clone()` instead of always using `None`.
- [ ] Preserve backward compatibility: old run specs and old `run.created` events without `automation` deserialize as `None`.
- [ ] Update all test fixture constructors by setting `automation: None` unless the test specifically checks automation linkage.
- [ ] Add a focused projection test proving `RunCreatedProps.automation` appears in cached `Run.automation`.
- [ ] Run:
```bash
cargo nextest run -p fabro-types
cargo nextest run -p fabro-workflow operations::create
cargo nextest run -p fabro-store run_state
```
- [ ] Commit:
```bash
git add lib/crates/fabro-types lib/crates/fabro-workflow lib/crates/fabro-store
git commit -m "feat: associate runs with automations"
```
## Task 4: Add OpenAPI Contract And Type Reuse
**Files:**
- Modify: `docs/public/api-reference/fabro-api.yaml`
- Modify: `lib/crates/fabro-api/Cargo.toml`
- Modify: `lib/crates/fabro-api/build.rs`
- Create: `lib/crates/fabro-api/tests/automation_round_trip.rs`
- [ ] Add an `Automations` tag.
- [ ] Add schemas for `Automation`, `AutomationTarget`, `AutomationTrigger`, `AutomationApiTrigger`, `AutomationScheduleTrigger`, `CreateAutomationRequest`, `ReplaceAutomationRequest`, `PatchAutomationRequest`, and `AutomationListResponse`.
- [ ] Use OpenAPI discriminator `propertyName: type` for trigger variants.
- [ ] Implement request-body parsing so unknown trigger discriminator values are reported as domain validation errors (`422`), not JSON parse errors (`400`). Use raw DTOs or custom deserialization before converting into `fabro-automation` domain types.
- [ ] Reuse existing `Run` and paginated run envelope schemas for `POST /automations/{id}/runs` and `GET /automations/{id}/runs`.
- [ ] Add response codes:
- `200` for reads and replace/patch.
- `201` for create automation and create run.
- `204` for delete.
- `400` for malformed JSON or invalid path syntax.
- `404` for missing automation.
- `409` for duplicate create, stale revision, disabled automation, or disabled/missing `api` trigger.
- `422` for domain validation errors.
- `428` for missing `If-Match` on `PUT`, `PATCH`, or `DELETE`.
- [ ] Add `If-Match` header parameters for mutating path operations except `POST /automations`.
- [ ] Add `ETag` response header on `GET /automations/{id}`, `PUT`, and `PATCH`.
- [ ] Before adding generated duplicate Rust types, search for matching domain types. If `fabro-automation` serde shape matches a schema exactly, add a `with_replacement(...)` entry in `lib/crates/fabro-api/build.rs`.
- [ ] Add JSON parity tests for every automation replacement type used by `fabro-api`.
- [ ] Run `cargo build -p fabro-api`.
- [ ] Commit:
```bash
git add docs/public/api-reference/fabro-api.yaml lib/crates/fabro-api
git commit -m "feat: define automations API contract"
```
## Task 5: Wire Automation Store Into Server State
**Files:**
- Modify: `lib/crates/fabro-server/Cargo.toml`
- Modify: `lib/crates/fabro-server/src/server.rs`
- Modify: `lib/crates/fabro-server/src/test_support.rs`
- [ ] Add `fabro-automation = { path = "../fabro-automation" }` to server dependencies.
- [ ] Add `automation_store: Arc<AutomationStore>` to `AppState`.
- [ ] In `build_app_state`, compute the automation directory as:
```rust
let automation_dir = active_config_path
.parent()
.unwrap_or_else(|| std::path::Path::new("."))
.join("automations");
```
- [ ] Load `AutomationStore::load(automation_dir)` before constructing `AppState`.
- [ ] Fail server startup if an existing automation file is malformed.
- [ ] Add `pub(crate) fn automation_store(&self) -> Arc<AutomationStore>`.
- [ ] In test support, keep the existing temp `active_config_path` behavior so each test gets its own sibling `automations` directory.
- [ ] Add a server unit test for empty automation store creation when no automation directory exists.
- [ ] Run `cargo nextest run -p fabro-server automation_store`.
- [ ] Commit:
```bash
git add lib/crates/fabro-server
git commit -m "feat: load automation store in server state"
```
## Task 6: Add Automation CRUD Routes
**Files:**
- Create: `lib/crates/fabro-server/src/server/handler/automations.rs`
- Modify: `lib/crates/fabro-server/src/server/handler/mod.rs`
- Create: `lib/crates/fabro-server/tests/it/api/automations.rs`
- Modify: `lib/crates/fabro-server/tests/it/api/mod.rs`
- [ ] Read `docs/internal/logging-strategy.md` and `docs/internal/error-handling-strategy.md` before adding request errors or logs.
- [ ] Implement `automations::routes()` and merge it into `handler::real_routes()`.
- [ ] Use `RequiredUser` for CRUD routes.
- [ ] Implement `GET /automations` by listing store entries, sorting by ID ascending, and returning `{ data, meta: { total } }`.
- [ ] Implement `POST /automations` with `CreateAutomationRequest`; duplicate ID returns `409`.
- [ ] Implement `GET /automations/{id}` with `ETag: "<revision>"`.
- [ ] Implement `PUT /automations/{id}` with `ReplaceAutomationRequest` and required `If-Match`.
- [ ] Implement `PATCH /automations/{id}` with `PatchAutomationRequest`, shallow patch semantics, and required `If-Match`.
- [ ] Implement `DELETE /automations/{id}` with required `If-Match`.
- [ ] Add a helper that parses a quoted or unquoted `If-Match` revision and rejects missing headers with `428`.
- [ ] Map `AutomationStoreError` to `ApiError`:
- not found to `404`
- already exists to `409`
- missing revision to `428`
- revision mismatch to `409`
- validation to `422`
- parse/I/O to `500` except malformed request bodies, which stay `400`
- [ ] Add route tests for empty list, create, duplicate create, get with ETag, replace, stale replace, missing `If-Match`, patch clearing description, delete, invalid trigger IDs, duplicate trigger IDs, second trigger with `type = "api"`, and invalid schedule expression.
- [ ] Run `cargo nextest run -p fabro-server automations`.
- [ ] Commit:
```bash
git add lib/crates/fabro-server
git commit -m "feat: add automation CRUD API"
```
## Task 7: Add Automation Run Listing And API-Triggered Runs
**Files:**
- Create: `lib/crates/fabro-server/src/automation_materializer.rs`
- Modify: `lib/crates/fabro-server/src/server.rs`
- Modify: `lib/crates/fabro-server/src/server/handler/runs.rs`
- Modify: `lib/crates/fabro-server/src/server/handler/automations.rs`
- Modify: `lib/crates/fabro-server/src/test_support.rs`
- Create: `lib/crates/fabro-server/tests/it/api/automations.rs`
- Modify: `lib/crates/fabro-server/tests/it/api/mod.rs`
- [ ] Extract the common run creation body from `handler/runs.rs::create_run` into a crate-private helper that accepts:
```rust
struct CreateRunFromManifestRequest {
manifest: fabro_api::types::RunManifest,
submitted_manifest_bytes: Vec<u8>,
explicit_run_id: Option<fabro_types::RunId>,
explicit_title_supplied: bool,
actor: fabro_types::Principal,
headers: axum::http::HeaderMap,
automation: Option<fabro_types::AutomationRef>,
}
```
- [ ] Keep `POST /runs` behavior unchanged by calling the helper with `automation: None`.
- [ ] Define a crate-private materializer trait:
```rust
pub(crate) struct AutomationRunMaterializeInput {
pub automation_id: fabro_automation::AutomationId,
pub target: fabro_automation::AutomationTarget,
pub run_id: fabro_types::RunId,
pub user_settings_path: std::path::PathBuf,
pub temp_root: std::path::PathBuf,
}
pub(crate) struct AutomationRunMaterialized {
pub manifest: fabro_api::types::RunManifest,
pub submitted_manifest_bytes: Vec<u8>,
}
#[derive(thiserror::Error, Debug)]
pub(crate) enum AutomationRunMaterializeError {
#[error("invalid automation target: {0}")]
InvalidTarget(String),
#[error("failed to clone automation repository: {0}")]
CloneFailed(String),
#[error("failed to resolve automation workflow: {0}")]
WorkflowNotFound(String),
#[error("failed to build run manifest: {0}")]
Manifest(String),
}
#[async_trait::async_trait]
pub(crate) trait AutomationRunMaterializer: Send + Sync {
async fn materialize(
&self,
input: AutomationRunMaterializeInput,
) -> Result<AutomationRunMaterialized, AutomationRunMaterializeError>;
}
```
- [ ] Use a production implementation that:
- validates target repository as GitHub `owner/repo`
- is constructed with the server GitHub credentials, GitHub API base URL, HTTP client, and cleanup policy needed for clone materialization
- creates a per-run temp directory under `AutomationRunMaterializeInput.temp_root`
- clones `https://github.com/{owner}/{repo}.git`
- uses existing GitHub clone credential helpers when configured
- checks out the configured `ref`
- resolves the workflow selector using `fabro_config::project::WorkflowLocation::resolve`
- builds a `RunManifest` with `fabro_manifest::build_run_manifest`
- passes `user_settings_path: Some(state.active_config_path().to_path_buf())`
- [ ] Use `tokio::process::Command` with argv values for git commands. Do not construct shell command strings. Set `GIT_TERMINAL_PROMPT=0` and explicit timeouts so private-repo credential failures cannot hang request handling.
- [ ] Store only sanitized repository URLs in run metadata. Do not persist credentialed clone URLs.
- [ ] Add test support injection for a fake `AutomationRunMaterializer` behind tests or the existing `test-support` feature.
- [ ] Implement `GET /automations/{id}/runs`:
- require the automation to exist
- list cached runs from the store
- filter by `run.automation.as_ref().is_some_and(|a| a.id == id)`
- sort newest first
- paginate with `page[limit]` and `page[offset]`
- return the existing `{ data, meta }` list shape
- [ ] Implement `POST /automations/{id}/runs`:
- use `RequiredRunToolActor`
- require automation `enabled == true`
- find the enabled trigger with `type = "api"`
- return `409` with API error code `automation_api_trigger_disabled` if not startable
- materialize the run manifest
- call the shared create-run helper with `AutomationRef { id, name, trigger_id: Some(api_trigger_id) }`
- return `201` and the created `Run`
- [ ] Add route tests using the fake materializer for disabled automation, disabled API trigger, successful run creation, persisted `Run.automation`, and associated run listing.
- [ ] Add lower-level materializer tests for target URL construction, credential redaction, ref checkout command planning, and workflow path resolution using temp directories. Do not add a live GitHub test.
- [ ] Run `cargo nextest run -p fabro-server automations`.
- [ ] Commit:
```bash
git add lib/crates/fabro-server
git commit -m "feat: start runs from automations"
```
## Task 8: Generate Clients And Final Verification
**Files:**
- Modify generated files under `lib/packages/fabro-api-client`
- Modify generated Rust files under `lib/crates/fabro-api/src` if `cargo build -p fabro-api` updates them
- [ ] Regenerate Rust API code:
```bash
cargo build -p fabro-api
```
- [ ] Regenerate the TypeScript API client:
```bash
cd lib/packages/fabro-api-client && bun run generate
```
- [ ] Confirm no web UI imports or CLI command modules changed:
```bash
git diff -- apps/fabro-web lib/crates/fabro-cli
```
Expected: no application or CLI command changes caused by this plan.
- [ ] Run focused tests:
```bash
cargo nextest run -p fabro-automation
cargo nextest run -p fabro-api
cargo nextest run -p fabro-server automations
cargo nextest run -p fabro-server openapi_conformance
```
- [ ] Run broader checks:
```bash
cargo +nightly-2026-04-14 fmt --check --all
cargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warnings
```
- [ ] If clippy or tests expose unrelated existing failures, record the exact failing command and failure summary in the implementation handoff.
- [ ] Commit generated and verification fixes:
```bash
git add docs/public/api-reference/fabro-api.yaml lib/crates lib/packages/fabro-api-client
git commit -m "chore: regenerate automation API clients"
```
## Acceptance Criteria
- A server with no `automations/` directory starts and returns an empty automation list.
- Creating an automation writes `dirname(active_config_path)/automations/<id>.toml`.
- Updating or deleting an automation requires `If-Match`.
- Stale revisions are rejected.
- Invalid automation and trigger shapes are rejected with `422`.
- Disabling the `api` trigger makes the automation not startable through `POST /automations/{id}/runs`.
- A successful API-triggered automation run returns a normal `Run` response with `automation.id`, `automation.name`, and `automation.trigger_id`.
- `GET /automations/{id}/runs` returns runs linked to that automation.
- No cron scheduler, web UI exposure, or CLI exposure is added.
## Completed stages
- **toolchain**: succeeded
- Script: `command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1`
- Output:
```
cargo 1.95.0 (f2d3ce0bd 2026-03-21)
```
- **preflight_compile**: succeeded
- Script: `cargo check -q --workspace 2>&1`
- Output: (empty)
- **preflight_lint**: succeeded
- Script: `cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1`
- Output: (empty)
- **fix_lints**: succeeded
- Model: claude-opus-4-7, 15.2k tokens in / 1.3k out
- Files: /home/daytona/workspace/fabro/lib/crates/fabro-store/src/run_state.rs
- **preflight_lint**: succeeded
- Script: `cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1`
- Output: (empty)
- **implement**: succeeded
- Model: gpt-5.5, 8.8m tokens in / 26.1k out
- Files: /home/daytona/workspace/fabro/lib/crates/fabro-api/tests/automation_round_trip.rs, /home/daytona/workspace/fabro/lib/crates/fabro-server/src/automation_materializer.rs, /home/daytona/workspace/fabro/lib/crates/fabro-server/src/server/handler/automations.rs, /home/daytona/workspace/fabro/lib/crates/fabro-server/tests/it/api/automations.rs
- **simplify_opus**: succeeded
- Model: claude-opus-4-7, 165.4k tokens in / 58.2k out
- Files: /home/daytona/workspace/fabro/lib/crates/fabro-api/tests/automation_round_trip.rs, /home/daytona/workspace/fabro/lib/crates/fabro-automation/Cargo.toml, /home/daytona/workspace/fabro/lib/crates/fabro-automation/src/error.rs, /home/daytona/workspace/fabro/lib/crates/fabro-automation/src/lib.rs, /home/daytona/workspace/fabro/lib/crates/fabro-automation/src/model.rs, /home/daytona/workspace/fabro/lib/crates/fabro-automation/src/store.rs, /home/daytona/workspace/fabro/lib/crates/fabro-server/src/automation_materializer.rs, /home/daytona/workspace/fabro/lib/crates/fabro-server/src/server/handler/automations.rs
# Simplify: Code Review and Cleanup
Review changes vs. origin for reuse, quality, and efficiency. Fix any issues found.
## Phase 1: Identify Changes
Run git diff (or git diff HEAD if there are staged changes) to see what changed. If there are no git changes, review the most recently modified files that the user mentioned or that you edited earlier in this conversation.
## Phase 2: Launch Three Review Agents in Parallel
Use the Agent tool to launch all three agents concurrently in a single message. Pass each agent the full diff so it has the complete context.
### Agent 1: Code Reuse Review
For each change:
1. Search for existing utilities and helpers that could replace newly written code. Use Grep to find similar patterns elsewhere in the codebase — common locations are utility directories, shared modules, and files adjacent to the changed ones.
2. Flag any new function that duplicates existing functionality. Suggest the existing function to use instead.
3. Flag any inline logic that could use an existing utility — hand-rolled string manipulation, manual path handling, custom environment checks, ad-hoc type guards, and similar patterns are common candidates.
Note: This is a greenfield app, so focus on maximizing simplicity and don't worry about changing things to achieve it.
### Agent 2: Code Quality Review
Review the same changes for hacky patterns:
1. Redundant state: state that duplicates existing state, cached values that could be derived, observers/effects that could be direct calls
2. Parameter sprawl: adding new parameters to a function instead of generalizing or restructuring existing ones
3. Copy-paste with slight variation: near-duplicate code blocks that should be unified with a shared abstraction
4. Leaky abstractions: exposing internal details that should be encapsulated, or breaking existing abstraction boundaries
5. Stringly-typed code: using raw strings where constants, enums (string unions), or branded types already exist in the codebase
Note: This is a greenfield app, so be aggressive in optimizing quality.
### Agent 3: Efficiency Review
Review the same changes for efficiency:
1. Unnecessary work: redundant computations, repeated file reads, duplicate network/API calls, N+1 patterns
2. Missed concurrency: independent operations run sequentially when they could run in parallel
3. Hot-path bloat: new blocking work added to startup or per-request/per-render hot paths
4. Unnecessary existence checks: pre-checking file/resource existence before operating (TOCTOU anti-pattern) — operate directly and handle the error
5. Memory: unbounded data structures, missing cleanup, event listener leaks
6. Overly broad operations: reading entire files when only a portion is needed, loading all items when filtering for one
## Phase 3: Fix Issues
Wait for all three agents to complete. Aggregate their findings and fix each issue directly. If a finding is a false positive or not worth addressing, note it and move on — do not argue with the finding, just skip it.
When done, briefly summarize what was fixed (or confirm the code was already clean).

View file

@ -0,0 +1,5 @@
{
"mode": "agent",
"provider": "openai",
"model": "gpt-5.5"
}

View file

@ -0,0 +1,16 @@
Cleanup complete.
Fixed:
- `lib/crates/fabro-server/src/automation_materializer.rs`
- Corrected the materializer workflow path test to use `flows/deps.fabro`.
- The previous extensionless `flows/deps` was treated by `WorkflowLocation::resolve` as a workflow selector/literal and failed with `workflow not found`.
Validated:
- `cargo nextest run -p fabro-automation`
- `cargo nextest run -p fabro-server 'automation_'`
- `cargo nextest run -p fabro-api automation`
- `cargo +nightly-2026-04-14 fmt --check --all`
- `cargo +nightly-2026-04-14 clippy -q -p fabro-server --all-targets -- -D warnings`
Working tree now has one cleanup change:
- `M lib/crates/fabro-server/src/automation_materializer.rs`