From 86b9c2e8105fa56a4a78ef7ee95bc89f8587e4c9 Mon Sep 17 00:00:00 2001 From: Fabro Date: Sun, 24 May 2026 20:27:04 -0400 Subject: [PATCH] =?UTF-8?q?checkpoint=20=E2=9A=92=EF=B8=8F=20Generated=20w?= =?UTF-8?q?ith=20[Fabro](https://fabro.sh)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- run.json | 506 ++++++++++++- stages/006-preflight_lint@2/output.log | 1 + .../006-preflight_lint@2/script_timing.json | 8 + stages/006-preflight_lint@2/status.json | 6 + stages/007-implement@1/prompt.md | 682 ++++++++++++++++++ stages/007-implement@1/provider_used.json | 6 + stages/007-implement@1/response.md | 78 ++ 7 files changed, 1266 insertions(+), 21 deletions(-) create mode 100644 stages/006-preflight_lint@2/output.log create mode 100644 stages/006-preflight_lint@2/script_timing.json create mode 100644 stages/006-preflight_lint@2/status.json create mode 100644 stages/007-implement@1/prompt.md create mode 100644 stages/007-implement@1/provider_used.json create mode 100644 stages/007-implement@1/response.md diff --git a/run.json b/run.json index 17df88548..56c9c09a9 100644 --- a/run.json +++ b/run.json @@ -490,7 +490,7 @@ "kind": "running" }, "status_updated_at": "2026-05-24T22:46:50.147828Z", - "last_event_at": "2026-05-24T22:52:27.119064Z", + "last_event_at": "2026-05-25T00:27:04.329516Z", "pending_control": null, "checkpoints": [ { @@ -874,9 +874,9 @@ } }, { - "seq": 0, + "seq": 95, "checkpoint": { - "timestamp": "2026-05-24T22:52:44.964088Z", + "timestamp": "2026-05-24T22:52:48.841667Z", "current_node": "preflight_lint", "completed_nodes": [ "start", @@ -888,32 +888,163 @@ ], "node_retries": {}, "context_values": { + "graph.rankdir": "LR", + "internal.retry_count.preflight_compile": 0, + "last_response": "Clippy is now clean across the workspace. The fix collapsed the inner `if props.resume` into a guarded match arm on `EventBody::RunStartRequested`, falling through to the existing wildcard arm for non", + "internal.retry_count.start": 0, + "thread.preflight_compile.current_node": "preflight_lint", + "internal.thread_id": "fix_lints", + "thread.fix_lints.current_node": "preflight_lint", + "command.output": "blob://sha256/12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126", "graph.goal": "# Automations Backend API Implementation Plan\n\n> **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.\n\n**Goal:** Build the backend data model and REST API for creating, editing, deleting, starting, and listing runs for Automations.\n\n**Architecture:** Automations are server-owned runnable bindings stored as one canonical TOML file per automation in `dirname(active_config_path)/automations/.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.\n\n**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.\n\n---\n\n## Locked Decisions\n\n- Backend only: do not add web UI routes/components and do not add CLI commands.\n- Storage root: `dirname(active_config_path)/automations`.\n- File layout: one automation per file, `automations/.toml`.\n- Canonical ID: the filename stem. The TOML file does not repeat `id`.\n- Automation ID format: `[a-z0-9][a-z0-9-]{0,62}`.\n- Trigger ID format: `[a-z0-9][a-z0-9_-]{0,62}`.\n- Trigger IDs are required, user-visible, editable, and unique within one automation.\n- Triggers are an array from v1.\n- 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\"`.\n- At most one trigger with `type = \"api\"` is allowed per automation.\n- Multiple `schedule` triggers are allowed.\n- Unknown trigger types, including future `event` shapes, return `422` in v1. Handlers must not let unknown trigger discriminators fail as JSON parse errors.\n- 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.\n- API writes canonicalize TOML and may discard comments in automation files.\n- 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.\n\n## File Structure\n\nCreate:\n\n- `lib/crates/fabro-automation/Cargo.toml` - domain crate manifest.\n- `lib/crates/fabro-automation/src/lib.rs` - public exports.\n- `lib/crates/fabro-automation/src/error.rs` - validation and persistence errors.\n- `lib/crates/fabro-automation/src/id.rs` - `AutomationId` and `AutomationTriggerId`.\n- `lib/crates/fabro-automation/src/model.rs` - automation domain and serde/TOML model.\n- `lib/crates/fabro-automation/src/store.rs` - in-memory file-backed automation store.\n- `lib/crates/fabro-server/src/automation_materializer.rs` - GitHub target materialization and manifest building for automation runs.\n- `lib/crates/fabro-server/src/server/handler/automations.rs` - REST handlers and router.\n- `lib/crates/fabro-server/tests/it/api/automations.rs` - server API integration tests.\n- `lib/crates/fabro-server/tests/it/api/mod.rs` - wire the automations integration test module.\n\nModify:\n\n- `lib/crates/fabro-server/Cargo.toml` - add `fabro-automation`.\n- `lib/crates/fabro-api/Cargo.toml` - add `fabro-automation` so OpenAPI can reuse matching automation domain types.\n- `lib/crates/fabro-types/src/run_summary.rs` - extend `AutomationRef` with `trigger_id`.\n- `lib/crates/fabro-types/src/run.rs` - add `automation: Option` to `RunSpec`.\n- `lib/crates/fabro-types/src/run_event/run.rs` - add `automation: Option` to `RunCreatedProps`.\n- `lib/crates/fabro-workflow/src/operations/create.rs` - carry automation metadata through `CreateRunInput`, persistence options, `RunSpec`, and `run.created`.\n- `lib/crates/fabro-workflow/src/event/convert.rs` - preserve automation metadata in any legacy-to-current event conversion path that constructs `RunCreatedProps`.\n- `lib/crates/fabro-store/src/run_state.rs` - project `RunSpec.automation` into `Run.automation`.\n- `lib/crates/fabro-server/src/server.rs` - load the automation store into `AppState` and expose crate-private accessors.\n- `lib/crates/fabro-server/src/server/handler/mod.rs` - merge real automation routes.\n- `lib/crates/fabro-server/src/test_support.rs` - create temp automation storage by active config path and allow test-only materializer injection.\n- `docs/public/api-reference/fabro-api.yaml` - add automation paths and schemas.\n- `lib/crates/fabro-api/build.rs` - add replacement mappings only for domain types with identical wire shape.\n- `lib/crates/fabro-api/tests/*` - add JSON parity tests for reused automation types.\n- `lib/packages/fabro-api-client` - regenerate generated TypeScript client files only; do not import them from the web UI.\n\nDo not modify:\n\n- `apps/fabro-web/**`, except generated API package consumers are not touched.\n- CLI command modules.\n- Scheduler services or background run loops.\n\n## Public API Shape\n\nAdd these OpenAPI paths under `/api/v1`:\n\n```http\nGET /automations\nPOST /automations\nGET /automations/{id}\nPUT /automations/{id}\nPATCH /automations/{id}\nDELETE /automations/{id}\nGET /automations/{id}/runs\nPOST /automations/{id}/runs\n```\n\nUse this response model:\n\n```ts\ntype Automation = {\n id: string;\n revision: string;\n name: string;\n description: string | null;\n enabled: boolean;\n target: AutomationTarget;\n triggers: AutomationTrigger[];\n};\n\ntype AutomationTarget = {\n repository: string; // GitHub owner/repo\n ref: string;\n workflow: string;\n};\n\ntype AutomationTrigger =\n | { id: string; type: \"api\"; enabled: boolean }\n | { id: string; type: \"schedule\"; enabled: boolean; expression: string };\n\n```\n\nRequest models:\n\n```ts\ntype CreateAutomationRequest = {\n id: string;\n name: string;\n description?: string | null;\n enabled?: boolean;\n target: AutomationTarget;\n triggers: AutomationTrigger[];\n};\n\ntype ReplaceAutomationRequest = {\n name: string;\n description?: string | null;\n enabled: boolean;\n target: AutomationTarget;\n triggers: AutomationTrigger[];\n};\n\ntype PatchAutomationRequest = {\n name?: string;\n description?: string | null;\n enabled?: boolean;\n target?: AutomationTarget;\n triggers?: AutomationTrigger[];\n};\n```\n\n`GET /automations/{id}/runs` returns the existing paginated run list envelope:\n\n```json\n{\n \"data\": [],\n \"meta\": { \"has_more\": false, \"total\": 0 }\n}\n```\n\nIt accepts `page[limit]` and `page[offset]`, sorts newest first, filters by `Run.automation.id`, and returns `404` if the automation definition no longer exists.\n\n`POST /automations/{id}/runs` returns the existing `Run` response shape with `automation` populated:\n\n```json\n{\n \"automation\": {\n \"id\": \"nightly-deps\",\n \"name\": \"Nightly dependency update\",\n \"trigger_id\": \"api\"\n }\n}\n```\n\n## TOML Shape\n\nPersist this canonical TOML:\n\n```toml\nname = \"Nightly dependency update\"\ndescription = \"Open a PR for dependency updates.\"\nenabled = true\n\n[target]\nrepository = \"fabro-sh/fabro\"\nref = \"main\"\nworkflow = \"dependency-update\"\n\n[[triggers]]\nid = \"api\"\ntype = \"api\"\nenabled = false\n\n[[triggers]]\nid = \"nightly\"\ntype = \"schedule\"\nenabled = true\nexpression = \"0 3 * * *\"\n```\n\nDefaults:\n\n- `enabled` defaults to `true` when omitted in TOML or create requests.\n- `description` defaults to `null`.\n- Trigger `enabled` defaults to `true` when omitted in TOML or create requests.\n- `schedule.expression` must be a non-empty five-field cron expression accepted by `croner`.\n- `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.\n- `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.\n- `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.\n\n## Task 1: Add Domain Crate And Model Tests\n\n**Files:**\n\n- Create: `lib/crates/fabro-automation/Cargo.toml`\n- Create: `lib/crates/fabro-automation/src/lib.rs`\n- Create: `lib/crates/fabro-automation/src/error.rs`\n- Create: `lib/crates/fabro-automation/src/id.rs`\n- Create: `lib/crates/fabro-automation/src/model.rs`\n\n- [ ] Read `docs/internal/testing-strategy.md` and `docs/internal/error-handling-strategy.md` before adding tests and error types.\n- [ ] Create the crate. Because the workspace uses `members = [\"lib/crates/*\"]`, no root workspace member edit is required.\n- [ ] Add dependencies in `lib/crates/fabro-automation/Cargo.toml`: `chrono`, `croner`, `hex`, `serde`, `sha2`, `thiserror`, `tokio`, `toml`, and `toml_edit`. Add dev-dependencies: `tempfile`.\n- [ ] Define `AutomationId` and `AutomationTriggerId` newtypes with `TryFrom`, `AsRef`, `Display`, `Serialize`, and `Deserialize`.\n- [ ] Define the domain model with this public shape:\n\n```rust\npub struct AutomationRevision(String);\n\npub struct RepositorySlug(String);\n\npub struct GitRefSelector(String);\n\npub struct WorkflowSlug(String);\n\npub struct Automation {\n pub id: AutomationId,\n pub revision: AutomationRevision,\n pub name: String,\n pub description: Option,\n pub enabled: bool,\n pub target: AutomationTarget,\n pub triggers: Vec,\n}\n\npub struct AutomationTarget {\n pub repository: RepositorySlug,\n pub ref_: GitRefSelector,\n pub workflow: WorkflowSlug,\n}\n\n#[serde(tag = \"type\", rename_all = \"snake_case\")]\npub enum AutomationTrigger {\n Api(ApiTrigger),\n Schedule(ScheduleTrigger),\n}\n\npub struct ApiTrigger {\n pub id: AutomationTriggerId,\n pub enabled: bool,\n}\n\npub struct ScheduleTrigger {\n pub id: AutomationTriggerId,\n pub enabled: bool,\n pub expression: String,\n}\n\npub struct AutomationDraft {\n pub id: AutomationId,\n pub name: String,\n pub description: Option,\n pub enabled: Option,\n pub target: AutomationTarget,\n pub triggers: Vec,\n}\n\npub struct AutomationReplace {\n pub name: String,\n pub description: Option,\n pub enabled: bool,\n pub target: AutomationTarget,\n pub triggers: Vec,\n}\n\npub struct AutomationPatch {\n pub name: Option,\n pub description: Option>,\n pub enabled: Option,\n pub target: Option,\n pub triggers: Option>,\n}\n```\n\n- [ ] Use `#[serde(rename = \"ref\")]` for the Rust field `ref_`.\n- [ ] Keep `revision` out of the persisted TOML model; compute it from raw file bytes.\n- [ ] Reject empty names, invalid GitHub repository slugs, invalid refs, invalid workflow selectors, duplicate trigger IDs, and more than one trigger with `type = \"api\"`.\n- [ ] 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.\n- [ ] Run `cargo nextest run -p fabro-automation`.\n- [ ] Commit:\n\n```bash\ngit add lib/crates/fabro-automation\ngit commit -m \"feat: add automation domain model\"\n```\n\n## Task 2: Implement File-Backed Automation Store\n\n**Files:**\n\n- Create: `lib/crates/fabro-automation/src/store.rs`\n- Modify: `lib/crates/fabro-automation/src/lib.rs`\n\n- [ ] Implement `AutomationStore` as an in-memory map guarded by `tokio::sync::RwLock`.\n- [ ] Load files from a configured directory with this behavior:\n - Missing directory means an empty store.\n - Non-`.toml` files are ignored.\n - Invalid filenames fail load.\n - Invalid TOML or invalid automation data fails load.\n- [ ] Compute `AutomationRevision` as lowercase hex SHA-256 of the exact TOML bytes read from disk.\n- [ ] Expose these async methods:\n\n```rust\npub async fn load(dir: impl Into) -> Result;\npub async fn list(&self) -> Vec;\npub async fn get(&self, id: &AutomationId) -> Option;\npub async fn create(&self, draft: AutomationDraft) -> Result;\npub async fn replace(\n &self,\n id: &AutomationId,\n expected: &AutomationRevision,\n draft: AutomationReplace,\n) -> Result;\npub async fn patch(\n &self,\n id: &AutomationId,\n expected: &AutomationRevision,\n patch: AutomationPatch,\n) -> Result;\npub async fn delete(\n &self,\n id: &AutomationId,\n expected: &AutomationRevision,\n) -> Result<(), AutomationStoreError>;\n```\n\n- [ ] 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.\n- [ ] Create the automation directory on first write.\n- [ ] Map store errors into precise variants: not found, already exists, missing revision, revision mismatch, validation, parse, and I/O.\n- [ ] 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.\n- [ ] Run `cargo nextest run -p fabro-automation`.\n- [ ] Commit:\n\n```bash\ngit add lib/crates/fabro-automation\ngit commit -m \"feat: persist automations as TOML files\"\n```\n\n## Task 3: Carry Automation Metadata Through Runs\n\n**Files:**\n\n- Modify: `lib/crates/fabro-types/src/run_summary.rs`\n- Modify: `lib/crates/fabro-types/src/run.rs`\n- Modify: `lib/crates/fabro-types/src/run_event/run.rs`\n- Modify: `lib/crates/fabro-workflow/src/operations/create.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/convert.rs`\n- Modify: `lib/crates/fabro-store/src/run_state.rs`\n- Modify tests that construct `RunSpec` or `RunCreatedProps`\n\n- [ ] Extend `AutomationRef`:\n\n```rust\npub struct AutomationRef {\n pub id: String,\n #[serde(default)]\n pub name: Option,\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n pub trigger_id: Option,\n}\n```\n\n- [ ] Add `automation: Option` to `RunSpec` with `#[serde(default, skip_serializing_if = \"Option::is_none\")]`.\n- [ ] Add `automation: Option` to `RunCreatedProps` with the same serde behavior.\n- [ ] Add `automation: Option` to `fabro_workflow::operations::CreateRunInput`.\n- [ ] Thread the field through `PersistCreateOptions`, the `RunSpec` built in `persist_validated`, and the `Event::RunCreated` emitted in `persist_created_run`.\n- [ ] In `fabro-store/src/run_state.rs`, set `Run.automation` from `state.spec.automation.clone()` instead of always using `None`.\n- [ ] Preserve backward compatibility: old run specs and old `run.created` events without `automation` deserialize as `None`.\n- [ ] Update all test fixture constructors by setting `automation: None` unless the test specifically checks automation linkage.\n- [ ] Add a focused projection test proving `RunCreatedProps.automation` appears in cached `Run.automation`.\n- [ ] Run:\n\n```bash\ncargo nextest run -p fabro-types\ncargo nextest run -p fabro-workflow operations::create\ncargo nextest run -p fabro-store run_state\n```\n\n- [ ] Commit:\n\n```bash\ngit add lib/crates/fabro-types lib/crates/fabro-workflow lib/crates/fabro-store\ngit commit -m \"feat: associate runs with automations\"\n```\n\n## Task 4: Add OpenAPI Contract And Type Reuse\n\n**Files:**\n\n- Modify: `docs/public/api-reference/fabro-api.yaml`\n- Modify: `lib/crates/fabro-api/Cargo.toml`\n- Modify: `lib/crates/fabro-api/build.rs`\n- Create: `lib/crates/fabro-api/tests/automation_round_trip.rs`\n\n- [ ] Add an `Automations` tag.\n- [ ] Add schemas for `Automation`, `AutomationTarget`, `AutomationTrigger`, `AutomationApiTrigger`, `AutomationScheduleTrigger`, `CreateAutomationRequest`, `ReplaceAutomationRequest`, `PatchAutomationRequest`, and `AutomationListResponse`.\n- [ ] Use OpenAPI discriminator `propertyName: type` for trigger variants.\n- [ ] 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.\n- [ ] Reuse existing `Run` and paginated run envelope schemas for `POST /automations/{id}/runs` and `GET /automations/{id}/runs`.\n- [ ] Add response codes:\n - `200` for reads and replace/patch.\n - `201` for create automation and create run.\n - `204` for delete.\n - `400` for malformed JSON or invalid path syntax.\n - `404` for missing automation.\n - `409` for duplicate create, stale revision, disabled automation, or disabled/missing `api` trigger.\n - `422` for domain validation errors.\n - `428` for missing `If-Match` on `PUT`, `PATCH`, or `DELETE`.\n- [ ] Add `If-Match` header parameters for mutating path operations except `POST /automations`.\n- [ ] Add `ETag` response header on `GET /automations/{id}`, `PUT`, and `PATCH`.\n- [ ] 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`.\n- [ ] Add JSON parity tests for every automation replacement type used by `fabro-api`.\n- [ ] Run `cargo build -p fabro-api`.\n- [ ] Commit:\n\n```bash\ngit add docs/public/api-reference/fabro-api.yaml lib/crates/fabro-api\ngit commit -m \"feat: define automations API contract\"\n```\n\n## Task 5: Wire Automation Store Into Server State\n\n**Files:**\n\n- Modify: `lib/crates/fabro-server/Cargo.toml`\n- Modify: `lib/crates/fabro-server/src/server.rs`\n- Modify: `lib/crates/fabro-server/src/test_support.rs`\n\n- [ ] Add `fabro-automation = { path = \"../fabro-automation\" }` to server dependencies.\n- [ ] Add `automation_store: Arc` to `AppState`.\n- [ ] In `build_app_state`, compute the automation directory as:\n\n```rust\nlet automation_dir = active_config_path\n .parent()\n .unwrap_or_else(|| std::path::Path::new(\".\"))\n .join(\"automations\");\n```\n\n- [ ] Load `AutomationStore::load(automation_dir)` before constructing `AppState`.\n- [ ] Fail server startup if an existing automation file is malformed.\n- [ ] Add `pub(crate) fn automation_store(&self) -> Arc`.\n- [ ] In test support, keep the existing temp `active_config_path` behavior so each test gets its own sibling `automations` directory.\n- [ ] Add a server unit test for empty automation store creation when no automation directory exists.\n- [ ] Run `cargo nextest run -p fabro-server automation_store`.\n- [ ] Commit:\n\n```bash\ngit add lib/crates/fabro-server\ngit commit -m \"feat: load automation store in server state\"\n```\n\n## Task 6: Add Automation CRUD Routes\n\n**Files:**\n\n- Create: `lib/crates/fabro-server/src/server/handler/automations.rs`\n- Modify: `lib/crates/fabro-server/src/server/handler/mod.rs`\n- Create: `lib/crates/fabro-server/tests/it/api/automations.rs`\n- Modify: `lib/crates/fabro-server/tests/it/api/mod.rs`\n\n- [ ] Read `docs/internal/logging-strategy.md` and `docs/internal/error-handling-strategy.md` before adding request errors or logs.\n- [ ] Implement `automations::routes()` and merge it into `handler::real_routes()`.\n- [ ] Use `RequiredUser` for CRUD routes.\n- [ ] Implement `GET /automations` by listing store entries, sorting by ID ascending, and returning `{ data, meta: { total } }`.\n- [ ] Implement `POST /automations` with `CreateAutomationRequest`; duplicate ID returns `409`.\n- [ ] Implement `GET /automations/{id}` with `ETag: \"\"`.\n- [ ] Implement `PUT /automations/{id}` with `ReplaceAutomationRequest` and required `If-Match`.\n- [ ] Implement `PATCH /automations/{id}` with `PatchAutomationRequest`, shallow patch semantics, and required `If-Match`.\n- [ ] Implement `DELETE /automations/{id}` with required `If-Match`.\n- [ ] Add a helper that parses a quoted or unquoted `If-Match` revision and rejects missing headers with `428`.\n- [ ] Map `AutomationStoreError` to `ApiError`:\n - not found to `404`\n - already exists to `409`\n - missing revision to `428`\n - revision mismatch to `409`\n - validation to `422`\n - parse/I/O to `500` except malformed request bodies, which stay `400`\n- [ ] 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.\n- [ ] Run `cargo nextest run -p fabro-server automations`.\n- [ ] Commit:\n\n```bash\ngit add lib/crates/fabro-server\ngit commit -m \"feat: add automation CRUD API\"\n```\n\n## Task 7: Add Automation Run Listing And API-Triggered Runs\n\n**Files:**\n\n- Create: `lib/crates/fabro-server/src/automation_materializer.rs`\n- Modify: `lib/crates/fabro-server/src/server.rs`\n- Modify: `lib/crates/fabro-server/src/server/handler/runs.rs`\n- Modify: `lib/crates/fabro-server/src/server/handler/automations.rs`\n- Modify: `lib/crates/fabro-server/src/test_support.rs`\n- Create: `lib/crates/fabro-server/tests/it/api/automations.rs`\n- Modify: `lib/crates/fabro-server/tests/it/api/mod.rs`\n\n- [ ] Extract the common run creation body from `handler/runs.rs::create_run` into a crate-private helper that accepts:\n\n```rust\nstruct CreateRunFromManifestRequest {\n manifest: fabro_api::types::RunManifest,\n submitted_manifest_bytes: Vec,\n explicit_run_id: Option,\n explicit_title_supplied: bool,\n actor: fabro_types::Principal,\n headers: axum::http::HeaderMap,\n automation: Option,\n}\n```\n\n- [ ] Keep `POST /runs` behavior unchanged by calling the helper with `automation: None`.\n- [ ] Define a crate-private materializer trait:\n\n```rust\npub(crate) struct AutomationRunMaterializeInput {\n pub automation_id: fabro_automation::AutomationId,\n pub target: fabro_automation::AutomationTarget,\n pub run_id: fabro_types::RunId,\n pub user_settings_path: std::path::PathBuf,\n pub temp_root: std::path::PathBuf,\n}\n\npub(crate) struct AutomationRunMaterialized {\n pub manifest: fabro_api::types::RunManifest,\n pub submitted_manifest_bytes: Vec,\n}\n\n#[derive(thiserror::Error, Debug)]\npub(crate) enum AutomationRunMaterializeError {\n #[error(\"invalid automation target: {0}\")]\n InvalidTarget(String),\n #[error(\"failed to clone automation repository: {0}\")]\n CloneFailed(String),\n #[error(\"failed to resolve automation workflow: {0}\")]\n WorkflowNotFound(String),\n #[error(\"failed to build run manifest: {0}\")]\n Manifest(String),\n}\n\n#[async_trait::async_trait]\npub(crate) trait AutomationRunMaterializer: Send + Sync {\n async fn materialize(\n &self,\n input: AutomationRunMaterializeInput,\n ) -> Result;\n}\n```\n\n- [ ] Use a production implementation that:\n - validates target repository as GitHub `owner/repo`\n - is constructed with the server GitHub credentials, GitHub API base URL, HTTP client, and cleanup policy needed for clone materialization\n - creates a per-run temp directory under `AutomationRunMaterializeInput.temp_root`\n - clones `https://github.com/{owner}/{repo}.git`\n - uses existing GitHub clone credential helpers when configured\n - checks out the configured `ref`\n - resolves the workflow selector using `fabro_config::project::WorkflowLocation::resolve`\n - builds a `RunManifest` with `fabro_manifest::build_run_manifest`\n - passes `user_settings_path: Some(state.active_config_path().to_path_buf())`\n- [ ] 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.\n- [ ] Store only sanitized repository URLs in run metadata. Do not persist credentialed clone URLs.\n- [ ] Add test support injection for a fake `AutomationRunMaterializer` behind tests or the existing `test-support` feature.\n- [ ] Implement `GET /automations/{id}/runs`:\n - require the automation to exist\n - list cached runs from the store\n - filter by `run.automation.as_ref().is_some_and(|a| a.id == id)`\n - sort newest first\n - paginate with `page[limit]` and `page[offset]`\n - return the existing `{ data, meta }` list shape\n- [ ] Implement `POST /automations/{id}/runs`:\n - use `RequiredRunToolActor`\n - require automation `enabled == true`\n - find the enabled trigger with `type = \"api\"`\n - return `409` with API error code `automation_api_trigger_disabled` if not startable\n - materialize the run manifest\n - call the shared create-run helper with `AutomationRef { id, name, trigger_id: Some(api_trigger_id) }`\n - return `201` and the created `Run`\n- [ ] Add route tests using the fake materializer for disabled automation, disabled API trigger, successful run creation, persisted `Run.automation`, and associated run listing.\n- [ ] 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.\n- [ ] Run `cargo nextest run -p fabro-server automations`.\n- [ ] Commit:\n\n```bash\ngit add lib/crates/fabro-server\ngit commit -m \"feat: start runs from automations\"\n```\n\n## Task 8: Generate Clients And Final Verification\n\n**Files:**\n\n- Modify generated files under `lib/packages/fabro-api-client`\n- Modify generated Rust files under `lib/crates/fabro-api/src` if `cargo build -p fabro-api` updates them\n\n- [ ] Regenerate Rust API code:\n\n```bash\ncargo build -p fabro-api\n```\n\n- [ ] Regenerate the TypeScript API client:\n\n```bash\ncd lib/packages/fabro-api-client && bun run generate\n```\n\n- [ ] Confirm no web UI imports or CLI command modules changed:\n\n```bash\ngit diff -- apps/fabro-web lib/crates/fabro-cli\n```\n\nExpected: no application or CLI command changes caused by this plan.\n\n- [ ] Run focused tests:\n\n```bash\ncargo nextest run -p fabro-automation\ncargo nextest run -p fabro-api\ncargo nextest run -p fabro-server automations\ncargo nextest run -p fabro-server openapi_conformance\n```\n\n- [ ] Run broader checks:\n\n```bash\ncargo +nightly-2026-04-14 fmt --check --all\ncargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warnings\n```\n\n- [ ] If clippy or tests expose unrelated existing failures, record the exact failing command and failure summary in the implementation handoff.\n- [ ] Commit generated and verification fixes:\n\n```bash\ngit add docs/public/api-reference/fabro-api.yaml lib/crates lib/packages/fabro-api-client\ngit commit -m \"chore: regenerate automation API clients\"\n```\n\n## Acceptance Criteria\n\n- A server with no `automations/` directory starts and returns an empty automation list.\n- Creating an automation writes `dirname(active_config_path)/automations/.toml`.\n- Updating or deleting an automation requires `If-Match`.\n- Stale revisions are rejected.\n- Invalid automation and trigger shapes are rejected with `422`.\n- Disabling the `api` trigger makes the automation not startable through `POST /automations/{id}/runs`.\n- A successful API-triggered automation run returns a normal `Run` response with `automation.id`, `automation.name`, and `automation.trigger_id`.\n- `GET /automations/{id}/runs` returns runs linked to that automation.\n- No cron scheduler, web UI exposure, or CLI exposure is added.\n", "internal.fidelity": "compact", - "internal.thread_id": "fix_lints", - "thread.start.current_node": "toolchain", - "outcome": "succeeded", - "last_response": "Clippy is now clean across the workspace. The fix collapsed the inner `if props.resume` into a guarded match arm on `EventBody::RunStartRequested`, falling through to the existing wildcard arm for non", - "thread.preflight_compile.current_node": "preflight_lint", + "internal.node_visit_count": 2, + "failure_class": "", + "internal.retry_count.toolchain": 0, + "internal.run_id": "01KSE2PAVXD56N4TWNK4T5H5VA", + "internal.work_dir": "/home/daytona/workspace/fabro", "thread.preflight_lint.current_node": "fix_lints", + "thread.toolchain.current_node": "preflight_compile", + "graph.model_stylesheet": "\n * { model: claude-opus-4-7; }\n ", "internal.retry_count.fix_lints": 0, + "last_stage": "fix_lints", + "outcome": "succeeded", + "internal.retry_count.preflight_lint": 0, + "current_node": "preflight_lint", + "response.fix_lints": "Clippy is now clean across the workspace. The fix collapsed the inner `if props.resume` into a guarded match arm on `EventBody::RunStartRequested`, falling through to the existing wildcard arm for non-resume cases.", + "failure_signature": "", + "thread.start.current_node": "toolchain" + }, + "node_outcomes": { + "start": { + "status": "succeeded", + "usage": null + }, + "fix_lints": { + "status": "succeeded", + "context_updates": { + "last_response": "Clippy is now clean across the workspace. The fix collapsed the inner `if props.resume` into a guarded match arm on `EventBody::RunStartRequested`, falling through to the existing wildcard arm for non", + "last_stage": "fix_lints", + "response.fix_lints": "Clippy is now clean across the workspace. The fix collapsed the inner `if props.resume` into a guarded match arm on `EventBody::RunStartRequested`, falling through to the existing wildcard arm for non-resume cases." + }, + "notes": "Stage completed: fix_lints", + "usage": { + "input": { + "usage": { + "model": { + "provider": "anthropic", + "model_id": "claude-opus-4-7" + }, + "tokens": { + "input_tokens": 15227, + "output_tokens": 1265, + "reasoning_tokens": 0, + "cache_read_tokens": 140948, + "cache_write_tokens": 27045 + } + }, + "facts": { + "algorithm": "anthropic", + "cache_write_5m_tokens": 27045, + "cache_write_1h_tokens": 0 + } + }, + "total_usd_micros": 347265 + }, + "files_touched": [ + "/home/daytona/workspace/fabro/lib/crates/fabro-store/src/run_state.rs" + ] + }, + "preflight_lint": { + "status": "succeeded", + "context_updates": { + "command.output": "blob://sha256/12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126" + }, + "notes": "Script completed: cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1", + "usage": null + }, + "preflight_compile": { + "status": "succeeded", + "context_updates": { + "command.output": "blob://sha256/12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126" + }, + "notes": "Script completed: cargo check -q --workspace 2>&1", + "usage": null + }, + "toolchain": { + "status": "succeeded", + "context_updates": { + "command.output": "blob://sha256/fc14b2ba2d770e5cd3169df7a29525c962adfc4cfa3097b9098c63ebd61a748c" + }, + "notes": "Script completed: 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", + "usage": null + } + }, + "next_node_id": "implement", + "git_commit_sha": "2a9ad6f0c164a5da4452c36f6c13517f68307651", + "loop_failure_signatures": { + "preflight_lint|deterministic|script failed with exit code: ## output error: this `if` can be collapsed into the outer `match` --> lib/crates/fabro-store/src/run_state.rs:: | | / if props.resume { | | self.try_apply_status(runstatus::submitted,ts)?; **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.\n\n**Goal:** Build the backend data model and REST API for creating, editing, deleting, starting, and listing runs for Automations.\n\n**Architecture:** Automations are server-owned runnable bindings stored as one canonical TOML file per automation in `dirname(active_config_path)/automations/.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.\n\n**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.\n\n---\n\n## Locked Decisions\n\n- Backend only: do not add web UI routes/components and do not add CLI commands.\n- Storage root: `dirname(active_config_path)/automations`.\n- File layout: one automation per file, `automations/.toml`.\n- Canonical ID: the filename stem. The TOML file does not repeat `id`.\n- Automation ID format: `[a-z0-9][a-z0-9-]{0,62}`.\n- Trigger ID format: `[a-z0-9][a-z0-9_-]{0,62}`.\n- Trigger IDs are required, user-visible, editable, and unique within one automation.\n- Triggers are an array from v1.\n- 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\"`.\n- At most one trigger with `type = \"api\"` is allowed per automation.\n- Multiple `schedule` triggers are allowed.\n- Unknown trigger types, including future `event` shapes, return `422` in v1. Handlers must not let unknown trigger discriminators fail as JSON parse errors.\n- 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.\n- API writes canonicalize TOML and may discard comments in automation files.\n- 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.\n\n## File Structure\n\nCreate:\n\n- `lib/crates/fabro-automation/Cargo.toml` - domain crate manifest.\n- `lib/crates/fabro-automation/src/lib.rs` - public exports.\n- `lib/crates/fabro-automation/src/error.rs` - validation and persistence errors.\n- `lib/crates/fabro-automation/src/id.rs` - `AutomationId` and `AutomationTriggerId`.\n- `lib/crates/fabro-automation/src/model.rs` - automation domain and serde/TOML model.\n- `lib/crates/fabro-automation/src/store.rs` - in-memory file-backed automation store.\n- `lib/crates/fabro-server/src/automation_materializer.rs` - GitHub target materialization and manifest building for automation runs.\n- `lib/crates/fabro-server/src/server/handler/automations.rs` - REST handlers and router.\n- `lib/crates/fabro-server/tests/it/api/automations.rs` - server API integration tests.\n- `lib/crates/fabro-server/tests/it/api/mod.rs` - wire the automations integration test module.\n\nModify:\n\n- `lib/crates/fabro-server/Cargo.toml` - add `fabro-automation`.\n- `lib/crates/fabro-api/Cargo.toml` - add `fabro-automation` so OpenAPI can reuse matching automation domain types.\n- `lib/crates/fabro-types/src/run_summary.rs` - extend `AutomationRef` with `trigger_id`.\n- `lib/crates/fabro-types/src/run.rs` - add `automation: Option` to `RunSpec`.\n- `lib/crates/fabro-types/src/run_event/run.rs` - add `automation: Option` to `RunCreatedProps`.\n- `lib/crates/fabro-workflow/src/operations/create.rs` - carry automation metadata through `CreateRunInput`, persistence options, `RunSpec`, and `run.created`.\n- `lib/crates/fabro-workflow/src/event/convert.rs` - preserve automation metadata in any legacy-to-current event conversion path that constructs `RunCreatedProps`.\n- `lib/crates/fabro-store/src/run_state.rs` - project `RunSpec.automation` into `Run.automation`.\n- `lib/crates/fabro-server/src/server.rs` - load the automation store into `AppState` and expose crate-private accessors.\n- `lib/crates/fabro-server/src/server/handler/mod.rs` - merge real automation routes.\n- `lib/crates/fabro-server/src/test_support.rs` - create temp automation storage by active config path and allow test-only materializer injection.\n- `docs/public/api-reference/fabro-api.yaml` - add automation paths and schemas.\n- `lib/crates/fabro-api/build.rs` - add replacement mappings only for domain types with identical wire shape.\n- `lib/crates/fabro-api/tests/*` - add JSON parity tests for reused automation types.\n- `lib/packages/fabro-api-client` - regenerate generated TypeScript client files only; do not import them from the web UI.\n\nDo not modify:\n\n- `apps/fabro-web/**`, except generated API package consumers are not touched.\n- CLI command modules.\n- Scheduler services or background run loops.\n\n## Public API Shape\n\nAdd these OpenAPI paths under `/api/v1`:\n\n```http\nGET /automations\nPOST /automations\nGET /automations/{id}\nPUT /automations/{id}\nPATCH /automations/{id}\nDELETE /automations/{id}\nGET /automations/{id}/runs\nPOST /automations/{id}/runs\n```\n\nUse this response model:\n\n```ts\ntype Automation = {\n id: string;\n revision: string;\n name: string;\n description: string | null;\n enabled: boolean;\n target: AutomationTarget;\n triggers: AutomationTrigger[];\n};\n\ntype AutomationTarget = {\n repository: string; // GitHub owner/repo\n ref: string;\n workflow: string;\n};\n\ntype AutomationTrigger =\n | { id: string; type: \"api\"; enabled: boolean }\n | { id: string; type: \"schedule\"; enabled: boolean; expression: string };\n\n```\n\nRequest models:\n\n```ts\ntype CreateAutomationRequest = {\n id: string;\n name: string;\n description?: string | null;\n enabled?: boolean;\n target: AutomationTarget;\n triggers: AutomationTrigger[];\n};\n\ntype ReplaceAutomationRequest = {\n name: string;\n description?: string | null;\n enabled: boolean;\n target: AutomationTarget;\n triggers: AutomationTrigger[];\n};\n\ntype PatchAutomationRequest = {\n name?: string;\n description?: string | null;\n enabled?: boolean;\n target?: AutomationTarget;\n triggers?: AutomationTrigger[];\n};\n```\n\n`GET /automations/{id}/runs` returns the existing paginated run list envelope:\n\n```json\n{\n \"data\": [],\n \"meta\": { \"has_more\": false, \"total\": 0 }\n}\n```\n\nIt accepts `page[limit]` and `page[offset]`, sorts newest first, filters by `Run.automation.id`, and returns `404` if the automation definition no longer exists.\n\n`POST /automations/{id}/runs` returns the existing `Run` response shape with `automation` populated:\n\n```json\n{\n \"automation\": {\n \"id\": \"nightly-deps\",\n \"name\": \"Nightly dependency update\",\n \"trigger_id\": \"api\"\n }\n}\n```\n\n## TOML Shape\n\nPersist this canonical TOML:\n\n```toml\nname = \"Nightly dependency update\"\ndescription = \"Open a PR for dependency updates.\"\nenabled = true\n\n[target]\nrepository = \"fabro-sh/fabro\"\nref = \"main\"\nworkflow = \"dependency-update\"\n\n[[triggers]]\nid = \"api\"\ntype = \"api\"\nenabled = false\n\n[[triggers]]\nid = \"nightly\"\ntype = \"schedule\"\nenabled = true\nexpression = \"0 3 * * *\"\n```\n\nDefaults:\n\n- `enabled` defaults to `true` when omitted in TOML or create requests.\n- `description` defaults to `null`.\n- Trigger `enabled` defaults to `true` when omitted in TOML or create requests.\n- `schedule.expression` must be a non-empty five-field cron expression accepted by `croner`.\n- `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.\n- `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.\n- `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.\n\n## Task 1: Add Domain Crate And Model Tests\n\n**Files:**\n\n- Create: `lib/crates/fabro-automation/Cargo.toml`\n- Create: `lib/crates/fabro-automation/src/lib.rs`\n- Create: `lib/crates/fabro-automation/src/error.rs`\n- Create: `lib/crates/fabro-automation/src/id.rs`\n- Create: `lib/crates/fabro-automation/src/model.rs`\n\n- [ ] Read `docs/internal/testing-strategy.md` and `docs/internal/error-handling-strategy.md` before adding tests and error types.\n- [ ] Create the crate. Because the workspace uses `members = [\"lib/crates/*\"]`, no root workspace member edit is required.\n- [ ] Add dependencies in `lib/crates/fabro-automation/Cargo.toml`: `chrono`, `croner`, `hex`, `serde`, `sha2`, `thiserror`, `tokio`, `toml`, and `toml_edit`. Add dev-dependencies: `tempfile`.\n- [ ] Define `AutomationId` and `AutomationTriggerId` newtypes with `TryFrom`, `AsRef`, `Display`, `Serialize`, and `Deserialize`.\n- [ ] Define the domain model with this public shape:\n\n```rust\npub struct AutomationRevision(String);\n\npub struct RepositorySlug(String);\n\npub struct GitRefSelector(String);\n\npub struct WorkflowSlug(String);\n\npub struct Automation {\n pub id: AutomationId,\n pub revision: AutomationRevision,\n pub name: String,\n pub description: Option,\n pub enabled: bool,\n pub target: AutomationTarget,\n pub triggers: Vec,\n}\n\npub struct AutomationTarget {\n pub repository: RepositorySlug,\n pub ref_: GitRefSelector,\n pub workflow: WorkflowSlug,\n}\n\n#[serde(tag = \"type\", rename_all = \"snake_case\")]\npub enum AutomationTrigger {\n Api(ApiTrigger),\n Schedule(ScheduleTrigger),\n}\n\npub struct ApiTrigger {\n pub id: AutomationTriggerId,\n pub enabled: bool,\n}\n\npub struct ScheduleTrigger {\n pub id: AutomationTriggerId,\n pub enabled: bool,\n pub expression: String,\n}\n\npub struct AutomationDraft {\n pub id: AutomationId,\n pub name: String,\n pub description: Option,\n pub enabled: Option,\n pub target: AutomationTarget,\n pub triggers: Vec,\n}\n\npub struct AutomationReplace {\n pub name: String,\n pub description: Option,\n pub enabled: bool,\n pub target: AutomationTarget,\n pub triggers: Vec,\n}\n\npub struct AutomationPatch {\n pub name: Option,\n pub description: Option>,\n pub enabled: Option,\n pub target: Option,\n pub triggers: Option>,\n}\n```\n\n- [ ] Use `#[serde(rename = \"ref\")]` for the Rust field `ref_`.\n- [ ] Keep `revision` out of the persisted TOML model; compute it from raw file bytes.\n- [ ] Reject empty names, invalid GitHub repository slugs, invalid refs, invalid workflow selectors, duplicate trigger IDs, and more than one trigger with `type = \"api\"`.\n- [ ] 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.\n- [ ] Run `cargo nextest run -p fabro-automation`.\n- [ ] Commit:\n\n```bash\ngit add lib/crates/fabro-automation\ngit commit -m \"feat: add automation domain model\"\n```\n\n## Task 2: Implement File-Backed Automation Store\n\n**Files:**\n\n- Create: `lib/crates/fabro-automation/src/store.rs`\n- Modify: `lib/crates/fabro-automation/src/lib.rs`\n\n- [ ] Implement `AutomationStore` as an in-memory map guarded by `tokio::sync::RwLock`.\n- [ ] Load files from a configured directory with this behavior:\n - Missing directory means an empty store.\n - Non-`.toml` files are ignored.\n - Invalid filenames fail load.\n - Invalid TOML or invalid automation data fails load.\n- [ ] Compute `AutomationRevision` as lowercase hex SHA-256 of the exact TOML bytes read from disk.\n- [ ] Expose these async methods:\n\n```rust\npub async fn load(dir: impl Into) -> Result;\npub async fn list(&self) -> Vec;\npub async fn get(&self, id: &AutomationId) -> Option;\npub async fn create(&self, draft: AutomationDraft) -> Result;\npub async fn replace(\n &self,\n id: &AutomationId,\n expected: &AutomationRevision,\n draft: AutomationReplace,\n) -> Result;\npub async fn patch(\n &self,\n id: &AutomationId,\n expected: &AutomationRevision,\n patch: AutomationPatch,\n) -> Result;\npub async fn delete(\n &self,\n id: &AutomationId,\n expected: &AutomationRevision,\n) -> Result<(), AutomationStoreError>;\n```\n\n- [ ] 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.\n- [ ] Create the automation directory on first write.\n- [ ] Map store errors into precise variants: not found, already exists, missing revision, revision mismatch, validation, parse, and I/O.\n- [ ] 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.\n- [ ] Run `cargo nextest run -p fabro-automation`.\n- [ ] Commit:\n\n```bash\ngit add lib/crates/fabro-automation\ngit commit -m \"feat: persist automations as TOML files\"\n```\n\n## Task 3: Carry Automation Metadata Through Runs\n\n**Files:**\n\n- Modify: `lib/crates/fabro-types/src/run_summary.rs`\n- Modify: `lib/crates/fabro-types/src/run.rs`\n- Modify: `lib/crates/fabro-types/src/run_event/run.rs`\n- Modify: `lib/crates/fabro-workflow/src/operations/create.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/convert.rs`\n- Modify: `lib/crates/fabro-store/src/run_state.rs`\n- Modify tests that construct `RunSpec` or `RunCreatedProps`\n\n- [ ] Extend `AutomationRef`:\n\n```rust\npub struct AutomationRef {\n pub id: String,\n #[serde(default)]\n pub name: Option,\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n pub trigger_id: Option,\n}\n```\n\n- [ ] Add `automation: Option` to `RunSpec` with `#[serde(default, skip_serializing_if = \"Option::is_none\")]`.\n- [ ] Add `automation: Option` to `RunCreatedProps` with the same serde behavior.\n- [ ] Add `automation: Option` to `fabro_workflow::operations::CreateRunInput`.\n- [ ] Thread the field through `PersistCreateOptions`, the `RunSpec` built in `persist_validated`, and the `Event::RunCreated` emitted in `persist_created_run`.\n- [ ] In `fabro-store/src/run_state.rs`, set `Run.automation` from `state.spec.automation.clone()` instead of always using `None`.\n- [ ] Preserve backward compatibility: old run specs and old `run.created` events without `automation` deserialize as `None`.\n- [ ] Update all test fixture constructors by setting `automation: None` unless the test specifically checks automation linkage.\n- [ ] Add a focused projection test proving `RunCreatedProps.automation` appears in cached `Run.automation`.\n- [ ] Run:\n\n```bash\ncargo nextest run -p fabro-types\ncargo nextest run -p fabro-workflow operations::create\ncargo nextest run -p fabro-store run_state\n```\n\n- [ ] Commit:\n\n```bash\ngit add lib/crates/fabro-types lib/crates/fabro-workflow lib/crates/fabro-store\ngit commit -m \"feat: associate runs with automations\"\n```\n\n## Task 4: Add OpenAPI Contract And Type Reuse\n\n**Files:**\n\n- Modify: `docs/public/api-reference/fabro-api.yaml`\n- Modify: `lib/crates/fabro-api/Cargo.toml`\n- Modify: `lib/crates/fabro-api/build.rs`\n- Create: `lib/crates/fabro-api/tests/automation_round_trip.rs`\n\n- [ ] Add an `Automations` tag.\n- [ ] Add schemas for `Automation`, `AutomationTarget`, `AutomationTrigger`, `AutomationApiTrigger`, `AutomationScheduleTrigger`, `CreateAutomationRequest`, `ReplaceAutomationRequest`, `PatchAutomationRequest`, and `AutomationListResponse`.\n- [ ] Use OpenAPI discriminator `propertyName: type` for trigger variants.\n- [ ] 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.\n- [ ] Reuse existing `Run` and paginated run envelope schemas for `POST /automations/{id}/runs` and `GET /automations/{id}/runs`.\n- [ ] Add response codes:\n - `200` for reads and replace/patch.\n - `201` for create automation and create run.\n - `204` for delete.\n - `400` for malformed JSON or invalid path syntax.\n - `404` for missing automation.\n - `409` for duplicate create, stale revision, disabled automation, or disabled/missing `api` trigger.\n - `422` for domain validation errors.\n - `428` for missing `If-Match` on `PUT`, `PATCH`, or `DELETE`.\n- [ ] Add `If-Match` header parameters for mutating path operations except `POST /automations`.\n- [ ] Add `ETag` response header on `GET /automations/{id}`, `PUT`, and `PATCH`.\n- [ ] 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`.\n- [ ] Add JSON parity tests for every automation replacement type used by `fabro-api`.\n- [ ] Run `cargo build -p fabro-api`.\n- [ ] Commit:\n\n```bash\ngit add docs/public/api-reference/fabro-api.yaml lib/crates/fabro-api\ngit commit -m \"feat: define automations API contract\"\n```\n\n## Task 5: Wire Automation Store Into Server State\n\n**Files:**\n\n- Modify: `lib/crates/fabro-server/Cargo.toml`\n- Modify: `lib/crates/fabro-server/src/server.rs`\n- Modify: `lib/crates/fabro-server/src/test_support.rs`\n\n- [ ] Add `fabro-automation = { path = \"../fabro-automation\" }` to server dependencies.\n- [ ] Add `automation_store: Arc` to `AppState`.\n- [ ] In `build_app_state`, compute the automation directory as:\n\n```rust\nlet automation_dir = active_config_path\n .parent()\n .unwrap_or_else(|| std::path::Path::new(\".\"))\n .join(\"automations\");\n```\n\n- [ ] Load `AutomationStore::load(automation_dir)` before constructing `AppState`.\n- [ ] Fail server startup if an existing automation file is malformed.\n- [ ] Add `pub(crate) fn automation_store(&self) -> Arc`.\n- [ ] In test support, keep the existing temp `active_config_path` behavior so each test gets its own sibling `automations` directory.\n- [ ] Add a server unit test for empty automation store creation when no automation directory exists.\n- [ ] Run `cargo nextest run -p fabro-server automation_store`.\n- [ ] Commit:\n\n```bash\ngit add lib/crates/fabro-server\ngit commit -m \"feat: load automation store in server state\"\n```\n\n## Task 6: Add Automation CRUD Routes\n\n**Files:**\n\n- Create: `lib/crates/fabro-server/src/server/handler/automations.rs`\n- Modify: `lib/crates/fabro-server/src/server/handler/mod.rs`\n- Create: `lib/crates/fabro-server/tests/it/api/automations.rs`\n- Modify: `lib/crates/fabro-server/tests/it/api/mod.rs`\n\n- [ ] Read `docs/internal/logging-strategy.md` and `docs/internal/error-handling-strategy.md` before adding request errors or logs.\n- [ ] Implement `automations::routes()` and merge it into `handler::real_routes()`.\n- [ ] Use `RequiredUser` for CRUD routes.\n- [ ] Implement `GET /automations` by listing store entries, sorting by ID ascending, and returning `{ data, meta: { total } }`.\n- [ ] Implement `POST /automations` with `CreateAutomationRequest`; duplicate ID returns `409`.\n- [ ] Implement `GET /automations/{id}` with `ETag: \"\"`.\n- [ ] Implement `PUT /automations/{id}` with `ReplaceAutomationRequest` and required `If-Match`.\n- [ ] Implement `PATCH /automations/{id}` with `PatchAutomationRequest`, shallow patch semantics, and required `If-Match`.\n- [ ] Implement `DELETE /automations/{id}` with required `If-Match`.\n- [ ] Add a helper that parses a quoted or unquoted `If-Match` revision and rejects missing headers with `428`.\n- [ ] Map `AutomationStoreError` to `ApiError`:\n - not found to `404`\n - already exists to `409`\n - missing revision to `428`\n - revision mismatch to `409`\n - validation to `422`\n - parse/I/O to `500` except malformed request bodies, which stay `400`\n- [ ] 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.\n- [ ] Run `cargo nextest run -p fabro-server automations`.\n- [ ] Commit:\n\n```bash\ngit add lib/crates/fabro-server\ngit commit -m \"feat: add automation CRUD API\"\n```\n\n## Task 7: Add Automation Run Listing And API-Triggered Runs\n\n**Files:**\n\n- Create: `lib/crates/fabro-server/src/automation_materializer.rs`\n- Modify: `lib/crates/fabro-server/src/server.rs`\n- Modify: `lib/crates/fabro-server/src/server/handler/runs.rs`\n- Modify: `lib/crates/fabro-server/src/server/handler/automations.rs`\n- Modify: `lib/crates/fabro-server/src/test_support.rs`\n- Create: `lib/crates/fabro-server/tests/it/api/automations.rs`\n- Modify: `lib/crates/fabro-server/tests/it/api/mod.rs`\n\n- [ ] Extract the common run creation body from `handler/runs.rs::create_run` into a crate-private helper that accepts:\n\n```rust\nstruct CreateRunFromManifestRequest {\n manifest: fabro_api::types::RunManifest,\n submitted_manifest_bytes: Vec,\n explicit_run_id: Option,\n explicit_title_supplied: bool,\n actor: fabro_types::Principal,\n headers: axum::http::HeaderMap,\n automation: Option,\n}\n```\n\n- [ ] Keep `POST /runs` behavior unchanged by calling the helper with `automation: None`.\n- [ ] Define a crate-private materializer trait:\n\n```rust\npub(crate) struct AutomationRunMaterializeInput {\n pub automation_id: fabro_automation::AutomationId,\n pub target: fabro_automation::AutomationTarget,\n pub run_id: fabro_types::RunId,\n pub user_settings_path: std::path::PathBuf,\n pub temp_root: std::path::PathBuf,\n}\n\npub(crate) struct AutomationRunMaterialized {\n pub manifest: fabro_api::types::RunManifest,\n pub submitted_manifest_bytes: Vec,\n}\n\n#[derive(thiserror::Error, Debug)]\npub(crate) enum AutomationRunMaterializeError {\n #[error(\"invalid automation target: {0}\")]\n InvalidTarget(String),\n #[error(\"failed to clone automation repository: {0}\")]\n CloneFailed(String),\n #[error(\"failed to resolve automation workflow: {0}\")]\n WorkflowNotFound(String),\n #[error(\"failed to build run manifest: {0}\")]\n Manifest(String),\n}\n\n#[async_trait::async_trait]\npub(crate) trait AutomationRunMaterializer: Send + Sync {\n async fn materialize(\n &self,\n input: AutomationRunMaterializeInput,\n ) -> Result;\n}\n```\n\n- [ ] Use a production implementation that:\n - validates target repository as GitHub `owner/repo`\n - is constructed with the server GitHub credentials, GitHub API base URL, HTTP client, and cleanup policy needed for clone materialization\n - creates a per-run temp directory under `AutomationRunMaterializeInput.temp_root`\n - clones `https://github.com/{owner}/{repo}.git`\n - uses existing GitHub clone credential helpers when configured\n - checks out the configured `ref`\n - resolves the workflow selector using `fabro_config::project::WorkflowLocation::resolve`\n - builds a `RunManifest` with `fabro_manifest::build_run_manifest`\n - passes `user_settings_path: Some(state.active_config_path().to_path_buf())`\n- [ ] 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.\n- [ ] Store only sanitized repository URLs in run metadata. Do not persist credentialed clone URLs.\n- [ ] Add test support injection for a fake `AutomationRunMaterializer` behind tests or the existing `test-support` feature.\n- [ ] Implement `GET /automations/{id}/runs`:\n - require the automation to exist\n - list cached runs from the store\n - filter by `run.automation.as_ref().is_some_and(|a| a.id == id)`\n - sort newest first\n - paginate with `page[limit]` and `page[offset]`\n - return the existing `{ data, meta }` list shape\n- [ ] Implement `POST /automations/{id}/runs`:\n - use `RequiredRunToolActor`\n - require automation `enabled == true`\n - find the enabled trigger with `type = \"api\"`\n - return `409` with API error code `automation_api_trigger_disabled` if not startable\n - materialize the run manifest\n - call the shared create-run helper with `AutomationRef { id, name, trigger_id: Some(api_trigger_id) }`\n - return `201` and the created `Run`\n- [ ] Add route tests using the fake materializer for disabled automation, disabled API trigger, successful run creation, persisted `Run.automation`, and associated run listing.\n- [ ] 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.\n- [ ] Run `cargo nextest run -p fabro-server automations`.\n- [ ] Commit:\n\n```bash\ngit add lib/crates/fabro-server\ngit commit -m \"feat: start runs from automations\"\n```\n\n## Task 8: Generate Clients And Final Verification\n\n**Files:**\n\n- Modify generated files under `lib/packages/fabro-api-client`\n- Modify generated Rust files under `lib/crates/fabro-api/src` if `cargo build -p fabro-api` updates them\n\n- [ ] Regenerate Rust API code:\n\n```bash\ncargo build -p fabro-api\n```\n\n- [ ] Regenerate the TypeScript API client:\n\n```bash\ncd lib/packages/fabro-api-client && bun run generate\n```\n\n- [ ] Confirm no web UI imports or CLI command modules changed:\n\n```bash\ngit diff -- apps/fabro-web lib/crates/fabro-cli\n```\n\nExpected: no application or CLI command changes caused by this plan.\n\n- [ ] Run focused tests:\n\n```bash\ncargo nextest run -p fabro-automation\ncargo nextest run -p fabro-api\ncargo nextest run -p fabro-server automations\ncargo nextest run -p fabro-server openapi_conformance\n```\n\n- [ ] Run broader checks:\n\n```bash\ncargo +nightly-2026-04-14 fmt --check --all\ncargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warnings\n```\n\n- [ ] If clippy or tests expose unrelated existing failures, record the exact failing command and failure summary in the implementation handoff.\n- [ ] Commit generated and verification fixes:\n\n```bash\ngit add docs/public/api-reference/fabro-api.yaml lib/crates lib/packages/fabro-api-client\ngit commit -m \"chore: regenerate automation API clients\"\n```\n\n## Acceptance Criteria\n\n- A server with no `automations/` directory starts and returns an empty automation list.\n- Creating an automation writes `dirname(active_config_path)/automations/.toml`.\n- Updating or deleting an automation requires `If-Match`.\n- Stale revisions are rejected.\n- Invalid automation and trigger shapes are rejected with `422`.\n- Disabling the `api` trigger makes the automation not startable through `POST /automations/{id}/runs`.\n- A successful API-triggered automation run returns a normal `Run` response with `automation.id`, `automation.name`, and `automation.trigger_id`.\n- `GET /automations/{id}/runs` returns runs linked to that automation.\n- No cron scheduler, web UI exposure, or CLI exposure is added.\n", + "internal.thread_id": "preflight_lint", + "thread.start.current_node": "toolchain", + "last_response": "Implemented the Automations backend API plan end-to-end.\n\n### What changed\n\n- Added new `fabro-automation` domain crate:\n - Automation/trigger IDs and validation.\n - TOML model with canonical file s", + "outcome": "succeeded", "graph.model_stylesheet": "\n * { model: claude-opus-4-7; }\n ", "failure_class": "", "internal.work_dir": "/home/daytona/workspace/fabro", - "thread.toolchain.current_node": "preflight_compile", "internal.retry_count.preflight_compile": 0, + "response.implement": "Implemented the Automations backend API plan end-to-end.\n\n### What changed\n\n- Added new `fabro-automation` domain crate:\n - Automation/trigger IDs and validation.\n - TOML model with canonical file serialization.\n - SHA-256 revision hashing from exact TOML bytes.\n - File-backed async `AutomationStore` with atomic writes.\n\n- Threaded automation metadata through runs:\n - `AutomationRef.trigger_id`\n - `RunSpec.automation`\n - `RunCreatedProps.automation`\n - workflow create/retry/fork/persistence paths\n - store projections into `Run.automation`\n\n- Added OpenAPI contract and Rust API type reuse:\n - `/api/v1/automations`\n - `/api/v1/automations/{id}`\n - `/api/v1/automations/{id}/runs`\n - Reused `fabro-automation` Rust types where wire shape matches.\n - Regenerated TypeScript client under `lib/packages/fabro-api-client`.\n\n- Wired server state:\n - Loads automation store from `dirname(active_config_path)/automations`.\n - Missing directory starts empty.\n - Malformed files fail startup.\n - Test support injects a fake automation run materializer.\n\n- Added REST handlers:\n - CRUD with ETags/If-Match.\n - `422` domain validation for invalid automation/trigger shapes, including unknown future trigger shapes.\n - `409` for disabled automation or no enabled API trigger.\n - Run listing filtered by `Run.automation.id`.\n - API-triggered run creation with populated `automation.id`, `automation.name`, and `automation.trigger_id`.\n\n- Added Git-based automation materializer:\n - Clones GitHub `owner/repo` targets.\n - Uses argv-based `git` commands, no shell string interpolation.\n - Uses non-interactive git and timeouts.\n - Resets origin to sanitized URL before manifest building.\n - Builds run manifests from resolved workflow selectors.\n\n### Verification run\n\nPassed:\n\n```bash\ncargo nextest run -p fabro-automation\ncargo nextest run -p fabro-api\ncargo nextest run -p fabro-types\ncargo nextest run -p fabro-workflow operations::create\ncargo nextest run -p fabro-store run_state\ncargo nextest run -p fabro-server --features test-support automation_store\ncargo nextest run -p fabro-server --features test-support automations\ncargo nextest run -p fabro-server --features test-support openapi_conformance\ncargo build -p fabro-api\ncd lib/packages/fabro-api-client && bun run generate\ncargo check -q --workspace\ncargo +nightly-2026-04-14 fmt --check --all\ncargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warnings\ngit diff --check\n```\n\nAlso confirmed:\n\n```bash\ngit diff -- apps/fabro-web\n```\n\nis empty.\n\n### Note\n\nNo UI routes/components, scheduler/background loop, or CLI commands were added. Two CLI test fixtures were minimally updated with `automation: None` because adding the required `RunSpec.automation` field otherwise breaks `--all-targets` compilation; no CLI behavior changed.\n\nNo commits were made.", + "thread.fix_lints.current_node": "preflight_lint", + "internal.run_id": "01KSE2PAVXD56N4TWNK4T5H5VA", + "current_node": "implement", + "internal.fidelity": "compact", + "internal.retry_count.fix_lints": 0, + "thread.preflight_compile.current_node": "preflight_lint", + "thread.preflight_lint.current_node": "implement", + "thread.toolchain.current_node": "preflight_compile", + "response.fix_lints": "Clippy is now clean across the workspace. The fix collapsed the inner `if props.resume` into a guarded match arm on `EventBody::RunStartRequested`, falling through to the existing wildcard arm for non-resume cases.", "graph.rankdir": "LR", "failure_signature": "", - "last_stage": "fix_lints", - "response.fix_lints": "Clippy is now clean across the workspace. The fix collapsed the inner `if props.resume` into a guarded match arm on `EventBody::RunStartRequested`, falling through to the existing wildcard arm for non-resume cases.", - "thread.fix_lints.current_node": "preflight_lint", + "last_stage": "implement", "internal.retry_count.start": 0, - "internal.run_id": "01KSE2PAVXD56N4TWNK4T5H5VA", - "internal.node_visit_count": 2, "command.output": "blob://sha256/12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126", - "current_node": "preflight_lint", - "internal.retry_count.toolchain": 0, - "internal.retry_count.preflight_lint": 0 + "internal.node_visit_count": 1, + "internal.retry_count.preflight_lint": 0, + "internal.retry_count.implement": 0, + "internal.retry_count.toolchain": 0 }, "node_outcomes": { "fix_lints": { @@ -967,6 +1098,42 @@ "notes": "Script completed: 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", "usage": null }, + "implement": { + "status": "succeeded", + "context_updates": { + "last_response": "Implemented the Automations backend API plan end-to-end.\n\n### What changed\n\n- Added new `fabro-automation` domain crate:\n - Automation/trigger IDs and validation.\n - TOML model with canonical file s", + "last_stage": "implement", + "response.implement": "Implemented the Automations backend API plan end-to-end.\n\n### What changed\n\n- Added new `fabro-automation` domain crate:\n - Automation/trigger IDs and validation.\n - TOML model with canonical file serialization.\n - SHA-256 revision hashing from exact TOML bytes.\n - File-backed async `AutomationStore` with atomic writes.\n\n- Threaded automation metadata through runs:\n - `AutomationRef.trigger_id`\n - `RunSpec.automation`\n - `RunCreatedProps.automation`\n - workflow create/retry/fork/persistence paths\n - store projections into `Run.automation`\n\n- Added OpenAPI contract and Rust API type reuse:\n - `/api/v1/automations`\n - `/api/v1/automations/{id}`\n - `/api/v1/automations/{id}/runs`\n - Reused `fabro-automation` Rust types where wire shape matches.\n - Regenerated TypeScript client under `lib/packages/fabro-api-client`.\n\n- Wired server state:\n - Loads automation store from `dirname(active_config_path)/automations`.\n - Missing directory starts empty.\n - Malformed files fail startup.\n - Test support injects a fake automation run materializer.\n\n- Added REST handlers:\n - CRUD with ETags/If-Match.\n - `422` domain validation for invalid automation/trigger shapes, including unknown future trigger shapes.\n - `409` for disabled automation or no enabled API trigger.\n - Run listing filtered by `Run.automation.id`.\n - API-triggered run creation with populated `automation.id`, `automation.name`, and `automation.trigger_id`.\n\n- Added Git-based automation materializer:\n - Clones GitHub `owner/repo` targets.\n - Uses argv-based `git` commands, no shell string interpolation.\n - Uses non-interactive git and timeouts.\n - Resets origin to sanitized URL before manifest building.\n - Builds run manifests from resolved workflow selectors.\n\n### Verification run\n\nPassed:\n\n```bash\ncargo nextest run -p fabro-automation\ncargo nextest run -p fabro-api\ncargo nextest run -p fabro-types\ncargo nextest run -p fabro-workflow operations::create\ncargo nextest run -p fabro-store run_state\ncargo nextest run -p fabro-server --features test-support automation_store\ncargo nextest run -p fabro-server --features test-support automations\ncargo nextest run -p fabro-server --features test-support openapi_conformance\ncargo build -p fabro-api\ncd lib/packages/fabro-api-client && bun run generate\ncargo check -q --workspace\ncargo +nightly-2026-04-14 fmt --check --all\ncargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warnings\ngit diff --check\n```\n\nAlso confirmed:\n\n```bash\ngit diff -- apps/fabro-web\n```\n\nis empty.\n\n### Note\n\nNo UI routes/components, scheduler/background loop, or CLI commands were added. Two CLI test fixtures were minimally updated with `automation: None` because adding the required `RunSpec.automation` field otherwise breaks `--all-targets` compilation; no CLI behavior changed.\n\nNo commits were made." + }, + "notes": "Stage completed: implement", + "usage": { + "input": { + "usage": { + "model": { + "provider": "openai", + "model_id": "gpt-5.5" + }, + "tokens": { + "input_tokens": 8765682, + "output_tokens": 15084, + "reasoning_tokens": 11000, + "cache_read_tokens": 10500096, + "cache_write_tokens": 0 + } + }, + "facts": { + "algorithm": "openai" + } + }, + "total_usd_micros": 49860978 + }, + "files_touched": [ + "/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" + ] + }, "start": { "status": "succeeded", "usage": null @@ -980,10 +1147,11 @@ "usage": null } }, - "next_node_id": "implement", + "next_node_id": "simplify_opus", "node_visits": { "toolchain": 1, "fix_lints": 1, + "implement": 1, "preflight_lint": 2, "preflight_compile": 1, "start": 1 @@ -1251,6 +1419,281 @@ }, "state": "succeeded" }, + "implement@1": { + "first_event_seq": 98, + "prompt": null, + "response": null, + "completion": null, + "provider_used": { + "mode": "agent", + "provider": "openai", + "model": "gpt-5.5", + "reasoning_effort": "xhigh" + }, + "diff": null, + "script_invocation": null, + "script_timing": null, + "parallel_results": null, + "output": null, + "started_at": "2026-05-24T22:52:48.845505Z", + "handler": "agent", + "usage": { + "input_tokens": 8765682, + "output_tokens": 15084, + "total_tokens": 19291862, + "reasoning_tokens": 11000, + "cache_read_tokens": 10500096, + "cache_write_tokens": 0, + "total_usd_micros": 49860978 + }, + "model": { + "provider": "openai", + "model_id": "gpt-5.5" + }, + "todos": { + "kind": "openai_plan", + "list_id": "openai_plan:564c3f3d-aaa6-4c2b-91c6-c85b0ece169c", + "items": [ + { + "id": "d50f7a628d5ac4d5", + "status": "completed", + "order": 0, + "subject": "Audit current automation implementation against locked requirements" + }, + { + "id": "6d865e872cf1e99a", + "status": "completed", + "order": 1, + "subject": "Run focused Rust tests for automation, API, and server OpenAPI conformance" + }, + { + "id": "aee9ead32777ec6f", + "status": "completed", + "order": 2, + "subject": "Regenerate TypeScript API client and verify no web UI/CLI changes" + }, + { + "id": "ab59970bda529038", + "status": "completed", + "order": 3, + "subject": "Run workspace check, formatting, and clippy; fix resulting issues" + }, + { + "id": "e8b56990c1366b3a", + "status": "completed", + "order": 4, + "subject": "Summarize changes, validation results, and any limitations" + } + ] + }, + "subagents": [ + { + "agent_id": "84deb57b", + "depth": 1, + "task": "Recon only: inspect fabro-server run creation routes, AppState, test_support, and integration test harness. Do not modify files. Report key files/functions and how to add automations routes/materializer safely.", + "status": { + "kind": "closed" + } + }, + { + "agent_id": "71a4660e", + "depth": 1, + "task": "Recon only: inspect fabro-api OpenAPI build.rs/progenitor replacement patterns and API tests. Do not modify files. Report how to add automation schemas/type replacements and parity tests.", + "status": { + "kind": "closed" + } + }, + { + "agent_id": "c5924717", + "depth": 1, + "task": "Recon only: inspect run metadata types and workflow create/store projection paths in fabro-types, fabro-workflow, fabro-store. Do not modify files. Report exact structs/tests that need automation metadata fields.", + "status": { + "kind": "completed", + "success": true, + "turns_used": 7 + } + }, + { + "agent_id": "72e77e39", + "depth": 1, + "task": "Independently audit the current Fabro automations backend implementation against the user's plan. Focus on locked requirements and likely compile/test gaps after recent changes. Do not edit files. Inspect relevant Rust/OpenAPI files and report concise findings with file/line references and suggested fixes. Pay special attention to OpenAPI shape/replacements, HTTP status mappings, automation materializer security, storage root semantics, and tests coverage.", + "status": { + "kind": "completed", + "success": true, + "turns_used": 11 + } + } + ], + "permission_level": "full", + "agent_tools": [ + { + "name": "apply_patch", + "description": "Use the `apply_patch` tool to edit files. This is a FREEFORM tool, so do not wrap the patch in JSON.", + "source": { + "kind": "native" + }, + "category": "write", + "invoked": true + }, + { + "name": "close_agent", + "description": "Close a running subagent that is no longer needed.", + "source": { + "kind": "native" + }, + "category": "subagent", + "invoked": false + }, + { + "name": "glob", + "description": "Find files by file names using a glob pattern. Use path to choose the search root. Prefer this over shell find or ls when locating repository files.", + "source": { + "kind": "native" + }, + "category": "read", + "invoked": true + }, + { + "name": "grep", + "description": "Search file contents with a regex pattern. Use path to choose the search root, glob_filter to limit matching files, case_insensitive for case folding, and max_results to cap output.", + "source": { + "kind": "native" + }, + "category": "read", + "invoked": true + }, + { + "name": "read_file", + "description": "Read files before editing them. Returns line-numbered text and supports offset/limit for large files. Use this instead of shell cat, head, tail, or sed when inspecting repository files.", + "source": { + "kind": "native" + }, + "category": "read", + "invoked": true + }, + { + "name": "request_user_input", + "description": "Ask the human one or more questions and wait for their answers before continuing this stage.", + "source": { + "kind": "native" + }, + "category": "other", + "invoked": false + }, + { + "name": "send_input", + "description": "Send a follow-up message to a running subagent when new information or corrected instructions are needed.", + "source": { + "kind": "native" + }, + "category": "subagent", + "invoked": false + }, + { + "name": "shell", + "description": "Execute shell commands for terminal operations, package managers, tests and builds. Use dedicated tools for file reads, file edits, filename searches, and content searches. Provide timeout_ms for long-running commands.", + "source": { + "kind": "native" + }, + "category": "shell", + "invoked": true + }, + { + "name": "spawn_agent", + "description": "Spawn a subagent for independent work or context isolation. Use it for tasks that can proceed separately, and avoid duplicating the same work in the parent session.", + "source": { + "kind": "native" + }, + "category": "subagent", + "invoked": true + }, + { + "name": "update_plan", + "description": "Update the multi-step plan for the current task. Submit the entire plan; existing steps are reconciled by exact step text.", + "source": { + "kind": "native" + }, + "category": "other", + "invoked": true + }, + { + "name": "wait", + "description": "Wait for a subagent to complete, then use the result to synthesize the outcome for the user.", + "source": { + "kind": "native" + }, + "category": "subagent", + "invoked": true + }, + { + "name": "web_fetch", + "description": "Fetch content from a URL that starts with http:// or https://. Pass a prompt to extract specific information or summarize the page; omit prompt to return the page content.", + "source": { + "kind": "native" + }, + "category": "other", + "invoked": false + }, + { + "name": "web_search", + "description": "Search the web using Brave Search when current external information is needed. Returns result titles, URLs, and descriptions; use web_fetch for a specific URL.", + "source": { + "kind": "native" + }, + "category": "other", + "invoked": false + }, + { + "name": "write_file", + "description": "Create new files, or overwrite an existing file only when replacement is explicitly intended. Prefer edit_file for targeted changes to existing files because write_file overwrites the full file content.", + "source": { + "kind": "native" + }, + "category": "write", + "invoked": true + } + ], + "context_window": { + "provider": "openai", + "model": "gpt-5.5", + "context_window_tokens": 272000, + "input_tokens": 197961, + "usage_percent": 72.77977941176471, + "count_method": "response_usage_scaled_breakdown", + "staleness": "live", + "generated_at": "2026-05-25T00:27:04.327856Z", + "event_seq": 1716, + "breakdown": [ + { + "category": "system_prompt", + "tokens": 970, + "usage_percent": 0.35661764705882354 + }, + { + "category": "tools", + "tokens": 1406, + "usage_percent": 0.5169117647058824 + }, + { + "category": "memory", + "tokens": 3289, + "usage_percent": 1.2091911764705883 + }, + { + "category": "conversation", + "tokens": 192289, + "usage_percent": 70.69448529411764 + }, + { + "category": "other", + "tokens": 7, + "usage_percent": 0.002573529411764706 + } + ], + "warnings": [] + }, + "state": "running" + }, "toolchain@1": { "first_event_seq": 21, "prompt": null, @@ -1303,7 +1746,12 @@ "first_event_seq": 88, "prompt": null, "response": null, - "completion": null, + "completion": { + "outcome": "succeeded", + "notes": "Script completed: cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1", + "failure_reason": null, + "timestamp": "2026-05-24T22:52:44.963474Z" + }, "provider_used": null, "diff": null, "script_invocation": { @@ -1311,11 +1759,27 @@ "command": "exec 2>&1\ncargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1", "language": "shell" }, - "script_timing": null, + "script_timing": { + "output": "blob://sha256/12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126", + "exit_code": 0, + "duration_ms": 17838, + "termination": "exited", + "output_bytes": 0, + "live_streaming": false + }, "parallel_results": null, "output": null, + "output_bytes": 0, + "live_streaming": false, + "termination": "exited", "started_at": "2026-05-24T22:52:27.118676Z", "handler": "command", + "timing": { + "wall_time_ms": 17844, + "inference_time_ms": 0, + "tool_time_ms": 0, + "active_time_ms": 0 + }, "usage": { "input_tokens": 0, "output_tokens": 0, @@ -1324,7 +1788,7 @@ "cache_read_tokens": 0, "cache_write_tokens": 0 }, - "state": "running" + "state": "succeeded" }, "start@1": { "first_event_seq": 17, diff --git a/stages/006-preflight_lint@2/output.log b/stages/006-preflight_lint@2/output.log new file mode 100644 index 000000000..d87ba9545 --- /dev/null +++ b/stages/006-preflight_lint@2/output.log @@ -0,0 +1 @@ +blob://sha256/12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126 \ No newline at end of file diff --git a/stages/006-preflight_lint@2/script_timing.json b/stages/006-preflight_lint@2/script_timing.json new file mode 100644 index 000000000..870f4252d --- /dev/null +++ b/stages/006-preflight_lint@2/script_timing.json @@ -0,0 +1,8 @@ +{ + "output": "blob://sha256/12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126", + "exit_code": 0, + "duration_ms": 17838, + "termination": "exited", + "output_bytes": 0, + "live_streaming": false +} \ No newline at end of file diff --git a/stages/006-preflight_lint@2/status.json b/stages/006-preflight_lint@2/status.json new file mode 100644 index 000000000..aebbde465 --- /dev/null +++ b/stages/006-preflight_lint@2/status.json @@ -0,0 +1,6 @@ +{ + "outcome": "succeeded", + "notes": "Script completed: cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1", + "failure_reason": null, + "timestamp": "2026-05-24T22:52:44.963474Z" +} \ No newline at end of file diff --git a/stages/007-implement@1/prompt.md b/stages/007-implement@1/prompt.md new file mode 100644 index 000000000..b9af1eb2b --- /dev/null +++ b/stages/007-implement@1/prompt.md @@ -0,0 +1,682 @@ +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/.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/.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` to `RunSpec`. +- `lib/crates/fabro-types/src/run_event/run.rs` - add `automation: Option` 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`, `AsRef`, `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, + pub enabled: bool, + pub target: AutomationTarget, + pub triggers: Vec, +} + +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, + pub enabled: Option, + pub target: AutomationTarget, + pub triggers: Vec, +} + +pub struct AutomationReplace { + pub name: String, + pub description: Option, + pub enabled: bool, + pub target: AutomationTarget, + pub triggers: Vec, +} + +pub struct AutomationPatch { + pub name: Option, + pub description: Option>, + pub enabled: Option, + pub target: Option, + pub triggers: Option>, +} +``` + +- [ ] 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) -> Result; +pub async fn list(&self) -> Vec; +pub async fn get(&self, id: &AutomationId) -> Option; +pub async fn create(&self, draft: AutomationDraft) -> Result; +pub async fn replace( + &self, + id: &AutomationId, + expected: &AutomationRevision, + draft: AutomationReplace, +) -> Result; +pub async fn patch( + &self, + id: &AutomationId, + expected: &AutomationRevision, + patch: AutomationPatch, +) -> Result; +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, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub trigger_id: Option, +} +``` + +- [ ] Add `automation: Option` to `RunSpec` with `#[serde(default, skip_serializing_if = "Option::is_none")]`. +- [ ] Add `automation: Option` to `RunCreatedProps` with the same serde behavior. +- [ ] Add `automation: Option` 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` 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`. +- [ ] 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: ""`. +- [ ] 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, + explicit_run_id: Option, + explicit_title_supplied: bool, + actor: fabro_types::Principal, + headers: axum::http::HeaderMap, + automation: Option, +} +``` + +- [ ] 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, +} + +#[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; +} +``` + +- [ ] 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/.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) + + +Read the plan file referenced in the goal and implement every step. Make all the code changes described in the plan. Use red/green TDD. \ No newline at end of file diff --git a/stages/007-implement@1/provider_used.json b/stages/007-implement@1/provider_used.json new file mode 100644 index 000000000..c57772db6 --- /dev/null +++ b/stages/007-implement@1/provider_used.json @@ -0,0 +1,6 @@ +{ + "mode": "agent", + "provider": "openai", + "model": "gpt-5.5", + "reasoning_effort": "xhigh" +} \ No newline at end of file diff --git a/stages/007-implement@1/response.md b/stages/007-implement@1/response.md new file mode 100644 index 000000000..00be38c85 --- /dev/null +++ b/stages/007-implement@1/response.md @@ -0,0 +1,78 @@ +Implemented the Automations backend API plan end-to-end. + +### What changed + +- Added new `fabro-automation` domain crate: + - Automation/trigger IDs and validation. + - TOML model with canonical file serialization. + - SHA-256 revision hashing from exact TOML bytes. + - File-backed async `AutomationStore` with atomic writes. + +- Threaded automation metadata through runs: + - `AutomationRef.trigger_id` + - `RunSpec.automation` + - `RunCreatedProps.automation` + - workflow create/retry/fork/persistence paths + - store projections into `Run.automation` + +- Added OpenAPI contract and Rust API type reuse: + - `/api/v1/automations` + - `/api/v1/automations/{id}` + - `/api/v1/automations/{id}/runs` + - Reused `fabro-automation` Rust types where wire shape matches. + - Regenerated TypeScript client under `lib/packages/fabro-api-client`. + +- Wired server state: + - Loads automation store from `dirname(active_config_path)/automations`. + - Missing directory starts empty. + - Malformed files fail startup. + - Test support injects a fake automation run materializer. + +- Added REST handlers: + - CRUD with ETags/If-Match. + - `422` domain validation for invalid automation/trigger shapes, including unknown future trigger shapes. + - `409` for disabled automation or no enabled API trigger. + - Run listing filtered by `Run.automation.id`. + - API-triggered run creation with populated `automation.id`, `automation.name`, and `automation.trigger_id`. + +- Added Git-based automation materializer: + - Clones GitHub `owner/repo` targets. + - Uses argv-based `git` commands, no shell string interpolation. + - Uses non-interactive git and timeouts. + - Resets origin to sanitized URL before manifest building. + - Builds run manifests from resolved workflow selectors. + +### Verification run + +Passed: + +```bash +cargo nextest run -p fabro-automation +cargo nextest run -p fabro-api +cargo nextest run -p fabro-types +cargo nextest run -p fabro-workflow operations::create +cargo nextest run -p fabro-store run_state +cargo nextest run -p fabro-server --features test-support automation_store +cargo nextest run -p fabro-server --features test-support automations +cargo nextest run -p fabro-server --features test-support openapi_conformance +cargo build -p fabro-api +cd lib/packages/fabro-api-client && bun run generate +cargo check -q --workspace +cargo +nightly-2026-04-14 fmt --check --all +cargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warnings +git diff --check +``` + +Also confirmed: + +```bash +git diff -- apps/fabro-web +``` + +is empty. + +### Note + +No UI routes/components, scheduler/background loop, or CLI commands were added. Two CLI test fixtures were minimally updated with `automation: None` because adding the required `RunSpec.automation` field otherwise breaks `--all-targets` compilation; no CLI behavior changed. + +No commits were made. \ No newline at end of file