The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: files changed src/openhuman/flows/build_registry.rs,src/openhuman/flows/draft_store.rs,src/op
Steven Enamakel57127f072e36
diff --git a/src/openhuman/flows/build_registry.rs b/src/openhuman/flows/build_registry.rsdeleted file mode 100644index 3badbd95c1..0000000000--- a/src/openhuman/flows/build_registry.rs+++ /dev/null@@ -1,250 +0,0 @@-//! Process-local registry of in-flight `flows_build` (Workflow Copilot)-//! authoring turns, keyed by `thread_id`, so the copilot's Stop button can-//! actually cancel the agent turn instead of merely hiding its own button-//! (issue: PR #5223 review found the FE-only Stop was cosmetic).-//!-//! `flows_build` runs the `workflow_builder` agent turn **awaited inline**-//! inside its RPC handler — wrapped in `with_origin` /-//! `APPROVAL_CHAT_CONTEXT.scope` / `APPROVAL_COPILOT_STREAM_CONTEXT.scope` /-//! `with_thread_id`, all task-local context that would be lost if the run were-//! `tokio::spawn`ed onto a fresh task. So it can't register in-//! `web_chat::IN_FLIGHT` (only tracks *spawned* interactive chat turns) or-//! `task_dispatcher::ACTIVE_RUNS` (aborts a detached tokio task via-//! `JoinHandle::abort`) — neither fits an inline-awaited future. This module-//! mirrors `flows::run_registry` (used by `flows_cancel_run` for live-//! `flows_run`/`flows_resume` executions — see that module's doc for the same-//! register-a-token / `tokio::select!` shape), but is scoped by `thread_id` +-//! `request_id` instead of `run_id`, matching-//! `task_dispatcher::cancel_session_scoped`'s stale-cancel guard (#4760): a-//! Stop click for a superseded/earlier request must not tear down a newer-//! builder turn that has since started on the same thread.--use std::collections::HashMap;-use std::sync::{LazyLock, Mutex};--use tokio_util::sync::CancellationToken;--/// One in-flight builder turn: the `request_id` it was registered under (for-/// scoped-cancel matching) and the token `flows_build` selects against.-struct BuildTurn {- request_id: Option<String>,- token: CancellationToken,-}--/// The live in-flight builder turns: `thread_id` -> its turn entry.-static BUILD_TURNS: LazyLock<Mutex<HashMap<String, BuildTurn>>> =- LazyLock::new(|| Mutex::new(HashMap::new()));--/// Registers an in-flight `flows_build` turn for `thread_id`, storing its-/// `request_id` (for scoped-cancel matching) and the `token` the turn selects-/// against.-///-/// Overwrites any prior entry on this thread unconditionally: `flows_build`-/// unregisters on every exit path (success, error, timeout, cancel), so a-/// still-present entry here means an earlier turn's cleanup hasn't run yet —-/// the newer registration should win either way, matching `run_registry`'s-/// duplicate-key handling.-pub(crate) fn register_build_turn(- thread_id: String,- request_id: Option<String>,- token: CancellationToken,-) {- tracing::debug!(- target: "flows",- thread_id = %thread_id,- request_id = request_id.as_deref().unwrap_or("<none>"),- "[flows] build_registry: registered in-flight build turn"- );- BUILD_TURNS- .lock()- .unwrap_or_else(|e| e.into_inner())- .insert(thread_id, BuildTurn { request_id, token });-}--/// Signals the in-flight `flows_build` turn on `thread_id` to cancel, scoped by-/// `request_id` exactly like `task_dispatcher::cancel_session_scoped`: when-/// `request_id` is `Some`, the cancel fires only if it matches the turn-/// currently registered on the thread — a stale Stop for a superseded/unrelated-/// request is a no-op rather than killing a newer turn. `None` cancels-/// unscoped (whatever turn is on the thread). Returns whether a turn was found-/// and signalled.-pub(crate) fn cancel_build_turn_scoped(thread_id: &str, request_id: Option<&str>) -> bool {- let guard = BUILD_TURNS.lock().unwrap_or_else(|e| e.into_inner());- let Some(turn) = guard.get(thread_id) else {- tracing::debug!(- target: "flows",- thread_id = %thread_id,- "[flows] build_registry: cancel ignored — no in-flight build turn on thread"- );- return false;- };- if let Some(rid) = request_id {- if turn.request_id.as_deref() != Some(rid) {- tracing::debug!(- target: "flows",- thread_id = %thread_id,- request_id = %rid,- active_request_id = turn.request_id.as_deref().unwrap_or("<none>"),- "[flows] build_registry: cancel ignored — request_id mismatch \- (superseded/unrelated request)"- );- return false;- }- }- turn.token.cancel();- tracing::info!(- target: "flows",- thread_id = %thread_id,- "[flows] build_registry: signalled in-flight build turn to cancel"- );- true-}--/// Removes the registered turn for `thread_id`, but only if it still matches-/// `request_id` (when `Some`) — guards the same race-/// `task_dispatcher::take_active_run_if` guards against: a newer turn may have-/// already re-registered on this thread by the time an older turn's own-/// cleanup runs, and unregistering unconditionally would clobber that newer-/// turn's entry out from under it. `None` unregisters unconditionally. Call on-/// every `flows_build` exit path (success, error, timeout, cancel).-pub(crate) fn unregister_build_turn(thread_id: &str, request_id: Option<&str>) {- let mut guard = BUILD_TURNS.lock().unwrap_or_else(|e| e.into_inner());- if let Some(rid) = request_id {- match guard.get(thread_id) {- Some(turn) if turn.request_id.as_deref() == Some(rid) => {}- _ => {- tracing::debug!(- target: "flows",- thread_id = %thread_id,- request_id = %rid,- "[flows] build_registry: unregister skipped — thread now owned by a \- different (or no) turn"- );- return;- }- }- }- guard.remove(thread_id);- tracing::debug!(- target: "flows",- thread_id = %thread_id,- "[flows] build_registry: deregistered build turn"- );-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn cancel_build_turn_scoped_cancels_a_registered_token() {- let thread_id = "build-registry-test:thread-1";- let token = CancellationToken::new();- register_build_turn(- thread_id.to_string(),- Some("req-1".to_string()),- token.clone(),- );-- assert!(!token.is_cancelled());- assert!(cancel_build_turn_scoped(thread_id, Some("req-1")));- assert!(token.is_cancelled());-- unregister_build_turn(thread_id, Some("req-1"));- }-- #[test]- fn cancel_build_turn_scoped_returns_false_when_nothing_registered() {- assert!(!cancel_build_turn_scoped(- "build-registry-test:never-registered",- Some("req-x")- ));- assert!(!cancel_build_turn_scoped(- "build-registry-test:never-registered",- None- ));- }-- #[test]- fn cancel_build_turn_scoped_ignores_a_mismatched_request_id() {- let thread_id = "build-registry-test:thread-2";- let token = CancellationToken::new();- register_build_turn(- thread_id.to_string(),- Some("req-1".to_string()),- token.clone(),- );-- // A stale/unrelated request_id must not cancel a still-live turn.- assert!(!cancel_build_turn_scoped(- thread_id,- Some("some-other-request")- ));- assert!(!token.is_cancelled());-- // The real request_id still works.- assert!(cancel_build_turn_scoped(thread_id, Some("req-1")));- assert!(token.is_cancelled());-- unregister_build_turn(thread_id, Some("req-1"));- }-- #[test]- fn cancel_build_turn_scoped_unscoped_none_cancels_whatever_is_registered() {- let thread_id = "build-registry-test:thread-3";- let token = CancellationToken::new();- register_build_turn(- thread_id.to_string(),- Some("req-1".to_string()),- token.clone(),- );-- assert!(cancel_build_turn_scoped(thread_id, None));- assert!(token.is_cancelled());-- unregister_build_turn(thread_id, None);- }-- #[test]- fn unregister_build_turn_is_match_guarded() {- let thread_id = "build-registry-test:thread-4";- let token_a = CancellationToken::new();- register_build_turn(- thread_id.to_string(),- Some("req-a".to_string()),- token_a.clone(),- );-- // A newer turn supersedes the entry (mirrors `flows_build` starting a- // second turn on the same thread before the first one's cleanup ran).- let token_b = CancellationToken::new();- register_build_turn(- thread_id.to_string(),- Some("req-b".to_string()),- token_b.clone(),- );-- // An unregister scoped to the OLD (superseded) request must not clobber- // the newer turn's entry.- unregister_build_turn(thread_id, Some("req-a"));- assert!(- cancel_build_turn_scoped(thread_id, Some("req-b")),- "the newer turn's entry must still be registered after a stale unregister"- );- assert!(token_b.is_cancelled());- assert!(!token_a.is_cancelled());-- unregister_build_turn(thread_id, Some("req-b"));- assert!(!cancel_build_turn_scoped(thread_id, None));- }-- #[test]- fn unregister_build_turn_none_removes_unconditionally() {- let thread_id = "build-registry-test:thread-5";- let token = CancellationToken::new();- register_build_turn(thread_id.to_string(), Some("req-1".to_string()), token);-- unregister_build_turn(thread_id, None);- assert!(!cancel_build_turn_scoped(thread_id, None));- }-}diff --git a/src/openhuman/flows/draft_store.rs b/src/openhuman/flows/draft_store.rsdeleted file mode 100644index 1a53433f90..0000000000--- a/src/openhuman/flows/draft_store.rs+++ /dev/null@@ -1,282 +0,0 @@-//! File-based persistence for [`FlowDraft`]s (audit F5).-//!-//! Drafts are plain JSON files under `{workspace_dir}/flows/drafts/<id>.json`,-//! one file per draft — deliberately NOT a SQLite table (no schema/migration,-//! trivially inspectable and deletable). The draft is the shared working copy-//! the agent tools (Rust core) and the canvas both read/write by id across-//! turns and reloads, which rules out frontend-only `localStorage`.-//!-//! This module is the thin storage layer; business logic (promote → the-//! existing create/update gates) lives in [`super::ops`]. The same RPC contract-//! (`flows_draft_*`) would hold if drafts later migrate into a table.--use std::path::PathBuf;--use anyhow::{bail, Context, Result};-use chrono::Utc;-use serde_json::Value;-use uuid::Uuid;--use crate::openhuman::config::Config;-use crate::openhuman::flows::types::{DraftOrigin, FlowDraft};--/// The directory holding draft files, `{workspace_dir}/flows/drafts`.-fn drafts_dir(config: &Config) -> PathBuf {- config.workspace_dir.join("flows").join("drafts")-}--/// Whether `id` is a safe draft-file stem — guards `get`/`update`/`delete`-/// against path traversal (`..`, separators) since the id reaches the-/// filesystem. Server-minted ids are UUIDs; this only accepts that shape.-fn is_safe_draft_id(id: &str) -> bool {- !id.is_empty()- && id.len() <= 64- && id- .chars()- .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')-}--/// The on-disk path for draft `id` (validated).-fn draft_path(config: &Config, id: &str) -> Result<PathBuf> {- if !is_safe_draft_id(id) {- bail!("invalid draft id: {id:?}");- }- Ok(drafts_dir(config).join(format!("{id}.json")))-}--/// Creates a new draft, writes it to disk, and returns it.-pub fn create_draft(- config: &Config,- flow_id: Option<String>,- name: String,- graph: Value,- origin: DraftOrigin,-) -> Result<FlowDraft> {- let now = Utc::now().to_rfc3339();- let draft = FlowDraft {- id: Uuid::new_v4().to_string(),- flow_id,- name,- graph,- origin,- created_at: now.clone(),- updated_at: now,- };- write_draft(config, &draft)?;- tracing::debug!(- target: "flows",- draft_id = %draft.id,- origin = draft.origin.as_str(),- "[flows] draft_store: created draft"- );- Ok(draft)-}--/// Reads a draft by id, or `None` if no such file exists.-pub fn get_draft(config: &Config, id: &str) -> Result<Option<FlowDraft>> {- let path = draft_path(config, id)?;- match std::fs::read(&path) {- Ok(bytes) => {- let draft: FlowDraft =- serde_json::from_slice(&bytes).with_context(|| format!("draft {id} is corrupt"))?;- Ok(Some(draft))- }- Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),- Err(e) => Err(e).with_context(|| format!("reading draft {id}")),- }-}--/// Patches a draft's mutable fields (any `Some` is applied), bumps-/// `updated_at`, persists, and returns the updated draft. Errors if the draft-/// does not exist.-pub fn update_draft(- config: &Config,- id: &str,- name: Option<String>,- graph: Option<Value>,- flow_id: Option<Option<String>>,-) -> Result<FlowDraft> {- let mut draft = get_draft(config, id)?.with_context(|| format!("draft {id} not found"))?;- if let Some(name) = name {- draft.name = name;- }- if let Some(graph) = graph {- draft.graph = graph;- }- if let Some(flow_id) = flow_id {- draft.flow_id = flow_id;- }- draft.updated_at = Utc::now().to_rfc3339();- write_draft(config, &draft)?;- tracing::debug!(target: "flows", draft_id = %id, "[flows] draft_store: updated draft");- Ok(draft)-}--/// Lists all drafts, newest-updated first. Skips (and logs) any corrupt file-/// rather than failing the whole listing.-pub fn list_drafts(config: &Config) -> Result<Vec<FlowDraft>> {- let dir = drafts_dir(config);- let entries = match std::fs::read_dir(&dir) {- Ok(entries) => entries,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),- Err(e) => return Err(e).with_context(|| format!("listing drafts in {}", dir.display())),- };- let mut drafts = Vec::new();- for entry in entries.flatten() {- let path = entry.path();- if path.extension().and_then(|e| e.to_str()) != Some("json") {- continue;- }- match std::fs::read(&path).map(|b| serde_json::from_slice::<FlowDraft>(&b)) {- Ok(Ok(draft)) => drafts.push(draft),- Ok(Err(e)) => {- tracing::warn!(target: "flows", path = %path.display(), error = %e, "[flows] draft_store: skipping corrupt draft file");- }- Err(e) => {- tracing::warn!(target: "flows", path = %path.display(), error = %e, "[flows] draft_store: could not read draft file");- }- }- }- // Newest-updated first (RFC3339 with a fixed +00:00 offset sorts lexically).- drafts.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));- Ok(drafts)-}--/// Deletes a draft file. Returns `true` if a file was removed, `false` if it-/// was already absent.-pub fn delete_draft(config: &Config, id: &str) -> Result<bool> {- let path = draft_path(config, id)?;- match std::fs::remove_file(&path) {- Ok(()) => {- tracing::debug!(target: "flows", draft_id = %id, "[flows] draft_store: deleted draft");- Ok(true)- }- Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),- Err(e) => Err(e).with_context(|| format!("deleting draft {id}")),- }-}--/// Serializes a draft to its file, creating the drafts dir if needed. Writes to-/// a temp file then renames, so a crash mid-write never leaves a corrupt draft.-fn write_draft(config: &Config, draft: &FlowDraft) -> Result<()> {- let dir = drafts_dir(config);- std::fs::create_dir_all(&dir)- .with_context(|| format!("creating drafts dir {}", dir.display()))?;- let path = draft_path(config, &draft.id)?;- let tmp = dir.join(format!(".{}.json.tmp", draft.id));- let json = serde_json::to_vec_pretty(draft).context("serializing draft")?;- std::fs::write(&tmp, &json).with_context(|| format!("writing {}", tmp.display()))?;- std::fs::rename(&tmp, &path).with_context(|| format!("renaming into {}", path.display()))?;- Ok(())-}--#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;- use tempfile::TempDir;-- fn test_config(tmp: &TempDir) -> Config {- Config {- workspace_dir: tmp.path().join("workspace"),- action_dir: tmp.path().join("workspace"),- config_path: tmp.path().join("config.toml"),- ..Config::default()- }- }-- fn sample_graph() -> Value {- json!({ "nodes": [ { "id": "t", "kind": "trigger", "name": "Manual" } ], "edges": [] })- }-- #[test]- fn create_get_roundtrip() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let draft = create_draft(- &config,- None,- "My draft".into(),- sample_graph(),- DraftOrigin::Chat,- )- .unwrap();- let loaded = get_draft(&config, &draft.id).unwrap().unwrap();- assert_eq!(loaded, draft);- assert_eq!(loaded.name, "My draft");- assert_eq!(loaded.origin, DraftOrigin::Chat);- assert!(loaded.flow_id.is_none());- }-- #[test]- fn get_missing_is_none() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- assert!(get_draft(&config, "does-not-exist").unwrap().is_none());- }-- #[test]- fn update_patches_fields_and_bumps_updated_at() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let draft = create_draft(- &config,- None,- "Old".into(),- sample_graph(),- DraftOrigin::Canvas,- )- .unwrap();- let updated = update_draft(- &config,- &draft.id,- Some("New name".into()),- Some(json!({ "nodes": [], "edges": [] })),- Some(Some("flow-42".into())),- )- .unwrap();- assert_eq!(updated.name, "New name");- assert_eq!(updated.flow_id.as_deref(), Some("flow-42"));- assert_eq!(updated.graph["nodes"].as_array().unwrap().len(), 0);- assert!(updated.updated_at >= draft.updated_at);- assert_eq!(updated.created_at, draft.created_at);- }-- #[test]- fn list_returns_newest_first_and_delete_removes() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let a = create_draft(&config, None, "A".into(), sample_graph(), DraftOrigin::Chat).unwrap();- // Bump a second draft's updated_at by updating it after creation.- let b = create_draft(&config, None, "B".into(), sample_graph(), DraftOrigin::Chat).unwrap();- let b = update_draft(&config, &b.id, Some("B2".into()), None, None).unwrap();-- let list = list_drafts(&config).unwrap();- assert_eq!(list.len(), 2);- assert_eq!(list[0].id, b.id, "newest-updated first");-- assert!(delete_draft(&config, &a.id).unwrap());- assert!(- !delete_draft(&config, &a.id).unwrap(),- "second delete is a no-op"- );- assert_eq!(list_drafts(&config).unwrap().len(), 1);- }-- #[test]- fn list_on_missing_dir_is_empty() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- assert!(list_drafts(&config).unwrap().is_empty());- }-- #[test]- fn rejects_path_traversal_ids() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- assert!(get_draft(&config, "../secret").is_err());- assert!(draft_path(&config, "a/b").is_err());- assert!(draft_path(&config, "..").is_err());- assert!(draft_path(&config, "ok-123_ID").is_ok());- }-}diff --git a/src/openhuman/flows/n8n_import.rs b/src/openhuman/flows/n8n_import.rsdeleted file mode 100644index 83be055f17..0000000000--- a/src/openhuman/flows/n8n_import.rs+++ /dev/null@@ -1,1093 +0,0 @@-//! Best-effort importer that maps an **n8n** workflow export into a tinyflows-//! [`WorkflowGraph`]. Backs the `format: "n8n"` branch of `flows_import`-//! (`schemas::handle_import` → `ops::flows_import`).-//!-//! n8n and tinyflows share a large slice of automation vocabulary (branching,-//! merging, HTTP, code, triggers), so this maps the overlap directly:-//!-//! | n8n node type (`n8n-nodes-base.*`) | tinyflows kind |-//! | --------------------------------------- | ----------------------- |-//! | `if` | `condition` |-//! | `switch` | `switch` |-//! | `merge` | `merge` |-//! | `splitOut` / `itemLists`(splitOut mode) | `split_out` |-//! | `httpRequest` | `http_request` |-//! | `code` / `function` / `functionItem` | `code` |-//! | `scheduleTrigger` / `cron` / `interval` | `trigger` (schedule) |-//! | `webhook` | `trigger` (webhook) |-//! | `manualTrigger` | `trigger` (manual) |-//!-//! **Everything else is not a failed import** — an unmapped node type lands as-//! an annotated placeholder (`transform`) node carrying the original n8n type-//! and parameters in its `config`, plus a `_n8n_import` note, so the graph-//! still loads, validates, and can be edited on the canvas. Connections and-//! canvas positions are preserved wherever the source provides them.-//!-//! The mapping is intentionally lossy and advisory: every approximation-//! (unmapped type, untranslated expression, synthesized/demoted trigger) is-//! reported as a warning string the UI surfaces next to the imported draft.--use serde_json::{json, Map, Value};-use tinyflows::model::{Edge, Node, NodeKind, Position, WorkflowGraph};--/// The outcome of mapping an n8n workflow: the best-effort tinyflows graph plus-/// the list of advisory warnings collected during the mapping.-#[derive(Debug)]-pub(crate) struct N8nImportResult {- /// The mapped graph (still passed through `migrate` + `validate` by the- /// caller before it is handed to the UI).- pub graph: WorkflowGraph,- /// Human-readable, non-fatal notes: unmapped node types, untranslated- /// expressions, and any synthesized/demoted trigger.- pub warnings: Vec<String>,-}--/// Returns `true` when `value` looks like an n8n workflow export rather than a-/// native tinyflows `WorkflowGraph` — used by `flows_import`'s auto-detect. The-/// tell-tales are a top-level `connections` object and/or nodes carrying an-/// `n8n-nodes-base.*`/`type`-style discriminator (tinyflows nodes use `kind`).-pub(crate) fn looks_like_n8n(value: &Value) -> bool {- if value.get("connections").map(Value::is_object) == Some(true) {- return true;- }- let Some(nodes) = value.get("nodes").and_then(Value::as_array) else {- return false;- };- nodes.iter().any(|n| {- // A native tinyflows node has `kind`; an n8n node has `type` and no `kind`.- n.get("kind").is_none() && n.get("type").and_then(Value::as_str).is_some()- })-}--/// Maps a parsed n8n workflow JSON `value` into a tinyflows [`WorkflowGraph`].-///-/// Never returns `Err` for an unrecognized node type — those become annotated-/// placeholders. `Err` is reserved for input that is not shaped like an n8n-/// export at all (e.g. `nodes` is not an array).-pub(crate) fn map_n8n_workflow(value: &Value) -> Result<N8nImportResult, String> {- let mut warnings: Vec<String> = Vec::new();-- let name = value- .get("name")- .and_then(Value::as_str)- .unwrap_or("Imported workflow")- .to_string();-- let raw_nodes = value- .get("nodes")- .and_then(Value::as_array)- .ok_or_else(|| "n8n workflow is missing a `nodes` array".to_string())?;-- tracing::debug!(- target: "flows",- %name,- node_count = raw_nodes.len(),- "[flows] n8n_import: mapping n8n workflow"- );-- // n8n connections key nodes by *name*; tinyflows edges reference node *ids*.- // Build a name → id lookup so connections can be rewired onto ids.- let mut name_to_id: Map<String, Value> = Map::new();- let mut nodes: Vec<Node> = Vec::new();-- for raw in raw_nodes {- let n8n_name = raw- .get("name")- .and_then(Value::as_str)- .unwrap_or("node")- .to_string();- let id = raw- .get("id")- .and_then(Value::as_str)- .map(str::to_string)- .unwrap_or_else(|| slug(&n8n_name));- // n8n's `connections` map is keyed by node NAME (not id), and- // `map_connections` below rewires every edge that names this node- // through this lookup. A duplicate name is last-wins here, which- // silently mis-wires every connection naming it onto whichever node- // happened to be inserted last — R-m6. Every other approximation in- // this importer reports a warning; a duplicate name is the one- // silent mis-wiring, so warn on the collision the same way.- if let Some(previous_id) = name_to_id- .insert(n8n_name.clone(), Value::String(id.clone()))- .and_then(|v| v.as_str().map(str::to_string))- {- tracing::warn!(- target: "flows",- name = %n8n_name,- previous_id = %previous_id,- new_id = %id,- "[flows] n8n_import: duplicate node name collision — connections will mis-wire"- );- warnings.push(format!(- "Multiple n8n nodes are named '{n8n_name}' (ids '{previous_id}' and '{id}') — \- n8n connections are keyed by node name, so every connection naming \- '{n8n_name}' was rewired onto node '{id}' and may now point at the wrong \- node. Rename the duplicates in the source n8n workflow and re-import, or fix \- the affected edges by hand."- ));- }-- let n8n_type = raw.get("type").and_then(Value::as_str).unwrap_or("");- let params = raw.get("parameters").cloned().unwrap_or(Value::Null);- let position = parse_position(raw.get("position"));-- let (kind, config) = map_node(n8n_type, ¶ms, &n8n_name, &mut warnings);- nodes.push(Node {- id,- kind,- type_version: 1,- name: n8n_name,- config,- ports: Vec::new(),- position,- });- }-- // tinyflows requires exactly one trigger. Reconcile the mapped triggers:- // synthesize a manual one when none survived, or demote extras to- // placeholders when several did — either way `validate` will pass.- reconcile_triggers(&mut nodes, &mut warnings);-- let edges = map_connections(value.get("connections"), &name_to_id, &nodes, &mut warnings);-- let graph = WorkflowGraph {- schema_version: tinyflows::model::CURRENT_SCHEMA_VERSION,- id: None,- name,- // n8n has no equivalent of a declared workflow input — its workflows are- // parameterized through trigger/node config — so an import declares- // none. The author adds them afterwards if the flow needs them.- inputs: Vec::new(),- // n8n agent nodes carry their configuration inline; they do not define- // reusable TinyFlows agent-registry entries, so every `agent_ref`- // resolves against this host's own registry instead.- agents: Vec::new(),- nodes,- edges,- };-- tracing::debug!(- target: "flows",- node_count = graph.nodes.len(),- edge_count = graph.edges.len(),- warning_count = warnings.len(),- "[flows] n8n_import: mapping complete"- );-- Ok(N8nImportResult { graph, warnings })-}--/// Maps a single n8n node `type` + `parameters` to a tinyflows kind and config.-/// Unrecognized types return a `transform` placeholder carrying the original-/// type/params under `_n8n_import` and record a warning.-fn map_node(- n8n_type: &str,- params: &Value,- n8n_name: &str,- warnings: &mut Vec<String>,-) -> (NodeKind, Value) {- // Strip the vendor prefix so both `n8n-nodes-base.if` and a bare `if` match.- let short = n8n_type- .rsplit_once('.')- .map(|(_, s)| s)- .unwrap_or(n8n_type);-- match short {- "if" => (- NodeKind::Condition,- translate_config(params, warnings, n8n_name),- ),- "switch" => (- NodeKind::Switch,- translate_config(params, warnings, n8n_name),- ),- "merge" => (- NodeKind::Merge,- translate_config(params, warnings, n8n_name),- ),- "splitOut" | "itemLists" => (- NodeKind::SplitOut,- translate_config(params, warnings, n8n_name),- ),- "httpRequest" => (- NodeKind::HttpRequest,- map_http_request(params, warnings, n8n_name),- ),- "code" | "function" | "functionItem" => {- (NodeKind::Code, map_code(params, warnings, n8n_name))- }- "scheduleTrigger" | "cron" | "interval" => (- NodeKind::Trigger,- trigger_config("schedule", params, warnings, n8n_name),- ),- "webhook" => (- NodeKind::Trigger,- trigger_config("webhook", params, warnings, n8n_name),- ),- "manualTrigger" | "start" => (- NodeKind::Trigger,- trigger_config("manual", params, warnings, n8n_name),- ),- _ => {- warnings.push(format!(- "Node '{n8n_name}' has n8n type '{n8n_type}', which has no tinyflows equivalent — \- imported as an editable placeholder that carries its original configuration. \- Replace it with a supported node before enabling the flow."- ));- let config = json!({- "_n8n_import": {- "original_type": n8n_type,- "note": "Unmapped n8n node imported as a placeholder; original parameters preserved below.",- },- "parameters": params,- });- (NodeKind::Transform, config)- }- }-}--/// Builds a tinyflows `trigger` config carrying the given `trigger_kind`-/// discriminator plus any (expression-translated) source parameters.-fn trigger_config(- trigger_kind: &str,- params: &Value,- warnings: &mut Vec<String>,- n8n_name: &str,-) -> Value {- let mut cfg = match translate_config(params, warnings, n8n_name) {- Value::Object(map) => map,- _ => Map::new(),- };- cfg.insert(- "trigger_kind".to_string(),- Value::String(trigger_kind.to_string()),- );- Value::Object(cfg)-}--/// Maps n8n `httpRequest` parameters onto tinyflows' `{ method, url, ... }`-/// http_request config. n8n uses `url` + `method`/`requestMethod`; anything-/// else is carried through after expression translation.-fn map_http_request(params: &Value, warnings: &mut Vec<String>, n8n_name: &str) -> Value {- let translated = translate_config(params, warnings, n8n_name);- let mut cfg = match translated {- Value::Object(map) => map,- _ => Map::new(),- };- // Normalize the method key (`requestMethod` is the older n8n spelling).- if !cfg.contains_key("method") {- if let Some(method) = cfg.remove("requestMethod") {- cfg.insert("method".to_string(), method);- }- }- cfg.entry("method".to_string())- .or_insert_with(|| Value::String("GET".to_string()));- Value::Object(cfg)-}--/// Maps n8n `code`/`function` parameters onto tinyflows' code config, pulling-/// the source out of n8n's `jsCode`/`functionCode`/`pythonCode` fields into the-/// `source` key tinyflows' `code` node actually reads (`vendor/tinyflows/src/nodes/integration/code.rs`)-/// while preserving the language hint.-fn map_code(params: &Value, warnings: &mut Vec<String>, n8n_name: &str) -> Value {- let translated = translate_config(params, warnings, n8n_name);- let mut cfg = match translated {- Value::Object(map) => map,- _ => Map::new(),- };- for (src, lang) in [- ("jsCode", "javascript"),- ("functionCode", "javascript"),- ("pythonCode", "python"),- ] {- if let Some(code) = cfg.remove(src) {- cfg.entry("source".to_string()).or_insert(code);- cfg.entry("language".to_string())- .or_insert_with(|| Value::String(lang.to_string()));- }- }- Value::Object(cfg)-}--/// Recursively translates n8n `={{ … }}` expressions inside a config `Value`-/// into tinyflows' `=`-prefixed jq form where trivially possible; anything not-/// trivially translatable is left as its raw string and a warning is recorded.-fn translate_config(value: &Value, warnings: &mut Vec<String>, n8n_name: &str) -> Value {- match value {- Value::String(s) => Value::String(translate_expr(s, warnings, n8n_name)),- Value::Array(items) => Value::Array(- items- .iter()- .map(|v| translate_config(v, warnings, n8n_name))- .collect(),- ),- Value::Object(map) => {- let mut out = Map::new();- for (k, v) in map {- out.insert(k.clone(), translate_config(v, warnings, n8n_name));- }- Value::Object(out)- }- other => other.clone(),- }-}--/// Translates a single n8n expression string. An n8n expression is a string-/// beginning with `=` whose body is `{{ … }}`. The trivially-translatable case-/// is a single `{{ $json.<path> }}` reference, which becomes tinyflows'-/// `=.item.<path>` jq. Anything richer is returned unchanged with a warning.-///-/// n8n's `$json` is the current input item's json — the tinyflows expression-/// scope root is `{item, items, run, nodes}` (`vendor/tinyflows/src/nodes/mod.rs::expr_scope_for`),-/// which binds exactly that under `item`. So `$json` must translate to-/// `.item`, never the bare `.` root: `.` would resolve the WHOLE scope object-/// (`item` + `items` + `run` + `nodes`), not the item, and `.<path>` without-/// the `item` segment dereferences a key that does not exist at the scope-/// root and is GUARANTEED to resolve `null` at runtime (R-C1).-fn translate_expr(raw: &str, warnings: &mut Vec<String>, n8n_name: &str) -> String {- // Only n8n expression strings start with `=`; plain values pass through.- if !raw.starts_with('=') {- return raw.to_string();- }- let body = raw[1..].trim();- let Some(inner) = body- .strip_prefix("{{")- .and_then(|b| b.strip_suffix("}}"))- .map(str::trim)- else {- // A `=`-prefixed non-`{{ }}` string: keep raw, warn.- warnings.push(untranslated_warning(n8n_name, raw));- return raw.to_string();- };-- // Trivial single-reference case: `$json.foo.bar` (or `$json["foo"]`).- if let Some(path) = inner.strip_prefix("$json") {- if let Some(jq_path) = json_path_to_jq(path) {- // `json_path_to_jq` returns the tail path RELATIVE to `$json`- // (`.foo`, `.foo.bar`, or `""` when there's no tail at all — see- // its doc). Prefixing `.item` here binds it at the tinyflows- // scope's `item` key instead of the scope root (see this fn's- // doc, R-C1): the empty-tail case naturally becomes `.item` (not- // `.item.`) because the tail is `""`, with no special-casing- // needed here.- tracing::debug!(- target: "flows",- node = %n8n_name,- %raw,- translated = %format!("=.item{jq_path}"),- "[flows] n8n_import: translated $json expression"- );- return format!("=.item{jq_path}");- }- }-- warnings.push(untranslated_warning(n8n_name, raw));- raw.to_string()-}--/// Turns an n8n `$json` accessor tail (`.foo.bar`, `["foo"]`, or empty) into a-/// jq path relative to `$json` itself (`.foo.bar`, `.foo`, or `""` for an-/// empty tail — deliberately NOT `.`, so the caller can prepend `.item`-/// without special-casing the empty case, see [`translate_expr`]). Returns-/// `None` for anything that isn't a plain dotted / bracketed-string path-/// (arithmetic, function calls, bracket-index into arrays, etc.), so the-/// caller falls back to raw + warn.-fn json_path_to_jq(tail: &str) -> Option<String> {- let tail = tail.trim();- if tail.is_empty() {- return Some(String::new());- }- let mut jq = String::new();- let mut rest = tail;- while !rest.is_empty() {- if let Some(after) = rest.strip_prefix('.') {- // `.identifier`- let end = after- .find(|c: char| !c.is_alphanumeric() && c != '_')- .unwrap_or(after.len());- if end == 0 {- return None;- }- jq.push('.');- jq.push_str(&after[..end]);- rest = &after[end..];- } else if let Some(after) = rest.strip_prefix('[') {- // `["identifier"]` or `['identifier']` — string keys only.- let close = after.find(']')?;- let key = after[..close].trim();- let key = key- .strip_prefix('"')- .and_then(|k| k.strip_suffix('"'))- .or_else(|| key.strip_prefix('\'').and_then(|k| k.strip_suffix('\'')))?;- if key.is_empty() {- return None;- }- jq.push('.');- jq.push_str(&jq_field(key));- rest = &after[close + 1..];- } else {- return None;- }- }- Some(jq)-}--/// Renders a single jq field-access key: bare (`foo`) when `key` is a plain-/// identifier (alphanumeric/underscore, not digit-leading), else quoted-/// (`"first name"`) per jq's dot-plus-quoted-string syntax — required for any-/// key containing spaces or punctuation, which `.foo bar` (unquoted) is not-/// valid jq for.-fn jq_field(key: &str) -> String {- let is_bare_identifier = !key.is_empty()- && !key.starts_with(|c: char| c.is_ascii_digit())- && key.chars().all(|c| c.is_alphanumeric() || c == '_');- if is_bare_identifier {- key.to_string()- } else {- format!("{:?}", key)- }-}--fn untranslated_warning(n8n_name: &str, raw: &str) -> String {- format!(- "Node '{n8n_name}' uses an n8n expression that was not automatically translated \- (`{raw}`) — it was kept as a raw string. Review and rewrite it as a tinyflows \- `=`-jq expression."- )-}--/// Ensures the graph has exactly one trigger, mutating `nodes` in place:-/// - zero triggers → prepend a synthesized `manual` trigger (with a warning);-/// - multiple triggers → keep the first, demote the rest to placeholders.-fn reconcile_triggers(nodes: &mut Vec<Node>, warnings: &mut Vec<String>) {- let trigger_idxs: Vec<usize> = nodes- .iter()- .enumerate()- .filter(|(_, n)| n.kind == NodeKind::Trigger)- .map(|(i, _)| i)- .collect();-- match trigger_idxs.len() {- 0 => {- warnings.push(- "The n8n workflow had no importable trigger — a manual trigger was added so the \- flow is runnable. Attach a schedule or app-event trigger to run it automatically."- .to_string(),- );- // Collision-free synthetic id: an n8n graph may already have a- // (non-trigger) node literally named "trigger" — colliding with a- // hardcoded id would produce a duplicate-id graph and fail- // validation, turning an otherwise-recoverable import into a hard- // failure.- let mut trigger_id = "trigger".to_string();- let mut suffix = 2;- while nodes.iter().any(|n| n.id == trigger_id) {- trigger_id = format!("trigger_{suffix}");- suffix += 1;- }-- nodes.insert(- 0,- Node {- id: trigger_id,- kind: NodeKind::Trigger,- type_version: 1,- name: "Manual Trigger".to_string(),- config: json!({ "trigger_kind": "manual" }),- ports: Vec::new(),- position: None,- },- );- }- 1 => {}- _ => {- // Keep the first trigger; demote the rest so `validate` accepts the- // graph. Their ids are unchanged, so edges stay wired.- for &idx in trigger_idxs.iter().skip(1) {- let node = &mut nodes[idx];- warnings.push(format!(- "The n8n workflow had more than one trigger; '{}' was imported as a \- placeholder because a tinyflows flow allows only one trigger.",- node.name- ));- let original = node.config.clone();- node.kind = NodeKind::Transform;- node.config = json!({- "_n8n_import": {- "original_type": "trigger",- "note": "Extra trigger demoted to a placeholder (a flow allows one trigger).",- },- "parameters": original,- });- }- }- }-}--/// Rewrites n8n's name-keyed `connections` map onto tinyflows edges (id-keyed),-/// preserving output-port routing: an `if`/`condition` source routes output 0 →-/// `true` and 1 → `false`; a `switch` source routes output _i_ → `"i"`; every-/// other source uses `main`. Connections that reference an unknown node are-/// dropped with a warning.-fn map_connections(- connections: Option<&Value>,- name_to_id: &Map<String, Value>,- nodes: &[Node],- warnings: &mut Vec<String>,-) -> Vec<Edge> {- let mut edges = Vec::new();- let Some(Value::Object(conns)) = connections else {- return edges;- };-- for (src_name, outputs) in conns {- let Some(src_id) = name_to_id.get(src_name).and_then(Value::as_str) else {- continue;- };- let src_kind = nodes- .iter()- .find(|n| n.id == src_id)- .map(|n| n.kind.clone());- // n8n groups outputs by connection type (`main`, `ai_tool`, …); we only- // wire `main` — other connection families have no tinyflows analogue.- let Some(main) = outputs.get("main").and_then(Value::as_array) else {- continue;- };- for (port_index, port_targets) in main.iter().enumerate() {- let from_port = output_port_name(src_kind.as_ref(), port_index);- let Some(targets) = port_targets.as_array() else {- continue;- };- for target in targets {- let Some(tgt_name) = target.get("node").and_then(Value::as_str) else {- continue;- };- match name_to_id.get(tgt_name).and_then(Value::as_str) {- Some(tgt_id) => edges.push(Edge {- from_node: src_id.to_string(),- from_port: from_port.clone(),- to_node: tgt_id.to_string(),- to_port: "main".to_string(),- }),- None => warnings.push(format!(- "Connection from '{src_name}' to unknown node '{tgt_name}' was dropped."- )),- }- }- }- }- edges-}--/// The tinyflows output-port name for source `kind`'s n8n output index.-fn output_port_name(kind: Option<&NodeKind>, index: usize) -> String {- match kind {- Some(NodeKind::Condition) => {- if index == 0 {- "true".to_string()- } else {- "false".to_string()- }- }- Some(NodeKind::Switch) => index.to_string(),- _ => {- if index == 0 {- "main".to_string()- } else {- index.to_string()- }- }- }-}--/// Parses n8n's `position: [x, y]` array into a tinyflows [`Position`].-fn parse_position(value: Option<&Value>) -> Option<Position> {- let arr = value?.as_array()?;- let x = arr.first()?.as_f64()?;- let y = arr.get(1)?.as_f64()?;- Some(Position { x, y })-}--/// Derives a stable, id-safe slug from an n8n node name when the node carries-/// no `id` of its own.-fn slug(name: &str) -> String {- let s: String = name- .chars()- .map(|c| {- if c.is_alphanumeric() {- c.to_ascii_lowercase()- } else {- '_'- }- })- .collect();- if s.is_empty() {- "node".to_string()- } else {- s- }-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn looks_like_n8n_detects_connections_and_typed_nodes() {- assert!(looks_like_n8n(&json!({ "connections": {} })));- assert!(looks_like_n8n(&json!({- "nodes": [{ "name": "x", "type": "n8n-nodes-base.httpRequest" }]- })));- // A native tinyflows graph is not mistaken for n8n.- assert!(!looks_like_n8n(&json!({- "nodes": [{ "id": "t", "kind": "trigger", "name": "start" }],- "edges": []- })));- }-- #[test]- fn maps_if_node_to_condition_with_true_false_ports() {- let wf = json!({- "name": "branch",- "nodes": [- { "id": "s", "name": "Schedule Trigger", "type": "n8n-nodes-base.scheduleTrigger", "position": [0, 0] },- { "id": "c", "name": "IF", "type": "n8n-nodes-base.if", "position": [200, 0] },- { "id": "a", "name": "Yes", "type": "n8n-nodes-base.httpRequest", "position": [400, -100] },- { "id": "b", "name": "No", "type": "n8n-nodes-base.httpRequest", "position": [400, 100] }- ],- "connections": {- "Schedule Trigger": { "main": [[{ "node": "IF", "type": "main", "index": 0 }]] },- "IF": { "main": [- [{ "node": "Yes", "type": "main", "index": 0 }],- [{ "node": "No", "type": "main", "index": 0 }]- ] }- }- });- let result = map_n8n_workflow(&wf).expect("map");- let g = &result.graph;- assert_eq!(g.name, "branch");-- let cond = g.node("c").expect("condition node");- assert_eq!(cond.kind, NodeKind::Condition);-- let trig = g.node("s").expect("trigger node");- assert_eq!(trig.kind, NodeKind::Trigger);- assert_eq!(trig.config["trigger_kind"], json!("schedule"));- assert_eq!(trig.position, Some(Position { x: 0.0, y: 0.0 }));-- // The IF node's two outputs route to `true`/`false` ports.- let true_edge = g- .edges- .iter()- .find(|e| e.from_node == "c" && e.to_node == "a")- .expect("true edge");- assert_eq!(true_edge.from_port, "true");- let false_edge = g- .edges- .iter()- .find(|e| e.from_node == "c" && e.to_node == "b")- .expect("false edge");- assert_eq!(false_edge.from_port, "false");-- // Whole graph is structurally valid (exactly one trigger, real edges).- tinyflows::validate::validate(g).expect("valid graph");- }-- #[test]- fn unmapped_type_becomes_annotated_placeholder_not_a_failure() {- let wf = json!({- "name": "exotic",- "nodes": [- { "id": "t", "name": "Manual", "type": "n8n-nodes-base.manualTrigger" },- { "id": "x", "name": "Airtable", "type": "n8n-nodes-base.airtable",- "parameters": { "operation": "append", "table": "leads" } }- ],- "connections": {- "Manual": { "main": [[{ "node": "Airtable", "type": "main", "index": 0 }]] }- }- });- let result = map_n8n_workflow(&wf).expect("map");- let node = result.graph.node("x").expect("placeholder node");- assert_eq!(node.kind, NodeKind::Transform);- assert_eq!(- node.config["_n8n_import"]["original_type"],- json!("n8n-nodes-base.airtable")- );- // Original parameters are preserved for editing.- assert_eq!(node.config["parameters"]["table"], json!("leads"));- // The unmapped type produced a warning.- assert!(result.warnings.iter().any(|w| w.contains("airtable")));- tinyflows::validate::validate(&result.graph).expect("valid graph");- }-- #[test]- fn synthesizes_manual_trigger_when_none_present() {- let wf = json!({- "name": "no-trigger",- "nodes": [- { "id": "h", "name": "HTTP", "type": "n8n-nodes-base.httpRequest" }- ],- "connections": {}- });- let result = map_n8n_workflow(&wf).expect("map");- assert_eq!(- result- .graph- .nodes- .iter()- .filter(|n| n.kind == NodeKind::Trigger)- .count(),- 1- );- assert!(result.warnings.iter().any(|w| w.contains("manual trigger")));- tinyflows::validate::validate(&result.graph).expect("valid graph");- }-- #[test]- fn synthesized_trigger_id_avoids_colliding_with_an_existing_node() {- // The n8n graph already has a (non-trigger) node literally id'd- // "trigger" — the synthesized manual trigger must not collide with it.- let wf = json!({- "name": "id-collision",- "nodes": [- { "id": "trigger", "name": "HTTP", "type": "n8n-nodes-base.httpRequest" }- ],- "connections": {}- });- let result = map_n8n_workflow(&wf).expect("map");- let ids: Vec<&str> = result.graph.nodes.iter().map(|n| n.id.as_str()).collect();- // Both the original node and the synthesized trigger survive, under- // distinct ids.- assert_eq!(ids.len(), 2);- assert!(ids.contains(&"trigger"));- assert!(ids.iter().any(|id| *id != "trigger"));- assert_eq!(- result- .graph- .nodes- .iter()- .filter(|n| n.kind == NodeKind::Trigger)- .count(),- 1- );- tinyflows::validate::validate(&result.graph).expect("valid graph");- }-- #[test]- fn demotes_extra_triggers_to_placeholders() {- let wf = json!({- "name": "two-triggers",- "nodes": [- { "id": "s", "name": "Schedule", "type": "n8n-nodes-base.scheduleTrigger" },- { "id": "w", "name": "Webhook", "type": "n8n-nodes-base.webhook" }- ],- "connections": {}- });- let result = map_n8n_workflow(&wf).expect("map");- assert_eq!(- result- .graph- .nodes- .iter()- .filter(|n| n.kind == NodeKind::Trigger)- .count(),- 1- );- // The demoted trigger is now a placeholder transform.- let demoted = result.graph.node("w").expect("webhook node");- assert_eq!(demoted.kind, NodeKind::Transform);- tinyflows::validate::validate(&result.graph).expect("valid graph");- }-- #[test]- fn translates_trivial_json_expression_to_jq() {- // R-C1: n8n's `$json` is the CURRENT INPUT ITEM, which the tinyflows- // scope binds under `item` (scope root is `{item, items, run,- // nodes}` — `vendor/tinyflows/src/nodes/mod.rs::expr_scope_for`).- // The translated jq path must therefore dereference `.item` first —- // `=.email` (the old, buggy output) dereferences a key that doesn't- // exist at the scope root and is GUARANTEED to resolve `null`.- let mut warnings = Vec::new();- assert_eq!(- translate_expr("={{ $json.email }}", &mut warnings, "n"),- "=.item.email"- );- assert_eq!(- translate_expr("={{ $json.user.name }}", &mut warnings, "n"),- "=.item.user.name"- );- // A bracket key with a space isn't a bare jq identifier — must come out- // quoted (`."first name"`), not `.first name` (invalid jq).- assert_eq!(- translate_expr("={{ $json[\"first name\"] }}", &mut warnings, "n"),- "=.item.\"first name\""- );- // `{{ $json }}` (no tail) must become `.item`, NOT the bare `.` root —- // `.` would return the whole `{item, items, run, nodes}` scope object,- // not the item.- assert_eq!(translate_expr("={{ $json }}", &mut warnings, "n"), "=.item");- assert!(warnings.is_empty());- }-- /// R-C1 regression proof: actually evaluate the translated expression- /// against a scope shaped exactly like the tinyflows engine's real- /// `expr_scope_for` (`vendor/tinyflows/src/nodes/mod.rs`), and assert it- /// resolves the real field — NOT `null`. This is the check that would- /// have caught the original bug: the old `=.email` translation compiles- /// fine and passes structural validation, it just silently resolves- /// `null` at runtime because `email` isn't a key at the scope root.- #[test]- fn translated_json_expression_resolves_against_the_real_engine_scope() {- let mut warnings = Vec::new();- let translated = translate_expr("={{ $json.email }}", &mut warnings, "n");- assert!(warnings.is_empty());-- let scope = json!({- "item": { "email": "[email protected]" },- "items": [{ "email": "[email protected]" }],- "run": {},- "nodes": {},- });- assert_eq!(- tinyflows::expr::evaluate(&json!(translated), &scope),- json!("[email protected]"),- "translated expression `{translated}` must resolve the real field, not null"- );-- // The pre-fix translation (`=.email`) is left here as a negative- // control: it dereferences a key that does not exist at the scope- // root and is GUARANTEED to resolve null — exactly the bug R-C1- // describes.- assert_eq!(- tinyflows::expr::evaluate(&json!("=.email"), &scope),- Value::Null- );-- // Bare `{{ $json }}` → `.item` must resolve the WHOLE item, not the- // whole scope (which would additionally carry `items`/`run`/`nodes`).- let translated_whole = translate_expr("={{ $json }}", &mut warnings, "n");- assert_eq!(- tinyflows::expr::evaluate(&json!(translated_whole), &scope),- json!({ "email": "[email protected]" })- );- }-- #[test]- fn jq_field_quotes_non_bare_identifiers() {- // Plain identifiers stay bare.- assert_eq!(jq_field("foo"), "foo");- assert_eq!(jq_field("foo_bar"), "foo_bar");- // Spaces, punctuation, and digit-leading keys aren't bare jq- // identifiers — jq requires the dot-plus-quoted-string form for these.- assert_eq!(jq_field("first name"), "\"first name\"");- assert_eq!(jq_field("foo-bar"), "\"foo-bar\"");- assert_eq!(jq_field("123key"), "\"123key\"");- }-- #[test]- fn leaves_untranslatable_expression_raw_with_warning() {- let mut warnings = Vec::new();- let raw = "={{ $json.a + $json.b }}";- assert_eq!(translate_expr(raw, &mut warnings, "Math"), raw);- assert_eq!(warnings.len(), 1);- assert!(warnings[0].contains("not automatically translated"));- }-- #[test]- fn plain_string_is_not_treated_as_expression() {- let mut warnings = Vec::new();- assert_eq!(translate_expr("hello", &mut warnings, "n"), "hello");- assert!(warnings.is_empty());- }-- #[test]- fn http_request_maps_url_and_method() {- let mut warnings = Vec::new();- let cfg = map_http_request(- &json!({ "url": "https://api.example.com", "requestMethod": "POST" }),- &mut warnings,- "HTTP",- );- assert_eq!(cfg["url"], json!("https://api.example.com"));- assert_eq!(cfg["method"], json!("POST"));- // Expression in the url is translated in place.- let cfg2 = map_http_request(- &json!({ "url": "={{ $json.endpoint }}" }),- &mut warnings,- "HTTP",- );- assert_eq!(cfg2["url"], json!("=.item.endpoint"));- assert_eq!(cfg2["method"], json!("GET"));- }-- #[test]- fn code_node_pulls_source_and_language() {- let mut warnings = Vec::new();- let cfg = map_code(&json!({ "jsCode": "return items;" }), &mut warnings, "Code");- assert_eq!(cfg["source"], json!("return items;"));- assert_eq!(cfg["language"], json!("javascript"));- }-- #[test]- fn switch_ports_are_numeric_indices() {- assert_eq!(output_port_name(Some(&NodeKind::Switch), 0), "0");- assert_eq!(output_port_name(Some(&NodeKind::Switch), 2), "2");- assert_eq!(output_port_name(Some(&NodeKind::Condition), 0), "true");- assert_eq!(output_port_name(Some(&NodeKind::Condition), 1), "false");- assert_eq!(output_port_name(Some(&NodeKind::Merge), 0), "main");- }-- #[test]- fn missing_nodes_array_is_an_error() {- let err = map_n8n_workflow(&json!({ "name": "x" })).unwrap_err();- assert!(err.contains("nodes"));- }-- #[test]- fn drops_connection_to_unknown_node_with_warning() {- let wf = json!({- "name": "dangling",- "nodes": [- { "id": "t", "name": "Manual", "type": "n8n-nodes-base.manualTrigger" }- ],- "connections": {- "Manual": { "main": [[{ "node": "Ghost", "type": "main", "index": 0 }]] }- }- });- let result = map_n8n_workflow(&wf).expect("map");- assert!(result.graph.edges.is_empty());- assert!(result.warnings.iter().any(|w| w.contains("Ghost")));- }-- // ── R-m6: duplicate n8n node names ──────────────────────────────────────-- #[test]- fn duplicate_node_name_collision_emits_a_warning() {- // n8n's `connections` map is keyed by node NAME, not id. Two nodes- // sharing the name "HTTP" mean `name_to_id` last-wins onto id "b" —- // any connection naming "HTTP" (including the trigger's own edge)- // silently rewires onto "b" instead of "a" with no warning, unless- // this collision is reported (R-m6: every other approximation in- // this importer warns; this was the one silent mis-wiring).- let wf = json!({- "name": "dup-names",- "nodes": [- { "id": "t", "name": "Manual", "type": "n8n-nodes-base.manualTrigger" },- { "id": "a", "name": "HTTP", "type": "n8n-nodes-base.httpRequest",- "parameters": { "url": "https://a.example.com" } },- { "id": "b", "name": "HTTP", "type": "n8n-nodes-base.httpRequest",- "parameters": { "url": "https://b.example.com" } }- ],- "connections": {- "Manual": { "main": [[{ "node": "HTTP", "type": "main", "index": 0 }]] }- }- });- let result = map_n8n_workflow(&wf).expect("map");-- // The collision itself is reported.- let collision_warning = result- .warnings- .iter()- .find(|w| w.contains("named 'HTTP'"))- .unwrap_or_else(|| {- panic!(- "expected a duplicate-name warning, got {:?}",- result.warnings- )- });- assert!(collision_warning.contains('a'));- assert!(collision_warning.contains('b'));-- // Both original nodes still exist under their own ids — nothing was- // dropped, only the *name*-keyed connection lookup collided.- assert!(result.graph.node("a").is_some());- assert!(result.graph.node("b").is_some());-- // The connection resolves deterministically onto exactly one target- // (last-wins onto "b") rather than silently vanishing or duplicating- // — the fix is the warning, not a change to which id wins.- assert_eq!(result.graph.edges.len(), 1);- assert_eq!(result.graph.edges[0].to_node, "b");-- tinyflows::validate::validate(&result.graph).expect("valid graph");- }-- // ── R-C1 end-to-end: n8n `$json` import passes binding-resolvability ───-- /// Imports a small n8n fixture that uses `$json` bindings end-to-end- /// through the exact same path `ops::flows_import` takes (map →- /// re-serialize → `validate_and_migrate_graph`), then runs the imported- /// graph through the domain's own binding-resolvability hard gate- /// (`ops::validate_binding_resolvability`, the same gate- /// `propose_workflow`/`revise_workflow`/`save_workflow` enforce before- /// accepting ANY graph — see `ops.rs`'s "Enforcing binding-resolvability- /// gate" section) and confirms it is accepted with zero errors, exactly- /// as `ops_tests.rs`'s `binding_to_agent_with_matching_schema_is_accepted`- /// exercises the gate for a hand-authored graph.- #[test]- fn imported_json_bindings_pass_binding_resolvability_and_resolve_the_real_item() {- use crate::openhuman::flows::ops::{- validate_and_migrate_graph, validate_binding_resolvability,- };-- let wf = json!({- "name": "json-binding-import",- "nodes": [- { "id": "t", "name": "Webhook", "type": "n8n-nodes-base.webhook" },- { "id": "h", "name": "Notify", "type": "n8n-nodes-base.httpRequest",- "parameters": {- "url": "={{ $json.callback_url }}",- "requestMethod": "POST"- } }- ],- "connections": {- "Webhook": { "main": [[{ "node": "Notify", "type": "main", "index": 0 }]] }- }- });-- let mapped = map_n8n_workflow(&wf).expect("map");- // No warning for the `$json.callback_url` binding — it's the trivial- // translatable case.- assert!(- !mapped- .warnings- .iter()- .any(|w| w.contains("callback_url") || w.contains("not automatically translated")),- "{:?}",- mapped.warnings- );-- let http_node = mapped.graph.node("h").expect("http node");- assert_eq!(http_node.config["url"], json!("=.item.callback_url"));-- // Re-enter the same migrate + validate path `flows_import` uses.- let value = serde_json::to_value(&mapped.graph).expect("serialize graph");- let graph =- validate_and_migrate_graph(value).expect("imported graph is structurally valid");-- // The domain's hard binding-resolvability gate accepts the imported- // graph — the same gate a hand-authored graph must clear before- // `propose_workflow`/`save_workflow` will accept it.- assert!(- validate_binding_resolvability(&graph).is_empty(),- "{:?}",- validate_binding_resolvability(&graph)- );-- // The direct proof this whole importer exists to guarantee: the- // translated binding actually resolves the real upstream item field- // at runtime, evaluated against a scope shaped like the tinyflows- // engine's real `expr_scope_for` — NOT null, which is exactly what- // the pre-fix `=.callback_url` translation would have produced.- let http_node = graph.node("h").expect("http node");- let scope = json!({- "item": { "callback_url": "https://example.com/hook" },- "items": [{ "callback_url": "https://example.com/hook" }],- "run": {},- "nodes": {},- });- let resolved = tinyflows::expr::evaluate(&http_node.config["url"], &scope);- assert_eq!(resolved, json!("https://example.com/hook"));- }-}diff --git a/src/openhuman/flows/run_registry.rs b/src/openhuman/flows/run_registry.rsdeleted file mode 100644index 0479ab34da..0000000000--- a/src/openhuman/flows/run_registry.rs+++ /dev/null@@ -1,204 +0,0 @@-//! Process-local registry of in-flight flow runs, keyed by `run_id`-//! (== the run's checkpointer `thread_id`), so `flows_cancel_run` (issue G4)-//! can signal a synchronously-executing run to abort.-//!-//! A `flows_run` / `flows_resume` executes inline inside its RPC await (or a-//! fire-and-forget `tokio::spawn` from `flows::bus`), so there is no-//! `JoinHandle` a caller can reach. Instead each active run [`register`]s a-//! [`tokio_util::sync::CancellationToken`] here for the duration of the run and-//! `tokio::select!`s its future against the token's `cancelled()`. A separate-//! `flows_cancel_run` RPC looks the token up by `run_id` and [`cancel`]s it,-//! tripping the run's select arm.-//!-//! The registration is RAII: [`register`] returns a [`RunGuard`] that removes-//! the entry on `Drop` (including on panic / early return), so a finished run-//! can never leave a stale token wedged in the map.--use std::collections::HashMap;-use std::sync::atomic::{AtomicU64, Ordering};-use std::sync::{LazyLock, Mutex};--use tokio_util::sync::CancellationToken;--/// Monotonic registration id, so a [`RunGuard`] can prove an entry is still-/// *its own* before removing it. See [`RunGuard::drop`].-static NEXT_REGISTRATION: AtomicU64 = AtomicU64::new(1);--/// The live in-flight runs: `run_id` → (registration id, cancellation token).-static IN_FLIGHT: LazyLock<Mutex<HashMap<String, (u64, CancellationToken)>>> =- LazyLock::new(|| Mutex::new(HashMap::new()));--/// Registers `run_id` as in-flight and returns both a clone of its-/// cancellation token (to `select!` on) and a [`RunGuard`] that deregisters it-/// on drop. Hold the guard for the whole run.-///-/// A duplicate `run_id` replaces the prior token, and each registration carries-/// a unique id so a guard only ever removes the entry it installed.-///-/// This used to be documented as impossible ("thread ids are UUID-suffixed"),-/// which held while only `flows_run` / `flows_run_detached` registered — both-/// mint a fresh UUID `thread_id` per call, so two concurrent registrations could-/// never collide on a key. `flows_resume` is the first caller to register-/// against a **stable, pre-existing** id (the parked run's own), and nothing-/// serializes two concurrent resumes of the same run — a client double-submit or-/// a retry-on-timeout is enough. With removal keyed only by `run_id`, the loser-/// of that race would deregister the *winner's* live token on its way out, and a-/// later `flows_cancel_run` would then see `is_in_flight == false` for a run that-/// is genuinely executing, take its "parked/stale" branch, and drop the-/// checkpoint out from under it — the exact bug class this registry exists to-/// prevent.-pub(crate) fn register(run_id: &str) -> (CancellationToken, RunGuard) {- let token = CancellationToken::new();- let registration = NEXT_REGISTRATION.fetch_add(1, Ordering::Relaxed);- let displaced = IN_FLIGHT- .lock()- .unwrap_or_else(|e| e.into_inner())- .insert(run_id.to_string(), (registration, token.clone()));- if displaced.is_some() {- tracing::warn!(- target: "flows",- run_id,- registration,- "[flows] run_registry: duplicate registration for a run id already in flight — the displaced guard will no longer deregister this entry"- );- }- tracing::debug!(target: "flows", run_id, registration, "[flows] run_registry: registered in-flight run");- (- token,- RunGuard {- run_id: run_id.to_string(),- registration,- },- )-}--/// Signals the in-flight run keyed by `run_id` to cancel, if one is registered.-/// Returns `true` when a live run was signalled, `false` when no run with that-/// id is currently in flight (e.g. it already settled, or is a parked-/// `pending_approval` row with no executing task).-pub(crate) fn cancel(run_id: &str) -> bool {- let guard = IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner());- match guard.get(run_id) {- Some((_registration, token)) => {- token.cancel();- tracing::info!(target: "flows", run_id, "[flows] run_registry: signalled in-flight run to cancel");- true- }- None => {- tracing::debug!(target: "flows", run_id, "[flows] run_registry: no in-flight run to cancel");- false- }- }-}--/// Returns `true` when `run_id` is currently registered as an in-flight run in-/// THIS process. Used by the boot-time orphan sweep (bug B42) to distinguish a-/// genuinely orphaned `running` row (left by a prior process — not in flight)-/// from one a freshly-started run in this process legitimately owns, so the-/// sweep never reconciles a live run out from under itself.-pub(crate) fn is_in_flight(run_id: &str) -> bool {- IN_FLIGHT- .lock()- .unwrap_or_else(|e| e.into_inner())- .contains_key(run_id)-}--/// RAII guard that removes a run's entry from the in-flight registry on drop.-pub(crate) struct RunGuard {- run_id: String,- registration: u64,-}--impl Drop for RunGuard {- /// Removes this run's entry — but only if it is still the entry THIS guard- /// installed. A plain `remove(&run_id)` would let the loser of a duplicate- /// registration deregister the winner's live token (see [`register`]).- fn drop(&mut self) {- let mut map = IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner());- match map.get(&self.run_id) {- Some((registration, _)) if *registration == self.registration => {- map.remove(&self.run_id);- tracing::debug!(target: "flows", run_id = %self.run_id, registration = self.registration, "[flows] run_registry: deregistered run");- }- Some(_) => {- tracing::debug!(- target: "flows",- run_id = %self.run_id,- registration = self.registration,- "[flows] run_registry: entry belongs to a newer registration — leaving it in place"- );- }- None => {}- }- }-}--#[cfg(test)]-mod tests {- // NOTE: `duplicate_registration_*` below pin the identity-based removal —- // see `register`'s doc for why `flows_resume` made this reachable.-- use super::*;-- #[test]- fn cancel_signals_a_registered_run_then_deregisters_on_drop() {- let run_id = "flow:reg-test:run-1";- let (token, guard) = register(run_id);- assert!(!token.is_cancelled());-- // A live run is signalled and its token trips.- assert!(cancel(run_id), "a registered run must be signalled");- assert!(token.is_cancelled(), "the run's token must be cancelled");-- // Dropping the guard removes it; a second cancel finds nothing.- drop(guard);- assert!(- !cancel(run_id),- "after the guard drops the run must no longer be in flight"- );- }-- #[test]- fn cancel_of_unknown_run_is_false() {- assert!(!cancel("flow:never-registered:run-x"));- }-- /// The loser of a duplicate registration must NOT deregister the winner's- /// live token. Before removal compared registration identity, the loser's- /// guard dropping would clear the map entry the winner still relies on, and- /// a later `cancel` would report "not in flight" for a genuinely running- /// run — letting the caller drop its checkpoint mid-execution.- #[test]- fn a_displaced_guard_does_not_deregister_the_live_registration() {- let run_id = "dup-resume-run";- let (_winner_token, winner_guard) = register(run_id);- // A second concurrent resume of the SAME run id registers on top.- let (_later_token, later_guard) = register(run_id);-- // The first (now displaced) guard drops, e.g. because it lost the- // guarded `mark_run_resuming` race and returned early.- drop(winner_guard);-- assert!(- is_in_flight(run_id),- "the newer, still-live registration must survive a displaced guard's drop"- );- assert!(cancel(run_id), "the live run must still be cancellable");-- drop(later_guard);- assert!(- !is_in_flight(run_id),- "the owning guard must still deregister its own entry"- );- }-- /// The ordinary single-registration path is unchanged.- #[test]- fn the_owning_guard_still_deregisters_its_own_entry() {- let run_id = "solo-run";- let (_token, guard) = register(run_id);- assert!(is_in_flight(run_id));- drop(guard);- assert!(!is_in_flight(run_id));- }-}diff --git a/src/openhuman/flows/store.rs b/src/openhuman/flows/store.rsdeleted file mode 100644index 200aca466d..0000000000--- a/src/openhuman/flows/store.rs+++ /dev/null@@ -1,1485 +0,0 @@-//! SQLite persistence for the `flows::` domain.-//!-//! Mirrors `src/openhuman/cron/store.rs`'s idiom: a `with_connection` helper-//! opens (and migrates) a dedicated SQLite database under the workspace, and-//! every public function takes `&Config` first and returns `anyhow::Result<T>`.-//!-//! Two tables:-//! - `flow_definitions` — one row per saved [`Flow`], with the graph stored as-//! JSON text (`graph_json`).-//! - `flow_state` — a generic namespaced key/value table backing-//! `tinyflows::caps::StateStore` (see `src/openhuman/flows/tinyflows/caps.rs`).-//!-//! There is deliberately **no** `flow_checkpoints` table here: the crate's own-//! `tinyagents::SqliteCheckpointer` owns checkpoint persistence in a separate-//! `checkpoints.db` (see `src/openhuman/flows/tinyflows/mod.rs::open_flow_checkpointer`).--use crate::openhuman::config::Config;-use crate::openhuman::flows::types::{- FlowRevision, FlowRun, FlowRunStep, FlowSuggestion, SuggestionStatus,-};-use crate::openhuman::flows::Flow;-use anyhow::{Context, Result};-use chrono::Utc;-use rusqlite::{params, Connection};-use std::collections::HashSet;-use std::path::{Path, PathBuf};-use std::sync::{Mutex, OnceLock};-use uuid::Uuid;--/// Tracks which flows database files have already had their schema DDL (the-/// `CREATE TABLE`/`CREATE INDEX` batch, `PRAGMA journal_mode = WAL`, and the-/// `add_column_if_missing` migration probe) run against them in this process-/// (R-m8). `with_connection` deliberately keeps opening a fresh, lightweight-/// `rusqlite::Connection` per call — `Connection` is `!Sync`, so caching a-/// single shared one would need a process-wide mutex that serializes every-/// caller, including the concurrent-writer scenario [`upsert_flow_run_step`]'s-/// `BEGIN IMMEDIATE` fix (R-m1) depends on being able to run from independent-/// connections. What actually repeats needlessly on every open is the DDL-/// batch itself — including once per node per live run via-/// `upsert_flow_run_step`. Gating just that batch behind a per-path-/// "already initialized" set keeps it to one execution per process per-/// database file while every call still gets its own connection.-///-/// Keyed by path rather than a single flag: tests each open an independent-/// per-`TempDir` workspace within the same test binary, and a bare-/// `OnceLock<()>` would silently skip schema creation for every database path-/// after the first test to run in the process.-static INITIALIZED_SCHEMAS: OnceLock<Mutex<HashSet<PathBuf>>> = OnceLock::new();--/// Runs the one-time schema DDL + migrations against `conn` unless `db_path`-/// has already been initialized in this process (see [`INITIALIZED_SCHEMAS`]).-/// Only marks `db_path` as initialized *after* [`init_schema`] succeeds, so a-/// transient failure (e.g. disk I/O) is retried on the next call rather than-/// permanently wedging the store into believing a schema exists that was-/// never created.-///-/// **Trust, but verify.** A cache hit is confirmed against the file actually on-/// disk before it is honoured. Before this gating existed, the DDL ran on every-/// `with_connection` call, so a database deleted or replaced at runtime — a-/// workspace reset, a manual deletion, a disk-recovery restore — self-healed on-/// the very next call: `Connection::open` silently creates a fresh empty file,-/// and `CREATE TABLE IF NOT EXISTS` immediately repopulated it. Caching removes-/// that safety net: the set still says "initialized" while the file behind it is-/// empty, so every subsequent query fails with `no such table` until the process-/// restarts. One indexed `sqlite_master` lookup is far cheaper than the ~11-/// statement DDL batch and restores the self-healing, so it is paid on each hit-/// rather than trusting a cache entry that the filesystem may have invalidated.-fn ensure_schema_initialized(conn: &Connection, db_path: &Path) -> Result<()> {- use rusqlite::OptionalExtension;-- let initialized = INITIALIZED_SCHEMAS.get_or_init(|| Mutex::new(HashSet::new()));- {- let guard = initialized- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- if guard.contains(db_path) {- let schema_present: bool = conn- .query_row(- "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'flow_definitions'",- [],- |_| Ok(true),- )- .optional()- .context("Failed to probe flows schema presence")?- .unwrap_or(false);- if schema_present {- return Ok(());- }- tracing::warn!(- target: "flows",- db = %db_path.display(),- "[flows] schema cached as initialized but the database has no tables (deleted or replaced at runtime?) — re-running schema init"- );- }- }- init_schema(conn)?;- let mut guard = initialized- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- guard.insert(db_path.to_path_buf());- Ok(())-}--/// The actual schema DDL: 5 `CREATE TABLE IF NOT EXISTS` + 6 `CREATE INDEX IF-/// NOT EXISTS` + `PRAGMA journal_mode = WAL` (a persistent db-file setting,-/// not per-connection — safe, and now guaranteed, to run only once) plus the-/// `require_approval` post-hoc column migration. Split out of-/// `with_connection` so [`ensure_schema_initialized`] can gate it (R-m8).-fn init_schema(conn: &Connection) -> Result<()> {- conn.execute_batch(- "PRAGMA journal_mode = WAL;- CREATE TABLE IF NOT EXISTS flow_definitions (- id TEXT PRIMARY KEY,- name TEXT NOT NULL,- graph_json TEXT NOT NULL,- enabled INTEGER NOT NULL DEFAULT 1,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- last_run_at TEXT,- last_status TEXT- );- CREATE INDEX IF NOT EXISTS idx_flow_definitions_enabled ON flow_definitions(enabled);-- CREATE TABLE IF NOT EXISTS flow_state (- namespace TEXT NOT NULL,- key TEXT NOT NULL,- value TEXT NOT NULL,- PRIMARY KEY (namespace, key)- );-- CREATE TABLE IF NOT EXISTS flow_runs (- id TEXT PRIMARY KEY,- flow_id TEXT NOT NULL,- thread_id TEXT NOT NULL,- status TEXT NOT NULL,- started_at TEXT NOT NULL,- finished_at TEXT,- steps_json TEXT NOT NULL DEFAULT '[]',- pending_approvals_json TEXT NOT NULL DEFAULT '[]',- error TEXT,- graph_hash TEXT,- FOREIGN KEY (flow_id) REFERENCES flow_definitions(id) ON DELETE CASCADE- );- CREATE INDEX IF NOT EXISTS idx_flow_runs_flow_id ON flow_runs(flow_id);- CREATE INDEX IF NOT EXISTS idx_flow_runs_started_at ON flow_runs(started_at);-- CREATE TABLE IF NOT EXISTS flow_suggestions (- id TEXT PRIMARY KEY,- title TEXT NOT NULL,- one_liner TEXT NOT NULL,- rationale TEXT NOT NULL,- trigger_hint TEXT,- steps_json TEXT NOT NULL DEFAULT '[]',- connections_json TEXT NOT NULL DEFAULT '[]',- slugs_json TEXT NOT NULL DEFAULT '[]',- build_prompt TEXT NOT NULL,- confidence REAL NOT NULL DEFAULT 0,- status TEXT NOT NULL DEFAULT 'new',- created_at TEXT NOT NULL,- source_run_id TEXT- );- CREATE INDEX IF NOT EXISTS idx_flow_suggestions_status ON flow_suggestions(status);- CREATE INDEX IF NOT EXISTS idx_flow_suggestions_created_at ON flow_suggestions(created_at);-- CREATE TABLE IF NOT EXISTS flow_revisions (- id TEXT PRIMARY KEY,- flow_id TEXT NOT NULL,- graph_json TEXT NOT NULL,- name TEXT NOT NULL,- require_approval INTEGER NOT NULL DEFAULT 0,- created_at TEXT NOT NULL,- FOREIGN KEY (flow_id) REFERENCES flow_definitions(id) ON DELETE CASCADE- );- CREATE INDEX IF NOT EXISTS idx_flow_revisions_flow_id ON flow_revisions(flow_id, created_at);",- )- .context("Failed to initialize flows schema")?;-- // `require_approval` (issue B2) — added post-hoc so a workspace created- // before this column existed still opens cleanly. Mirrors- // `cron::store`'s `add_column_if_missing` idiom.- add_column_if_missing(- conn,- "flow_definitions",- "require_approval",- "INTEGER NOT NULL DEFAULT 0",- )?;-- // T-M1 — added post-hoc so a workspace whose `flows.db` predates the- // stale-approval graph pin still opens cleanly. A row written before this- // migration reads back as `graph_hash IS NULL`, which `flows_resume`- // treats as "unknown — allow, with a warning log" (see its doc), never as- // a hard refusal, so upgrading mid-park cannot strand an in-flight- // approval.- add_column_if_missing(conn, "flow_runs", "graph_hash", "TEXT")?;-- Ok(())-}--/// Opens (creating/migrating as needed — once per process per database file,-/// see [`ensure_schema_initialized`]) the flows SQLite database and runs `f`-/// against the connection.-fn with_connection<T>(config: &Config, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {- let db_path = config.workspace_dir.join("flows").join("flows.db");- if let Some(parent) = db_path.parent() {- std::fs::create_dir_all(parent)- .with_context(|| format!("Failed to create flows directory: {}", parent.display()))?;- }-- let conn = Connection::open(&db_path)- .with_context(|| format!("Failed to open flows DB: {}", db_path.display()))?;-- // Per-connection pragmas: NOT persisted in the database file, so these- // must be reapplied on every open regardless of the schema-init cache- // below. `busy_timeout` retries (rather than immediately erroring- // `SQLITE_BUSY`) when a concurrent writer holds the lock — including this- // store's own `BEGIN IMMEDIATE` step upsert (R-m1); `foreign_keys` is- // required on every connection for the `ON DELETE CASCADE` FKs to be- // enforced.- conn.execute_batch("PRAGMA busy_timeout = 5000; PRAGMA foreign_keys = ON;")- .context("Failed to set flows DB connection pragmas")?;-- ensure_schema_initialized(&conn, &db_path)?;-- tracing::debug!(db = %db_path.display(), "[flows] store opened");-- f(&conn)-}--/// Adds `name` to `table` if it isn't already present, tolerating the race-/// where a concurrent process adds the same column between the `PRAGMA`-/// check and the `ALTER TABLE`. Mirrors `cron::store::add_column_if_missing`-/// (kept per-domain rather than shared — each store owns its own connection-/// helper and this is a handful of lines).-fn add_column_if_missing(conn: &Connection, table: &str, name: &str, sql_type: &str) -> Result<()> {- let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;- let mut rows = stmt.query([])?;- while let Some(row) = rows.next()? {- let col_name: String = row.get(1)?;- if col_name == name {- return Ok(());- }- }- drop(rows);- drop(stmt);-- match conn.execute(- &format!("ALTER TABLE {table} ADD COLUMN {name} {sql_type}"),- [],- ) {- Ok(_) => Ok(()),- Err(rusqlite::Error::SqliteFailure(err, Some(ref msg)))- if msg.contains("duplicate column name") =>- {- tracing::debug!(- "[flows] column {table}.{name} already exists (concurrent migration): {err}"- );- Ok(())- }- Err(e) => Err(e).with_context(|| format!("Failed to add {table}.{name}")),- }-}--/// Shared column list for every `flow_definitions` SELECT — keeps-/// [`map_flow_row`]'s positional `row.get(N)` calls in sync with the query.-const FLOW_DEFINITION_COLUMNS: &str = "id, name, graph_json, enabled, created_at, updated_at, \- last_run_at, last_status, require_approval";--/// Inserts or fully replaces a flow definition row.-pub fn upsert_flow(config: &Config, flow: &Flow) -> Result<()> {- let graph_json = serde_json::to_string(&flow.graph).context("Failed to serialize graph")?;- with_connection(config, |conn| {- conn.execute(- "INSERT INTO flow_definitions- (id, name, graph_json, enabled, created_at, updated_at, last_run_at, last_status, require_approval)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)- ON CONFLICT(id) DO UPDATE SET- name = excluded.name,- graph_json = excluded.graph_json,- enabled = excluded.enabled,- updated_at = excluded.updated_at,- last_run_at = excluded.last_run_at,- last_status = excluded.last_status,- require_approval = excluded.require_approval",- params![- flow.id,- flow.name,- graph_json,- if flow.enabled { 1 } else { 0 },- flow.created_at,- flow.updated_at,- flow.last_run_at,- flow.last_status,- if flow.require_approval { 1 } else { 0 },- ],- )- .context("Failed to upsert flow definition")?;- tracing::debug!(flow_id = %flow.id, "[flows] upserted flow definition");- Ok(())- })-}--/// Duplicates an existing [`Flow`] into a fresh row: same graph +-/// `require_approval`, a new id/timestamps, the given `new_name`, and-/// **`enabled = false`** so the copy never auto-fires (no schedule/app_event-/// trigger is bound while disabled — the caller relies on this to keep a-/// duplicate inert until explicitly enabled). `last_run_at`/`last_status` are-/// reset to `None` — run history does not carry over. Returns the persisted-/// copy.-pub fn insert_duplicate_flow(config: &Config, source: &Flow, new_name: String) -> Result<Flow> {- let now = Utc::now().to_rfc3339();- let flow = Flow {- id: Uuid::new_v4().to_string(),- name: new_name,- enabled: false,- graph: source.graph.clone(),- created_at: now.clone(),- updated_at: now,- last_run_at: None,- last_status: None,- require_approval: source.require_approval,- };- upsert_flow(config, &flow)?;- tracing::debug!(target: "flows", source_id = %source.id, new_id = %flow.id, "[flows] inserted duplicate flow (disabled)");- Ok(flow)-}--/// Creates a brand-new [`Flow`] row from a name + validated graph, stamping-/// fresh id/timestamps, and returns the persisted record.-///-/// `enabled` is decided by the caller ([`crate::openhuman::flows::ops::flows_create`],-/// issue B29 — save/enable safety): a graph with an automatic trigger-/// (`schedule` / `app_event` / `webhook`) is created disabled so it cannot-/// silently arm itself live and unattended; a `manual`-triggered graph is-/// created enabled since it only ever runs on explicit `flows_run`.-pub fn create_flow(- config: &Config,- name: String,- graph: tinyflows::model::WorkflowGraph,- require_approval: bool,- enabled: bool,-) -> Result<Flow> {- let now = Utc::now().to_rfc3339();- let flow = Flow {- id: Uuid::new_v4().to_string(),- name,- enabled,- graph,- created_at: now.clone(),- updated_at: now,- last_run_at: None,- last_status: None,- require_approval,- };- upsert_flow(config, &flow)?;- Ok(flow)-}--/// Loads one flow by id, running its stored `graph_json` through-/// `tinyflows::migrate::migrate` before deserializing so a graph persisted-/// under an older `schema_version` is upgraded on read.-pub fn get_flow(config: &Config, id: &str) -> Result<Option<Flow>> {- with_connection(config, |conn| {- let mut stmt = conn.prepare(&format!(- "SELECT {FLOW_DEFINITION_COLUMNS} FROM flow_definitions WHERE id = ?1"- ))?;- let mut rows = stmt.query(params![id])?;- match rows.next()? {- Some(row) => Ok(Some(map_flow_row(row)?)),- None => Ok(None),- }- })-}--/// Runs a `flow_definitions` SELECT and splits its rows into successfully-/// decoded [`Flow`]s and a count of rows that failed to parse/migrate-/// (R-M4).-///-/// **Skip-and-log, not fail-the-whole-query.** Before this, `list_flows` /-/// `list_enabled_flows` did `flows.push(row?)`, so a single corrupt or-/// newer-schema-than-this-build `graph_json` (e.g. a user downgrades after-/// running a newer build that persisted a graph `tinyflows::migrate::migrate`-/// cannot step backward) hard-failed the *entire* query — bricking every-/// `flows_list`, every `app_event` trigger dispatch (which is driven by-/// `list_enabled_flows`, see `bus.rs::handle_app_event`), and the boot-/// `reconcile_schedule_triggers_on_boot` sweep, all because of one bad row.-/// Mirrors the posture `draft_store::list_drafts` already uses. The returned-/// skip count is **not** swallowed here — it is the caller's job to log/-/// surface it loudly (a silently short flow list is its own failure mode) —-/// but this function itself does log each skip at `warn` with the row's `id`-/// and the parse/migrate error, never the `graph_json` payload.-fn list_flow_rows(conn: &Connection, where_clause: &str) -> Result<(Vec<Flow>, usize)> {- let mut stmt = conn.prepare(&format!(- "SELECT {FLOW_DEFINITION_COLUMNS} FROM flow_definitions {where_clause} \- ORDER BY created_at ASC"- ))?;- let mut rows = stmt.query([])?;- let mut flows = Vec::new();- let mut skipped = 0usize;- while let Some(row) = rows.next()? {- match map_flow_row(row) {- Ok(flow) => flows.push(flow),- Err(e) => {- skipped += 1;- let id: String = row.get(0).unwrap_or_else(|_| "<unknown>".to_string());- tracing::warn!(- target: "flows",- flow_id = %id,- error = %e,- "[flows] skipping corrupt or unmigratable flow_definitions row \- (graph_json failed to parse/migrate)"- );- }- }- }- Ok((flows, skipped))-}--/// Lists all saved flows, migrating each graph on read (see [`get_flow`]).-///-/// Returns `(flows, skipped)` — `skipped` is the number of rows that could-/// not be decoded and were left out of `flows` (R-M4). Callers must not treat-/// a non-zero `skipped` as a reason to fail; they must surface it loudly-/// instead (see [`list_flow_rows`]).-pub fn list_flows(config: &Config) -> Result<(Vec<Flow>, usize)> {- with_connection(config, |conn| list_flow_rows(conn, ""))-}--/// Lists only enabled flows, migrating each graph on read (see [`get_flow`]).-///-/// Used by `flows::bus::FlowTriggerSubscriber` to match an inbound-/// `ComposioTriggerReceived` event against every enabled `app_event` flow —-/// scanning the (small) enabled set once per event is simpler and cheap-/// enough at expected flow counts; a dedicated toolkit/trigger_slug index is-/// a later optimization if this ever shows up as a bottleneck.-///-/// Returns `(flows, skipped)` — see [`list_flows`]. A corrupt row here must-/// not take down `app_event` dispatch for every *other* enabled flow (R-M4).-pub fn list_enabled_flows(config: &Config) -> Result<(Vec<Flow>, usize)> {- with_connection(config, |conn| list_flow_rows(conn, "WHERE enabled = 1"))-}--/// Deletes a flow by id. Returns an error if no such flow exists.-pub fn remove_flow(config: &Config, id: &str) -> Result<()> {- let changed = with_connection(config, |conn| {- conn.execute("DELETE FROM flow_definitions WHERE id = ?1", params![id])- .context("Failed to delete flow definition")- })?;- if changed == 0 {- anyhow::bail!("flow '{id}' not found");- }- tracing::debug!(flow_id = %id, "[flows] removed flow definition");- Ok(())-}--/// Toggles a flow's `enabled` flag, returning the updated record.-pub fn set_enabled(config: &Config, id: &str, enabled: bool) -> Result<Flow> {- let now = Utc::now().to_rfc3339();- let changed = with_connection(config, |conn| {- conn.execute(- "UPDATE flow_definitions SET enabled = ?1, updated_at = ?2 WHERE id = ?3",- params![if enabled { 1 } else { 0 }, now, id],- )- .context("Failed to update flow enabled state")- })?;- if changed == 0 {- anyhow::bail!("flow '{id}' not found");- }- tracing::debug!(flow_id = %id, enabled, "[flows] set_enabled");- get_flow(config, id)?.ok_or_else(|| anyhow::anyhow!("flow '{id}' not found after update"))-}--/// How many revision snapshots to retain per flow (audit F6). Older ones are-/// pruned on each new capture.-const MAX_REVISIONS_PER_FLOW: usize = 20;--/// Failure modes of [`update_flow_graph`] that the caller must distinguish:-/// a genuine not-found, an optimistic-concurrency conflict (carrying the-/// current server flow so the UI can diff/reload), or a store error.-#[derive(Debug)]-pub enum FlowUpdateError {- /// No flow with that id exists.- NotFound,- /// The flow changed since `expected_updated_at` was observed — the write- /// was refused to avoid clobbering. Carries the current server flow.- Conflict(Box<Flow>),- /// An underlying store failure.- Store(anyhow::Error),-}--impl std::fmt::Display for FlowUpdateError {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- Self::NotFound => write!(f, "flow not found"),- Self::Conflict(_) => write!(f, "flow changed since it was loaded"),- Self::Store(e) => write!(f, "{e}"),- }- }-}--/// Replaces a flow's name/graph/`require_approval` (re-validated by the caller-/// before this is invoked) in place, bumping `updated_at`, capturing the prior-/// graph as a revision, and enforcing optimistic concurrency.-///-/// When `expected_updated_at` is `Some`, the write is refused with-/// [`FlowUpdateError::Conflict`] (carrying the current server flow) if the-/// flow's `updated_at` no longer matches — so an agent save and a concurrent-/// canvas save can't silently clobber each other. `None` keeps the prior-/// last-write-wins behaviour for callers that don't track a version.-///-/// `enabled_override`, when `Some`, forces the persisted `enabled` flag to-/// that value in the *same* guarded `UPDATE` as the graph/name/-/// `require_approval` write. `None` leaves `enabled` untouched (falls back to-/// the freshly re-read `current.enabled`), matching the previous behaviour-/// for every other caller.-///-/// `force_disarm_if_automatic`, when `true`, unconditionally disarms-/// (`enabled: false`) if the resulting graph (`graph`) has an automatic-/// trigger — used by `ops::flows_update_disarming_automatic` for remote-/// authoring surfaces.-///-/// **R-m2:** independent of `force_disarm_if_automatic`, this ALWAYS disarms-/// on a manual/none → automatic trigger transition (the B29 Rule 1 analogue)-/// — computed here, against the row this call just re-read-/// (`current.graph`), rather than trusting a transition flag the caller-/// derived from an earlier, possibly-stale read. `update_flow_graph`'s own-/// guarded `UPDATE` below keys its `WHERE` clause on this exact `current`-/// row, so this is the only read of "was it automatic before" that can't-/// have gone stale between computing the decision and writing it. An-/// `enabled_override` supplied by the caller can never re-arm a graph this-/// check disarms — the disarm always wins.-pub fn update_flow_graph(- config: &Config,- id: &str,- name: String,- graph: tinyflows::model::WorkflowGraph,- require_approval: bool,- enabled_override: Option<bool>,- force_disarm_if_automatic: bool,- expected_updated_at: Option<&str>,-) -> std::result::Result<Flow, FlowUpdateError> {- let current = get_flow(config, id)- .map_err(FlowUpdateError::Store)?- .ok_or(FlowUpdateError::NotFound)?;-- // Optimistic-concurrency check: refuse if the flow moved on since the- // caller observed `expected_updated_at`.- if let Some(expected) = expected_updated_at {- if current.updated_at != expected {- return Err(FlowUpdateError::Conflict(Box::new(current)));- }- }-- // R-m2: `was_auto` MUST come from `current` (just re-read above, right- // before the guarded UPDATE below), never from a caller-observed- // snapshot — a concurrent write between an ops-level read and this call- // would otherwise let a manual→automatic transition slip past- // undetected and persist `enabled: true` on an automatic-trigger graph.- let now_auto = super::ops::trigger_is_automatic(&graph);- let was_auto = super::ops::trigger_is_automatic(¤t.graph);- let is_manual_to_auto_transition = now_auto && !was_auto;- let forced_automatic_disarm = force_disarm_if_automatic && now_auto;- let auto_disarm = is_manual_to_auto_transition || forced_automatic_disarm;- if auto_disarm {- tracing::debug!(- target: "flows",- flow_id = %id,- was_auto,- now_auto,- is_manual_to_auto_transition,- forced_automatic_disarm,- "[flows] update_flow_graph: disarming — automatic-trigger transition detected \- against the freshly re-read row (R-m2)"- );- }-- let graph_json = serde_json::to_string(&graph)- .context("Failed to serialize graph")- .map_err(FlowUpdateError::Store)?;- let prior_graph_json =- serde_json::to_string(¤t.graph).unwrap_or_else(|_| "null".to_string());- let now = Utc::now().to_rfc3339();- let new_enabled = if auto_disarm {- false- } else {- enabled_override.unwrap_or(current.enabled)- };-- with_connection(config, |conn| {- // Guarded UPDATE keyed on the observed updated_at (race-safe even- // without an explicit expected version) — a concurrent writer that- // moved updated_at makes this match 0 rows. Targeted columns only, so a- // concurrent set_enabled/record_run isn't clobbered (unless this call- // itself carries an `enabled_override`, in which case `enabled` is- // one of the targeted columns by design).- let changed = conn- .execute(- "UPDATE flow_definitions SET name = ?1, graph_json = ?2, updated_at = ?3, \- require_approval = ?4, enabled = ?5 WHERE id = ?6 AND updated_at = ?7",- params![- name,- graph_json,- now,- if require_approval { 1 } else { 0 },- if new_enabled { 1 } else { 0 },- id,- current.updated_at,- ],- )- .context("Failed to update flow")?;- if changed == 0 {- // Someone raced us between the read and the write.- anyhow::bail!("__conflict__");- }- // Capture the prior graph as a revision, then prune to the cap.- let rev_id = Uuid::new_v4().to_string();- conn.execute(- "INSERT INTO flow_revisions (id, flow_id, graph_json, name, require_approval, \- created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",- params![- rev_id,- id,- prior_graph_json,- current.name,- if current.require_approval { 1 } else { 0 },- now,- ],- )- .context("Failed to record flow revision")?;- conn.execute(- "DELETE FROM flow_revisions WHERE flow_id = ?1 AND id NOT IN (\- SELECT id FROM flow_revisions WHERE flow_id = ?1 \- ORDER BY created_at DESC, id DESC LIMIT ?2)",- params![id, MAX_REVISIONS_PER_FLOW as i64],- )- .context("Failed to prune flow revisions")?;- Ok(())- })- .map_err(|e| {- if e.to_string().contains("__conflict__") {- // Re-read to hand back the current state.- match get_flow(config, id) {- Ok(Some(f)) => FlowUpdateError::Conflict(Box::new(f)),- Ok(None) => FlowUpdateError::NotFound,- Err(e) => FlowUpdateError::Store(e),- }- } else {- FlowUpdateError::Store(e)- }- })?;-- get_flow(config, id)- .map_err(FlowUpdateError::Store)?- .ok_or(FlowUpdateError::NotFound)-}--/// Lists a flow's revision snapshots, newest first, up to `limit`.-pub fn list_revisions(config: &Config, flow_id: &str, limit: usize) -> Result<Vec<FlowRevision>> {- with_connection(config, |conn| {- let mut stmt = conn.prepare(- "SELECT id, flow_id, graph_json, name, require_approval, created_at \- FROM flow_revisions WHERE flow_id = ?1 ORDER BY created_at DESC, id DESC LIMIT ?2",- )?;- let rows = stmt- .query_map(params![flow_id, limit as i64], map_revision_row)?- .collect::<rusqlite::Result<Vec<_>>>()?;- Ok(rows)- })-}--/// Fetches one revision by id (scoped to `flow_id`), or `None`.-pub fn revision_by_id(- config: &Config,- flow_id: &str,- revision_id: &str,-) -> Result<Option<FlowRevision>> {- with_connection(config, |conn| {- let mut stmt = conn.prepare(- "SELECT id, flow_id, graph_json, name, require_approval, created_at \- FROM flow_revisions WHERE flow_id = ?1 AND id = ?2",- )?;- let mut rows = stmt.query_map(params![flow_id, revision_id], map_revision_row)?;- match rows.next() {- Some(row) => Ok(Some(row?)),- None => Ok(None),- }- })-}--fn map_revision_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<FlowRevision> {- let graph_str: String = row.get(2)?;- let graph: serde_json::Value =- serde_json::from_str(&graph_str).unwrap_or(serde_json::Value::Null);- Ok(FlowRevision {- id: row.get(0)?,- flow_id: row.get(1)?,- graph,- name: row.get(3)?,- require_approval: row.get::<_, i64>(4)? != 0,- created_at: row.get(5)?,- })-}--/// Records the outcome of a `flows_run` invocation onto the flow's summary-/// fields (`last_run_at` / `last_status`).-pub fn record_run(config: &Config, id: &str, status: &str) -> Result<()> {- let now = Utc::now().to_rfc3339();- let changed = with_connection(config, |conn| {- conn.execute(- "UPDATE flow_definitions SET last_run_at = ?1, last_status = ?2 WHERE id = ?3",- params![now, status, id],- )- .context("Failed to record flow run")- })?;- if changed == 0 {- anyhow::bail!("flow '{id}' not found");- }- tracing::debug!(flow_id = %id, status, "[flows] recorded run");- Ok(())-}--fn map_flow_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Flow> {- let graph_raw: String = row.get(2)?;- let raw_value: serde_json::Value =- serde_json::from_str(&graph_raw).map_err(sql_conversion_error)?;- let migrated = tinyflows::migrate::migrate(raw_value).map_err(sql_conversion_error)?;- let graph: tinyflows::model::WorkflowGraph =- serde_json::from_value(migrated).map_err(sql_conversion_error)?;-- Ok(Flow {- id: row.get(0)?,- name: row.get(1)?,- graph,- enabled: row.get::<_, i64>(3)? != 0,- created_at: row.get(4)?,- updated_at: row.get(5)?,- last_run_at: row.get(6)?,- last_status: row.get(7)?,- require_approval: row.get::<_, i64>(8)? != 0,- })-}--fn sql_conversion_error<E: std::error::Error + Send + Sync + 'static>(err: E) -> rusqlite::Error {- rusqlite::Error::ToSqlConversionFailure(Box::new(err))-}--/// Loads a value from the `flow_state` KV table, scoped to `namespace`.-///-/// Backs `tinyflows::caps::StateStore::load` via-/// `src/openhuman/flows/tinyflows/caps.rs::FlowStateStore`.-pub fn kv_get(config: &Config, namespace: &str, key: &str) -> Result<Option<serde_json::Value>> {- with_connection(config, |conn| {- let mut stmt =- conn.prepare("SELECT value FROM flow_state WHERE namespace = ?1 AND key = ?2")?;- let mut rows = stmt.query(params![namespace, key])?;- match rows.next()? {- Some(row) => {- let raw: String = row.get(0)?;- let value: serde_json::Value =- serde_json::from_str(&raw).map_err(sql_conversion_error)?;- Ok(Some(value))- }- None => Ok(None),- }- })-}--/// Stores a value into the `flow_state` KV table, scoped to `namespace`.-///-/// Backs `tinyflows::caps::StateStore::store` via-/// `src/openhuman/flows/tinyflows/caps.rs::FlowStateStore`.-pub fn kv_set(- config: &Config,- namespace: &str,- key: &str,- value: &serde_json::Value,-) -> Result<()> {- let raw = serde_json::to_string(value).context("Failed to serialize flow state value")?;- with_connection(config, |conn| {- conn.execute(- "INSERT INTO flow_state (namespace, key, value) VALUES (?1, ?2, ?3)- ON CONFLICT(namespace, key) DO UPDATE SET value = excluded.value",- params![namespace, key, raw],- )- .context("Failed to store flow state value")?;- Ok(())- })-}--/// Deletes one key from the `flow_state` KV table, scoped to `namespace`.-/// A no-op (not an error) when the key doesn't exist.-///-/// Used by `flows::bus::DedupCommitSubscriber` (issue #5263 PR2) to clear a-/// `dedup` node's `tentative` key set once a run's outcome has been settled —-/// preferred over `kv_set(.., json!([]))` because an absent key reads back as-/// `None` (an unambiguous "nothing pending"), matching what a fresh flow that-/// never ran a dedup node also reads back as.-pub fn kv_delete(config: &Config, namespace: &str, key: &str) -> Result<()> {- with_connection(config, |conn| {- conn.execute(- "DELETE FROM flow_state WHERE namespace = ?1 AND key = ?2",- params![namespace, key],- )- .context("Failed to delete flow state value")?;- Ok(())- })-}--/// Shared column list for every `flow_runs` SELECT — keeps-/// [`map_flow_run_row`]'s positional `row.get(N)` calls in sync.-const FLOW_RUN_COLUMNS: &str = "id, flow_id, thread_id, status, started_at, finished_at, \- steps_json, pending_approvals_json, error, graph_hash";--/// Default per-flow run-history retention cap: how many of the most-recent runs-/// a single flow keeps before older *terminal* runs are pruned on the next-/// insert (and by the manual `flows_prune_runs` sweep). Bounds unbounded-/// `flow_runs` growth for a hot, frequently-triggered flow while keeping enough-/// history for the run-history inspector.-///-/// Non-terminal runs (`running`, `pending_approval`) are **never** pruned — a-/// parked `pending_approval` run must survive so a later `flows_resume` can find-/// it — so the effective row count for a flow may briefly exceed this cap by the-/// number of live/parked runs. See [`prune_flow_runs`].-pub const MAX_FLOW_RUNS_PER_FLOW: usize = 100;--/// Inserts the initial `"running"` row for a new `flows_run` / `flows_resume`-/// invocation. `id` and `thread_id` are the same value in practice (the-/// tinyflows checkpointer thread id doubles as the run's stable identifier),-/// kept as two columns because they answer two different questions (row-/// identity vs. the checkpointer key `flows_resume` needs).-pub fn insert_flow_run(- config: &Config,- id: &str,- flow_id: &str,- thread_id: &str,- started_at: &str,-) -> Result<()> {- with_connection(config, |conn| {- conn.execute(- "INSERT INTO flow_runs (id, flow_id, thread_id, status, started_at)- VALUES (?1, ?2, ?3, 'running', ?4)",- params![id, flow_id, thread_id, started_at],- )- .context("Failed to insert flow run")?;- // Retention: prune older terminal runs for this flow on every new-run- // insert, so `flow_runs` stays bounded for a hot flow. Same connection- // as the insert — atomic w.r.t. this write. A pruning failure is not- // fatal to the insert (the run itself matters more than trimming- // history), so it's logged and swallowed.- if let Err(e) = prune_flow_runs_conn(conn, flow_id, MAX_FLOW_RUNS_PER_FLOW) {- tracing::warn!(target: "flows", flow_id, error = %e, "[flows] insert_flow_run: retention prune failed (insert kept)");- }- Ok(())- })-}--/// Prunes a flow's run history down to at most `keep` of its most-recent runs,-/// deleting any row outside the newest-`keep` window whose `status` is NOT-/// `running` or `pending_approval` — that is every terminal status this store-/// can hold (`completed`, `completed_with_warnings`, `failed`, `cancelled`,-/// `interrupted`, and any future status this host doesn't recognize yet), not-/// just the `completed`/`failed`/`cancelled` trio. The two excluded statuses-/// are the only ones that are never deleted — a parked `pending_approval` run-/// must never be pruned out from under a pending `flows_resume`, and a-/// `running` row belongs to a live task. Returns the number of rows deleted.-///-/// `keep` is clamped to at least 1. Exposed for the manual `flows_prune_runs`-/// sweep; the new-run insert path calls the connection-scoped helper directly.-pub fn prune_flow_runs(config: &Config, flow_id: &str, keep: usize) -> Result<usize> {- with_connection(config, |conn| prune_flow_runs_conn(conn, flow_id, keep))-}--/// Connection-scoped core of [`prune_flow_runs`] — see its doc. Kept separate so-/// the new-run insert path can prune inside its own `with_connection` block-/// without reopening the database.-fn prune_flow_runs_conn(conn: &Connection, flow_id: &str, keep: usize) -> Result<usize> {- let keep = i64::try_from(keep.max(1)).context("Run retention cap overflow")?;- let deleted = conn- .execute(- "DELETE FROM flow_runs- WHERE flow_id = ?1- AND status NOT IN ('running', 'pending_approval')- AND id NOT IN (- SELECT id FROM flow_runs- WHERE flow_id = ?1- ORDER BY started_at DESC, id DESC- LIMIT ?2- )",- params![flow_id, keep],- )- .context("Failed to prune flow runs")?;- if deleted > 0 {- tracing::debug!(target: "flows", flow_id, deleted, keep, "[flows] pruned old terminal flow runs past retention cap");- }- Ok(deleted)-}--/// Finalizes a flow run row: settles its terminal `status`, `finished_at`,-/// reconstructed `steps`, `pending_approvals`, and (on failure) `error`.-/// Called once a `flows_run` / `flows_resume` invocation settles — including-/// the timeout / capability-error paths, so a row never gets stuck at-/// `"running"` when the process is still up.-///-/// **Guarded write (R-M2).** The `UPDATE` only matches a row that is still-/// live — `status IN ('running','pending_approval')` — mirroring the same-/// re-check [`expire_parked_runs`] and [`mark_run_interrupted`] already do.-/// Without it this was an unconditional `WHERE id = ?`, so a caller that read a-/// non-terminal status and then lost a race could overwrite a row that had-/// meanwhile settled: `flows_cancel_run` reads `running`, the live run finishes-/// `completed` and deregisters, `run_registry::cancel` returns `false`, and the-/// "not in flight" branch then relabels a fully-completed run (whose real side-/// effects fired) as `cancelled`. Returns whether a row was actually updated so-/// callers can log the no-op instead of silently believing the write landed.-///-/// `graph_hash` (T-M1) is `Some(hash)` only when this write is the one that-/// *parks* the row (`status == "pending_approval"`) — it pins the content hash-/// of the graph the checkpoint was taken against, so a later `flows_resume`-/// can refuse if `save_workflow` rewrote the flow in the meantime. Every other-/// write passes `None`, which clears any stale pin once the row leaves-/// `pending_approval` (a settled row has no further use for it).-pub fn finish_flow_run(- config: &Config,- id: &str,- status: &str,- finished_at: &str,- steps: &[FlowRunStep],- pending_approvals: &[String],- error: Option<&str>,- graph_hash: Option<&str>,-) -> Result<bool> {- let steps_json = serde_json::to_string(steps).context("Failed to serialize flow run steps")?;- let pending_json = serde_json::to_string(pending_approvals)- .context("Failed to serialize flow run pending approvals")?;- with_connection(config, |conn| {- let updated = conn- .execute(- "UPDATE flow_runs SET status = ?1, finished_at = ?2, steps_json = ?3, \- pending_approvals_json = ?4, error = ?5, graph_hash = ?6 \- WHERE id = ?7 AND status IN ('running', 'pending_approval')",- params![- status,- finished_at,- steps_json,- pending_json,- error,- graph_hash,- id- ],- )- .context("Failed to finish flow run")?;- Ok(updated > 0)- })-}--/// Incrementally upserts a single [`FlowRunStep`] onto a live `flow_runs`-/// row's `steps_json`, keyed by `node_id` — used by the run observer-/// (`flows::observability::FlowRunObserver`) to persist each node's step **as-/// it finishes** (issue G2, live run observation) rather than only rebuilding-/// the whole step list at settle.-///-/// **`BEGIN IMMEDIATE`-guarded read-modify-write (R-m1).** Each call opens its-/// own connection (see `with_connection`), so without an explicit transaction-/// two observer callbacks firing for parallel branch nodes of the *same* run-/// can interleave: both read `steps_json = [A]`, one writes `[A,B]`, the other-/// writes `[A,C]` — B is silently lost from the live view, and lost for good,-/// since the post-hoc `settle_steps` reconstruction only refills a missing-/// node with `status: None` rather than recovering the real outcome/duration.-/// `BEGIN IMMEDIATE` takes SQLite's write lock up front (rather than only at-/// the final `UPDATE`, which is what a plain autocommit read-then-write would-/// do), so a concurrent upsert either waits (covered by this store's-/// `busy_timeout = 5000` connection pragma — see `with_connection`) or is-/// serialized behind it; there is no window in which both readers can observe-/// the same pre-write `steps_json`. Kept deliberately minimal (one SELECT, one-/// UPDATE) to bound how long the write lock is held.-///-/// A re-run of the same `node_id` (a retry, or a resumed run re-touching a-/// node) replaces its prior entry rather than duplicating it, so the-/// persisted list stays one entry per node. No-op if the run's start row-/// hasn't been inserted yet (nothing to update) — mirrors the best-effort-/// contract of the run-row writers in `flows::ops`.-pub fn upsert_flow_run_step(config: &Config, run_id: &str, step: &FlowRunStep) -> Result<()> {- use rusqlite::OptionalExtension;- with_connection(config, |conn| {- with_immediate_transaction(conn, |conn| {- let existing: Option<String> = conn- .query_row(- "SELECT steps_json FROM flow_runs WHERE id = ?1",- params![run_id],- |row| row.get(0),- )- .optional()- .context("Failed to read flow run steps for incremental upsert")?;- let Some(raw) = existing else {- tracing::debug!(target: "flows", run_id, node = %step.node_id, "[flows] upsert_flow_run_step: no run row yet — skipping incremental step persist");- return Ok(());- };- let mut steps: Vec<FlowRunStep> = serde_json::from_str(&raw)- .context("Failed to deserialize existing flow run steps")?;- match steps.iter_mut().find(|s| s.node_id == step.node_id) {- Some(slot) => *slot = step.clone(),- None => steps.push(step.clone()),- }- let steps_json =- serde_json::to_string(&steps).context("Failed to serialize flow run steps")?;- conn.execute(- "UPDATE flow_runs SET steps_json = ?1 WHERE id = ?2",- params![steps_json, run_id],- )- .context("Failed to persist incremental flow run step")?;- tracing::debug!(target: "flows", run_id, node = %step.node_id, step_count = steps.len(), "[flows] persisted incremental flow run step");- Ok(())- })- })-}--/// Runs `f` inside a `BEGIN IMMEDIATE` / `COMMIT` transaction on `conn`,-/// rolling back on error. `BEGIN IMMEDIATE` (rather than the default deferred-/// `BEGIN`) acquires SQLite's write lock immediately instead of only at the-/// first write statement, which is what closes the read-then-write race-/// [`upsert_flow_run_step`] needs closed (R-m1). Issued as raw SQL via-/// `execute_batch` rather than `rusqlite::Connection::transaction` (which-/// needs `&mut Connection`) so this can compose with `with_connection`'s-/// `&Connection` closure signature used by every other store function.-fn with_immediate_transaction<T>(- conn: &Connection,- f: impl FnOnce(&Connection) -> Result<T>,-) -> Result<T> {- conn.execute_batch("BEGIN IMMEDIATE")- .context("Failed to begin immediate transaction")?;- match f(conn) {- Ok(value) => {- conn.execute_batch("COMMIT")- .context("Failed to commit transaction")?;- Ok(value)- }- Err(e) => {- if let Err(rollback_err) = conn.execute_batch("ROLLBACK") {- tracing::warn!(target: "flows", error = %rollback_err, "[flows] failed to roll back transaction after error");- }- Err(e)- }- }-}--/// Expires every parked `pending_approval` run whose "parked since" timestamp-/// (`COALESCE(finished_at, started_at)` — a run's `finished_at` is stamped when-/// it pauses at a gate) is strictly older than `cutoff` (an RFC3339 instant),-/// transitioning it to a terminal `"cancelled"` status stamped `now` with-/// `error_msg`. Returns the `(run_id, flow_id)` of the runs **actually flipped**-/// so the caller can update the flow summary, publish `FlowRunFinished`, and-/// drop the durable checkpoint (issue G4 — parked-run TTL) for real settles-/// only.-///-/// **Candidates are not sweeps.** The `SELECT` and each row's guarded `UPDATE`-/// are separate statements on an autocommit connection (`with_connection` opens-/// a fresh connection per call, not a transaction spanning this function), so a-/// concurrent `mark_run_resuming` on another connection can land in between: the-/// row was `pending_approval` at `SELECT` time and no longer is when its own-/// `UPDATE` runs. The per-row `WHERE status = 'pending_approval'` re-check keeps-/// that row's data safe — but returning the unfiltered candidate list would let-/// the caller act on a run it never actually expired: dropping the checkpoint out-/// from under a resume that just claimed it, and publishing a terminal-/// `FlowRunFinished` for a run still executing. That false event is the worse-/// half, because the frontend de-dupes terminal events by `${flow_id}:${run_id}`-/// — so the run's real completion would later be discarded as an alias replay,-/// leaving a successful run displayed as cancelled. Only rows whose `UPDATE`-/// reports `changed > 0` are returned.-///-/// RFC3339 timestamps produced by `chrono::Utc::…to_rfc3339()` all carry the-/// same `+00:00` offset, so a lexicographic `<` is a valid chronological-/// comparison here. Best-effort by contract at the call site: the update runs-/// under the same WAL + `busy_timeout` connection as every other write.-pub fn expire_parked_runs(- config: &Config,- cutoff: &str,- now: &str,- error_msg: &str,-) -> Result<Vec<(String, String)>> {- with_connection(config, |conn| {- let mut stmt = conn.prepare(- "SELECT id, flow_id FROM flow_runs- WHERE status = 'pending_approval'- AND COALESCE(finished_at, started_at) < ?1",- )?;- let stale: Vec<(String, String)> = stmt- .query_map(params![cutoff], |row| Ok((row.get(0)?, row.get(1)?)))?- .collect::<rusqlite::Result<_>>()?;- drop(stmt);-- let mut swept = Vec::with_capacity(stale.len());- for (run_id, flow_id) in stale {- // Re-check the status in the WHERE so a run resumed/cancelled- // between the SELECT and here is not clobbered, and keep only the- // rows this sweep genuinely flipped — see the fn doc.- let changed = conn- .execute(- "UPDATE flow_runs SET status = 'cancelled', finished_at = ?1, error = ?2 \- WHERE id = ?3 AND status = 'pending_approval'",- params![now, error_msg, &run_id],- )- .context("Failed to expire parked flow run")?;- if changed > 0 {- swept.push((run_id, flow_id));- } else {- tracing::debug!(- target: "flows",- run_id = %run_id,- "[flows] TTL sweep: run left 'pending_approval' concurrently — not expiring it"- );- }- }- if !swept.is_empty() {- tracing::info!(target: "flows", swept = swept.len(), "[flows] expired parked pending_approval runs past TTL");- }- Ok(swept)- })-}--/// Lists the `(id, flow_id)` of every run persisted at `status = 'running'`-/// whose `started_at` is strictly **before** `started_before` (RFC3339). Used by-/// the boot-time orphan sweep (bug B42): after a crash/restart no in-process-/// task is executing these rows, so-/// [`crate::openhuman::flows::ops::sweep_orphaned_running_runs_on_boot`]-/// reconciles each one that isn't backed by a live in-flight run to a terminal-/// `'interrupted'` via [`mark_run_interrupted`].-///-/// The `started_before` floor is what makes the sweep provably unable to touch-/// a run **this** process started: the sweep passes the instant this process-/// first entered the flow-run lifecycle, and every row this process inserts is-/// stamped at or after that instant. Without it, the sweep's only guard is the-/// in-flight registry, which a row briefly escapes between `start_flow_run_row`-/// and `run_registry::register`. `started_at` is a fixed-shape UTC RFC3339-/// string, so the lexicographic `<` matches chronological order (same-/// comparison the parked-run TTL sweep already relies on).-pub fn list_running_run_ids(- config: &Config,- started_before: &str,-) -> Result<Vec<(String, String)>> {- with_connection(config, |conn| {- let mut stmt = conn.prepare(- "SELECT id, flow_id FROM flow_runs WHERE status = 'running' AND started_at < ?1",- )?;- let rows: Vec<(String, String)> = stmt- .query_map(params![started_before], |row| {- Ok((row.get(0)?, row.get(1)?))- })?- .collect::<rusqlite::Result<_>>()?;- Ok(rows)- })-}--/// Test-only unconditional status write, bypassing the-/// [`finish_flow_run`] liveness guard.-///-/// Production code must never do a terminal → terminal transition — that is the-/// corruption [`finish_flow_run`]'s `status IN ('running','pending_approval')`-/// predicate exists to prevent. But a couple of tests legitimately need to-/// *stage* a row at an arbitrary terminal status (`completed_with_warnings`,-/// `interrupted`) to exercise the guards that read it, and they previously did-/// so by calling `finish_flow_run` twice — which the guard now correctly-/// refuses. Staging is a fixture concern, so it gets a fixture-only door rather-/// than a weaker production write.-#[cfg(test)]-pub fn force_run_status_for_test(- config: &Config,- id: &str,- status: &str,- error: Option<&str>,-) -> Result<()> {- with_connection(config, |conn| {- conn.execute(- "UPDATE flow_runs SET status = ?1, error = ?2 WHERE id = ?3",- params![status, error, id],- )- .context("Failed to force flow run status (test fixture)")?;- Ok(())- })-}--/// Test-only fixture door: overwrites an existing flow row's `graph_json`-/// with arbitrary text, bypassing the normal `Flow`/`WorkflowGraph`-typed-/// write path entirely. Used to stage the corrupt-or-newer-schema-row-/// scenario `list_flows` / `list_enabled_flows` / boot reconciliation must-/// survive (R-M4) — same "staging is a fixture concern, so it gets a-/// fixture-only door" rationale as [`force_run_status_for_test`]. Real-/// production writes can never produce a row `map_flow_row` can't decode-/// (every write path serializes a validated `WorkflowGraph`), so there is no-/// non-test way to reach this state other than a cross-version downgrade.-#[cfg(test)]-pub fn force_corrupt_graph_json_for_test(- config: &Config,- flow_id: &str,- raw_graph_json: &str,-) -> Result<()> {- with_connection(config, |conn| {- let changed = conn- .execute(- "UPDATE flow_definitions SET graph_json = ?1 WHERE id = ?2",- params![raw_graph_json, flow_id],- )- .context("Failed to force corrupt graph_json (test fixture)")?;- anyhow::ensure!(changed > 0, "flow '{flow_id}' not found (test fixture)");- Ok(())- })-}--/// Flips a parked `'pending_approval'` row to `'running'` for the duration of a-/// [`crate::openhuman::flows::ops::flows_resume`], guarded by a-/// `status = 'pending_approval'` predicate so a run cancelled or expired-/// concurrently is never revived. Returns `true` when a row was actually-/// flipped.-///-/// Without this flip the row stays `pending_approval` for the whole (up to-/// `FLOW_RUN_TIMEOUT_SECS`) resume, so-/// [`expire_parked_runs`]' TTL sweep still matches it: a run approved just-/// before its TTL would be relabelled `cancelled` and have its durable-/// checkpoint dropped **while the resume was actively executing approved-/// outbound nodes** (R-M1). Marking it `running` moves it out of the sweep's-/// predicate and into the same lifecycle state a `flows_run` occupies, which is-/// also what the boot orphan sweep already knows how to reconcile.-pub fn mark_run_resuming(config: &Config, id: &str) -> Result<bool> {- with_connection(config, |conn| {- let changed = conn- .execute(- "UPDATE flow_runs SET status = 'running', finished_at = NULL, error = NULL \- WHERE id = ?1 AND status = 'pending_approval'",- params![id],- )- .context("Failed to mark parked flow run as resuming")?;- if changed > 0 {- tracing::debug!(target: "flows", run_id = id, "[flows] marked parked run 'running' for the duration of the resume");- }- Ok(changed > 0)- })-}--/// Reconciles a single orphaned `'running'` run row to a terminal-/// `'interrupted'` status stamped `now` (RFC3339) with `reason`, guarded by a-/// `status = 'running'` predicate so a run that settled or was resumed-/// concurrently is never clobbered. Returns `true` when a row was actually-/// flipped (bug B42 — cancellation-safe finalizer + boot sweep). Best-effort by-/// contract at the call site.-pub fn mark_run_interrupted(config: &Config, id: &str, now: &str, reason: &str) -> Result<bool> {- with_connection(config, |conn| {- let changed = conn- .execute(- "UPDATE flow_runs SET status = 'interrupted', finished_at = ?1, error = ?2 \- WHERE id = ?3 AND status = 'running'",- params![now, reason, id],- )- .context("Failed to reconcile orphaned running flow run")?;- if changed > 0 {- tracing::info!(target: "flows", run_id = id, "[flows] reconciled orphaned 'running' flow run to 'interrupted'");- }- Ok(changed > 0)- })-}--/// Loads one flow run by id (== thread_id).-pub fn get_flow_run(config: &Config, id: &str) -> Result<Option<FlowRun>> {- with_connection(config, |conn| {- let mut stmt = conn.prepare(&format!(- "SELECT {FLOW_RUN_COLUMNS} FROM flow_runs WHERE id = ?1"- ))?;- let mut rows = stmt.query(params![id])?;- match rows.next()? {- Some(row) => Ok(Some(map_flow_run_row(row)?)),- None => Ok(None),- }- })-}--/// Lists the most recent runs for a flow, newest first.-pub fn list_flow_runs(config: &Config, flow_id: &str, limit: usize) -> Result<Vec<FlowRun>> {- with_connection(config, |conn| {- let lim = i64::try_from(limit.max(1)).context("Run history limit overflow")?;- let mut stmt = conn.prepare(&format!(- "SELECT {FLOW_RUN_COLUMNS} FROM flow_runs WHERE flow_id = ?1 \- ORDER BY started_at DESC, id DESC LIMIT ?2"- ))?;- let rows = stmt.query_map(params![flow_id, lim], map_flow_run_row)?;- let mut runs = Vec::new();- for row in rows {- runs.push(row?);- }- Ok(runs)- })-}--/// List the most recent runs across ALL flows, newest first (the "All runs"-/// page). Uses the `idx_flow_runs_started_at` index for the ordering. Each-/// [`FlowRun`] carries its own `flow_id`, so the UI can group/label by flow.-pub fn list_all_flow_runs(config: &Config, limit: usize) -> Result<Vec<FlowRun>> {- with_connection(config, |conn| {- let lim = i64::try_from(limit.max(1)).context("Run history limit overflow")?;- let mut stmt = conn.prepare(&format!(- "SELECT {FLOW_RUN_COLUMNS} FROM flow_runs \- ORDER BY started_at DESC, id DESC LIMIT ?1"- ))?;- let rows = stmt.query_map(params![lim], map_flow_run_row)?;- let mut runs = Vec::new();- for row in rows {- runs.push(row?);- }- Ok(runs)- })-}--fn map_flow_run_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<FlowRun> {- let steps_raw: String = row.get(6)?;- let steps: Vec<FlowRunStep> = serde_json::from_str(&steps_raw).map_err(sql_conversion_error)?;- let pending_raw: String = row.get(7)?;- let pending_approvals: Vec<String> =- serde_json::from_str(&pending_raw).map_err(sql_conversion_error)?;-- Ok(FlowRun {- id: row.get(0)?,- flow_id: row.get(1)?,- thread_id: row.get(2)?,- status: row.get(3)?,- started_at: row.get(4)?,- finished_at: row.get(5)?,- steps,- pending_approvals,- error: row.get(8)?,- graph_hash: row.get(9)?,- })-}--// ─────────────────────────────────────────────────────────────────────────────-// flow_suggestions — discovery-agent workflow suggestions (Flow Scout)-// ─────────────────────────────────────────────────────────────────────────────--/// Shared column list for every `flow_suggestions` SELECT — keeps-/// [`map_suggestion_row`]'s positional `row.get(N)` calls in sync with the query.-const FLOW_SUGGESTION_COLUMNS: &str = "id, title, one_liner, rationale, trigger_hint, steps_json, \- connections_json, slugs_json, build_prompt, confidence, status, created_at, source_run_id";--/// Inserts a batch of freshly discovered suggestions.-///-/// **Dedupe-preserving upsert.** Each suggestion's `id` is a stable content-/// hash (see `discovery_tools`), so a re-run that re-proposes an identical idea-/// hits `ON CONFLICT(id)` and refreshes the *pitch* fields — **without**-/// resetting a `status` the user already set. This is the invariant that keeps a-/// dismissed idea dismissed and a built idea built across repeated discovery-/// runs: the `status` and `created_at` columns are deliberately excluded from-/// the `DO UPDATE SET` list. Returns the number of rows written.-pub fn upsert_suggestions(config: &Config, suggestions: &[FlowSuggestion]) -> Result<usize> {- if suggestions.is_empty() {- return Ok(0);- }- with_connection(config, |conn| {- let mut written = 0usize;- for s in suggestions {- let steps_json = serde_json::to_string(&s.steps_outline)- .context("Failed to serialize suggestion steps")?;- let connections_json = serde_json::to_string(&s.suggested_connections)- .context("Failed to serialize suggestion connections")?;- let slugs_json = serde_json::to_string(&s.suggested_slugs)- .context("Failed to serialize suggestion slugs")?;- conn.execute(- "INSERT INTO flow_suggestions- (id, title, one_liner, rationale, trigger_hint, steps_json,- connections_json, slugs_json, build_prompt, confidence, status,- created_at, source_run_id)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)- ON CONFLICT(id) DO UPDATE SET- title = excluded.title,- one_liner = excluded.one_liner,- rationale = excluded.rationale,- trigger_hint = excluded.trigger_hint,- steps_json = excluded.steps_json,- connections_json = excluded.connections_json,- slugs_json = excluded.slugs_json,- build_prompt = excluded.build_prompt,- confidence = excluded.confidence,- source_run_id = excluded.source_run_id",- params![- s.id,- s.title,- s.one_liner,- s.rationale,- s.trigger_hint,- steps_json,- connections_json,- slugs_json,- s.build_prompt,- s.confidence,- s.status.as_str(),- s.created_at,- s.source_run_id,- ],- )- .context("Failed to upsert flow suggestion")?;- written += 1;- }- tracing::debug!(count = written, "[flows] upserted flow suggestions");- Ok(written)- })-}--/// Lists persisted suggestions, newest first, highest-confidence first within a-/// timestamp. When `status` is `Some`, only rows in that lifecycle state are-/// returned (the UI passes `New` to render the active "Suggested for you"-/// cards); `None` returns every status.-pub fn list_suggestions(- config: &Config,- status: Option<SuggestionStatus>,- limit: usize,-) -> Result<Vec<FlowSuggestion>> {- with_connection(config, |conn| {- let lim = i64::try_from(limit.max(1)).context("Suggestion limit overflow")?;- let mut out = Vec::new();- match status {- Some(st) => {- let mut stmt = conn.prepare(&format!(- "SELECT {FLOW_SUGGESTION_COLUMNS} FROM flow_suggestions WHERE status = ?1 \- ORDER BY created_at DESC, confidence DESC, id ASC LIMIT ?2"- ))?;- let rows = stmt.query_map(params![st.as_str(), lim], map_suggestion_row)?;- for row in rows {- out.push(row?);- }- }- None => {- let mut stmt = conn.prepare(&format!(- "SELECT {FLOW_SUGGESTION_COLUMNS} FROM flow_suggestions \- ORDER BY created_at DESC, confidence DESC, id ASC LIMIT ?1"- ))?;- let rows = stmt.query_map(params![lim], map_suggestion_row)?;- for row in rows {- out.push(row?);- }- }- }- Ok(out)- })-}--/// Updates one suggestion's lifecycle status (dismiss / mark built). Returns-/// `true` when a row matched, `false` when the id was unknown (already pruned).-pub fn set_suggestion_status(config: &Config, id: &str, status: SuggestionStatus) -> Result<bool> {- with_connection(config, |conn| {- let changed = conn- .execute(- "UPDATE flow_suggestions SET status = ?1 WHERE id = ?2",- params![status.as_str(), id],- )- .context("Failed to update flow suggestion status")?;- tracing::debug!(suggestion_id = %id, status = %status.as_str(), changed, "[flows] set suggestion status");- Ok(changed > 0)- })-}--fn map_suggestion_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<FlowSuggestion> {- let steps_raw: String = row.get(5)?;- let steps_outline: Vec<String> =- serde_json::from_str(&steps_raw).map_err(sql_conversion_error)?;- let connections_raw: String = row.get(6)?;- let suggested_connections: Vec<String> =- serde_json::from_str(&connections_raw).map_err(sql_conversion_error)?;- let slugs_raw: String = row.get(7)?;- let suggested_slugs: Vec<String> =- serde_json::from_str(&slugs_raw).map_err(sql_conversion_error)?;- let status_raw: String = row.get(10)?;-- Ok(FlowSuggestion {- id: row.get(0)?,- title: row.get(1)?,- one_liner: row.get(2)?,- rationale: row.get(3)?,- trigger_hint: row.get(4)?,- steps_outline,- suggested_connections,- suggested_slugs,- build_prompt: row.get(8)?,- confidence: row.get(9)?,- status: SuggestionStatus::from_str_lossy(&status_raw),- created_at: row.get(11)?,- source_run_id: row.get(12)?,- })-}--#[cfg(test)]-#[path = "store_tests.rs"]-mod tests;diff --git a/src/openhuman/flows/store_tests.rs b/src/openhuman/flows/store_tests.rsdeleted file mode 100644index 42e78dbb91..0000000000--- a/src/openhuman/flows/store_tests.rs+++ /dev/null@@ -1,1455 +0,0 @@-use super::*;-use crate::openhuman::config::Config;-use tempfile::TempDir;-use tinyflows::model::{Node, NodeKind, WorkflowGraph};--fn test_config(tmp: &TempDir) -> Config {- let config = Config {- workspace_dir: tmp.path().join("workspace"),- action_dir: tmp.path().join("workspace"),- config_path: tmp.path().join("config.toml"),- ..Config::default()- };- std::fs::create_dir_all(&config.workspace_dir).unwrap();- config-}--fn trigger_graph() -> WorkflowGraph {- WorkflowGraph {- nodes: vec![Node {- id: "t".to_string(),- kind: NodeKind::Trigger,- type_version: 1,- name: "Trigger".to_string(),- config: serde_json::Value::Null,- ports: Vec::new(),- position: None,- }],- ..Default::default()- }-}--/// An automatic-trigger (`schedule`) graph — `trigger_is_automatic` returns-/// `true` for this, unlike [`trigger_graph`]'s manual (no `trigger_kind`)-/// trigger.-fn automatic_schedule_graph() -> WorkflowGraph {- WorkflowGraph {- nodes: vec![Node {- id: "t".to_string(),- kind: NodeKind::Trigger,- type_version: 1,- name: "Trigger".to_string(),- config: serde_json::json!({ "trigger_kind": "schedule", "schedule": "0 9 * * *" }),- ports: Vec::new(),- position: None,- }],- ..Default::default()- }-}--#[test]-fn create_get_list_delete_roundtrip() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();- assert_eq!(flow.name, "demo");- assert!(flow.enabled);-- let fetched = get_flow(&config, &flow.id).unwrap().expect("flow present");- assert_eq!(fetched.id, flow.id);- assert_eq!(fetched.graph, flow.graph);-- let (listed, skipped) = list_flows(&config).unwrap();- assert_eq!(listed.len(), 1);- assert_eq!(listed[0].id, flow.id);- assert_eq!(skipped, 0);-- remove_flow(&config, &flow.id).unwrap();- assert!(get_flow(&config, &flow.id).unwrap().is_none());- assert!(list_flows(&config).unwrap().0.is_empty());-}--#[test]-fn get_flow_returns_none_for_unknown_id() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- assert!(get_flow(&config, "missing").unwrap().is_none());-}--#[test]-fn remove_flow_errors_when_not_found() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let err = remove_flow(&config, "missing").unwrap_err();- assert!(err.to_string().contains("not found"));-}--#[test]-fn set_enabled_toggles_and_persists() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();- assert!(flow.enabled);-- let disabled = set_enabled(&config, &flow.id, false).unwrap();- assert!(!disabled.enabled);-- let reloaded = get_flow(&config, &flow.id).unwrap().unwrap();- assert!(!reloaded.enabled);-- let enabled = set_enabled(&config, &flow.id, true).unwrap();- assert!(enabled.enabled);-}--#[test]-fn update_flow_graph_bumps_updated_at_and_preserves_created_at() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();-- let mut new_graph = trigger_graph();- new_graph.name = "renamed-graph".to_string();- let updated = update_flow_graph(- &config,- &flow.id,- "renamed".to_string(),- new_graph,- false,- None,- false,- None,- )- .unwrap();-- assert_eq!(updated.name, "renamed");- assert_eq!(updated.created_at, flow.created_at);- assert_eq!(updated.graph.name, "renamed-graph");-}--/// `enabled_override: None` must leave the persisted `enabled` column-/// exactly as it was — `update_flow_graph` re-reads the current row and-/// falls back to `current.enabled`, not to whatever the caller might have-/// observed earlier.-#[test]-fn update_flow_graph_with_none_override_preserves_current_enabled_column() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();- assert!(flow.enabled, "flow created enabled");-- let updated = update_flow_graph(- &config,- &flow.id,- flow.name.clone(),- trigger_graph(),- false,- None, // enabled_override- false, // force_disarm_if_automatic- None,- )- .unwrap();-- assert!(- updated.enabled,- "a None override must preserve the row's current enabled state"- );- let reloaded = get_flow(&config, &flow.id).unwrap().unwrap();- assert!(reloaded.enabled);-}--/// `enabled_override: Some(false)` must force-persist `enabled=false`-/// regardless of what the row's `enabled` column currently holds — this is-/// the mechanism `flows_update`'s B29 Rule 1 analogue relies on to disarm a-/// manual→automatic trigger transition in the same guarded write.-#[test]-fn update_flow_graph_with_some_false_override_forces_disabled() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();- assert!(flow.enabled, "flow created enabled");-- let updated = update_flow_graph(- &config,- &flow.id,- flow.name.clone(),- trigger_graph(),- false,- Some(false), // enabled_override- false, // force_disarm_if_automatic- None,- )- .unwrap();-- assert!(- !updated.enabled,- "a Some(false) override must force enabled=false even though the row was enabled"- );- let reloaded = get_flow(&config, &flow.id).unwrap().unwrap();- assert!(!reloaded.enabled);-}--/// Regression for the silent live-arming race Codex flagged on this PR:-/// `flows_update` (ops.rs) makes its manual→automatic disarm decision from-/// an *outer* `existing` read taken before `update_flow_graph`'s own guarded-/// UPDATE re-reads the row. If a concurrent `flows_set_enabled(id, true)`-/// landed in that gap — which bumps `updated_at`, so it would NOT trip the-/// optimistic-concurrency conflict — the outer read would be stale while the-/// row is actually enabled by write time. This proves the mechanism the fix-/// relies on to close that race: an `enabled_override` of `Some(false)`-/// (what `flows_update` now passes unconditionally on a manual→automatic-/// transition, never gated on the stale outer read) always wins over-/// whatever the row's `enabled` column was concurrently flipped to,-/// simulated here by flipping it with `set_enabled` between the two calls.-#[test]-fn update_flow_graph_override_wins_over_concurrently_enabled_row() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, false).unwrap();- assert!(!flow.enabled, "flow created disabled");-- // Simulates a concurrent `flows_set_enabled(id, true)` racing in after- // `flows_update`'s outer `existing` read observed `enabled: false`, but- // before its guarded `update_flow_graph` write below.- let raced = set_enabled(&config, &flow.id, true).unwrap();- assert!(raced.enabled);-- let updated = update_flow_graph(- &config,- &flow.id,- flow.name.clone(),- trigger_graph(),- false,- Some(false), // the unconditional disarm override- false, // force_disarm_if_automatic- None,- )- .unwrap();-- assert!(- !updated.enabled,- "the disarm override must win over a concurrently-enabled row, not the reverse"- );- let reloaded = get_flow(&config, &flow.id).unwrap().unwrap();- assert!(!reloaded.enabled);-}--/// R-m2 regression: the manual→automatic disarm decision must be computed-/// against the row `update_flow_graph` JUST re-read (`current`), never a-/// caller-supplied belief about the flow's prior state. Before the fix,-/// `ops::flows_update` computed this transition from an OUTER `existing`-/// read taken before calling into the store — a concurrent write between-/// that read and this call could make the transition invisible to the-/// caller, letting an automatic-trigger graph persist `enabled: true`.-///-/// Proven here without needing to fake a race: the disarm must fire from-/// `current.graph` (MANUAL) vs the new `graph` (automatic) alone, and must-/// WIN over an `enabled_override` that explicitly asks to stay enabled —-/// exactly the shape of override a stale caller-side decision could-/// otherwise have smuggled through.-#[test]-fn update_flow_graph_disarms_transition_from_the_fresh_row_even_when_override_asks_to_stay_enabled()-{- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();- assert!(flow.enabled, "flow created enabled");-- let updated = update_flow_graph(- &config,- &flow.id,- flow.name.clone(),- automatic_schedule_graph(),- false,- Some(true), // caller explicitly asks to stay enabled- false, // force_disarm_if_automatic (the remote-authoring flag) OFF —- // proving the unconditional Rule 1 transition-disarm fires on its own- None,- )- .unwrap();-- assert!(- !updated.enabled,- "a manual->automatic transition must disarm even when enabled_override asks to stay \- enabled — the disarm always wins (R-m2)"- );- let reloaded = get_flow(&config, &flow.id).unwrap().unwrap();- assert!(!reloaded.enabled);-}--/// Sibling of the above: when there is NO transition (the row was already-/// automatic before this call, matching what's actually in the DB right-/// now), an ordinary `enabled_override` is honoured normally — the fix must-/// not over-disarm every automatic-trigger update, only genuine-/// manual/none → automatic transitions (unless `force_disarm_if_automatic`-/// is also set).-#[test]-fn update_flow_graph_does_not_disarm_an_automatic_to_automatic_update() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(- &config,- "demo".to_string(),- automatic_schedule_graph(),- false,- false,- )- .unwrap();- assert!(!flow.enabled, "born disabled — armed explicitly next");- let armed = set_enabled(&config, &flow.id, true).unwrap();- assert!(armed.enabled);-- let updated = update_flow_graph(- &config,- &flow.id,- flow.name.clone(),- automatic_schedule_graph(),- false,- None, // no explicit override — preserve current.enabled- false, // force_disarm_if_automatic OFF- None,- )- .unwrap();-- assert!(- updated.enabled,- "an automatic->automatic update (no transition) must not be auto-disarmed"- );-}--#[test]-fn record_run_sets_last_run_fields() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();- assert!(flow.last_run_at.is_none());-- record_run(&config, &flow.id, "completed").unwrap();- let reloaded = get_flow(&config, &flow.id).unwrap().unwrap();- assert!(reloaded.last_run_at.is_some());- assert_eq!(reloaded.last_status.as_deref(), Some("completed"));-}--#[test]-fn stored_graph_older_than_current_schema_is_migrated_on_read() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- // Insert a raw, versionless graph row directly (bypassing create_flow's- // typed path) to simulate a definition persisted by an older crate build.- let legacy_graph_json = serde_json::json!({- "name": "legacy",- "nodes": [{ "id": "t", "kind": "trigger", "name": "Trigger" }],- "edges": []- })- .to_string();-- with_connection(&config, |conn| {- conn.execute(- "INSERT INTO flow_definitions- (id, name, graph_json, enabled, created_at, updated_at, last_run_at, last_status)- VALUES ('legacy-1', 'legacy', ?1, 1, '2020-01-01T00:00:00Z', '2020-01-01T00:00:00Z', NULL, NULL)",- rusqlite::params![legacy_graph_json],- )?;- Ok(())- })- .unwrap();-- let loaded = get_flow(&config, "legacy-1").unwrap().expect("row present");- assert_eq!(- loaded.graph.schema_version,- tinyflows::model::CURRENT_SCHEMA_VERSION- );- assert_eq!(loaded.graph.nodes.len(), 1);-}--#[test]-fn kv_get_set_round_trips_and_is_namespace_scoped() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- assert!(kv_get(&config, "ns1", "k").unwrap().is_none());-- kv_set(&config, "ns1", "k", &serde_json::json!({"v": 1})).unwrap();- assert_eq!(- kv_get(&config, "ns1", "k").unwrap(),- Some(serde_json::json!({"v": 1}))- );-- // A different namespace does not see ns1's value.- assert!(kv_get(&config, "ns2", "k").unwrap().is_none());-- // Overwrite.- kv_set(&config, "ns1", "k", &serde_json::json!(2)).unwrap();- assert_eq!(- kv_get(&config, "ns1", "k").unwrap(),- Some(serde_json::json!(2))- );-}--// ── require_approval ─────────────────────────────────────────────────────--#[test]-fn create_flow_persists_require_approval() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), true, true).unwrap();- assert!(flow.require_approval);-- let reloaded = get_flow(&config, &flow.id).unwrap().unwrap();- assert!(reloaded.require_approval);-}--#[test]-fn update_flow_graph_can_change_require_approval() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();- assert!(!flow.require_approval);-- let updated = update_flow_graph(- &config,- &flow.id,- flow.name.clone(),- trigger_graph(),- true,- None,- false,- None,- )- .unwrap();- assert!(updated.require_approval);-- let reloaded = get_flow(&config, &flow.id).unwrap().unwrap();- assert!(reloaded.require_approval);-}--#[test]-fn legacy_flow_definitions_row_without_require_approval_column_defaults_false() {- // A row inserted before the `require_approval` column existed. Schema- // init (including the `add_column_if_missing` ALTER) runs once per- // process per database file (R-m8) — since this test opens a fresh- // per-`TempDir` database, that one-time init still runs here, simulating- // a workspace opened once on an older build.- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let legacy_graph_json = serde_json::to_string(&trigger_graph()).unwrap();- with_connection(&config, |conn| {- conn.execute(- "INSERT INTO flow_definitions- (id, name, graph_json, enabled, created_at, updated_at, last_run_at, last_status)- VALUES ('legacy-2', 'legacy', ?1, 1, '2020-01-01T00:00:00Z', '2020-01-01T00:00:00Z', NULL, NULL)",- rusqlite::params![legacy_graph_json],- )?;- Ok(())- })- .unwrap();-- let loaded = get_flow(&config, "legacy-2").unwrap().expect("row present");- assert!(!loaded.require_approval);-}--// ── list_enabled_flows ────────────────────────────────────────────────────--#[test]-fn list_enabled_flows_excludes_disabled() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let enabled_flow =- create_flow(&config, "enabled".to_string(), trigger_graph(), false, true).unwrap();- let disabled_flow = create_flow(- &config,- "disabled".to_string(),- trigger_graph(),- false,- true,- )- .unwrap();- set_enabled(&config, &disabled_flow.id, false).unwrap();-- let (enabled, skipped) = list_enabled_flows(&config).unwrap();- assert_eq!(enabled.len(), 1);- assert_eq!(enabled[0].id, enabled_flow.id);- assert_eq!(skipped, 0);-}--// ── flow_runs CRUD ────────────────────────────────────────────────────────--#[test]-fn flow_run_insert_finish_get_round_trip() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();-- let thread_id = format!("flow:{}:run-1", flow.id);- insert_flow_run(- &config,- &thread_id,- &flow.id,- &thread_id,- "2026-01-01T00:00:00Z",- )- .unwrap();-- let running = get_flow_run(&config, &thread_id)- .unwrap()- .expect("row present");- assert_eq!(running.status, "running");- assert!(running.finished_at.is_none());- assert!(running.steps.is_empty());-- let steps = vec![FlowRunStep {- node_id: "t".to_string(),- output: serde_json::json!([{"json": {"x": 1}}]),- port: None,- ..Default::default()- }];- finish_flow_run(- &config,- &thread_id,- "completed",- "2026-01-01T00:00:01Z",- &steps,- &[],- None,- None,- )- .unwrap();-- let finished = get_flow_run(&config, &thread_id)- .unwrap()- .expect("row present");- assert_eq!(finished.status, "completed");- assert_eq!(- finished.finished_at.as_deref(),- Some("2026-01-01T00:00:01Z")- );- assert_eq!(finished.steps.len(), 1);- assert_eq!(finished.steps[0].node_id, "t");- assert!(finished.pending_approvals.is_empty());- assert!(finished.error.is_none());-}--#[test]-fn finish_flow_run_records_error_on_failure() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();- let thread_id = format!("flow:{}:run-2", flow.id);- insert_flow_run(- &config,- &thread_id,- &flow.id,- &thread_id,- "2026-01-01T00:00:00Z",- )- .unwrap();-- finish_flow_run(- &config,- &thread_id,- "failed",- "2026-01-01T00:00:01Z",- &[],- &[],- Some("boom"),- None,- )- .unwrap();-- let finished = get_flow_run(&config, &thread_id).unwrap().unwrap();- assert_eq!(finished.status, "failed");- assert_eq!(finished.error.as_deref(), Some("boom"));-}--#[test]-fn get_flow_run_returns_none_for_unknown_id() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- assert!(get_flow_run(&config, "missing").unwrap().is_none());-}--#[test]-fn list_flow_runs_orders_newest_first_and_is_scoped_to_flow() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow_a = create_flow(&config, "a".to_string(), trigger_graph(), false, true).unwrap();- let flow_b = create_flow(&config, "b".to_string(), trigger_graph(), false, true).unwrap();-- insert_flow_run(- &config,- "run-a1",- &flow_a.id,- "run-a1",- "2026-01-01T00:00:00Z",- )- .unwrap();- insert_flow_run(- &config,- "run-a2",- &flow_a.id,- "run-a2",- "2026-01-02T00:00:00Z",- )- .unwrap();- insert_flow_run(- &config,- "run-b1",- &flow_b.id,- "run-b1",- "2026-01-01T00:00:00Z",- )- .unwrap();-- let runs_a = list_flow_runs(&config, &flow_a.id, 10).unwrap();- assert_eq!(runs_a.len(), 2);- assert_eq!(runs_a[0].id, "run-a2", "newest run must come first");- assert_eq!(runs_a[1].id, "run-a1");-- let runs_b = list_flow_runs(&config, &flow_b.id, 10).unwrap();- assert_eq!(runs_b.len(), 1);- assert_eq!(runs_b[0].id, "run-b1");-}--// ── insert_duplicate_flow ─────────────────────────────────────────────────--#[test]-fn insert_duplicate_flow_makes_a_disabled_copy_with_new_id_and_same_graph() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- // Enabled source with require_approval + a distinctive graph name.- let mut graph = trigger_graph();- graph.name = "original-graph".to_string();- let source = create_flow(&config, "My Flow".to_string(), graph, true, true).unwrap();- assert!(source.enabled);- record_run(&config, &source.id, "completed").unwrap();- let source = get_flow(&config, &source.id).unwrap().unwrap();- assert!(source.last_status.is_some());-- let copy = insert_duplicate_flow(&config, &source, "My Flow (copy)".to_string()).unwrap();-- // New id, suffixed name, DISABLED, run history reset.- assert_ne!(copy.id, source.id);- assert_eq!(copy.name, "My Flow (copy)");- assert!(- !copy.enabled,- "duplicate must be disabled so it never fires"- );- assert!(copy.last_run_at.is_none());- assert!(copy.last_status.is_none());- // Same graph + require_approval carried over.- assert_eq!(copy.graph, source.graph);- assert_eq!(copy.graph.name, "original-graph");- assert!(copy.require_approval);-- // Persisted and independent — both rows exist.- let reloaded = get_flow(&config, ©.id).unwrap().unwrap();- assert!(!reloaded.enabled);- assert_eq!(reloaded.graph, source.graph);- assert_eq!(list_flows(&config).unwrap().0.len(), 2);-}--// ── prune_flow_runs ───────────────────────────────────────────────────────--fn seed_run(config: &Config, flow_id: &str, id: &str, day: u32, status: &str) {- let started = format!("2026-01-{day:02}T00:00:00Z");- insert_flow_run(config, id, flow_id, id, &started).unwrap();- if status != "running" {- finish_flow_run(- config,- id,- status,- &format!("2026-01-{day:02}T00:00:05Z"),- &[],- &[],- None,- None,- )- .unwrap();- }-}--#[test]-fn prune_flow_runs_keeps_newest_n_terminal_runs() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();-- // 5 completed runs on ascending days.- for i in 1..=5 {- seed_run(&config, &flow.id, &format!("run-{i}"), i, "completed");- }-- let deleted = prune_flow_runs(&config, &flow.id, 2).unwrap();- assert_eq!(deleted, 3, "5 terminal runs, keep 2 => 3 pruned");-- let remaining = list_flow_runs(&config, &flow.id, 100).unwrap();- let ids: Vec<_> = remaining.iter().map(|r| r.id.as_str()).collect();- assert_eq!(ids, vec!["run-5", "run-4"], "newest two survive");-}--#[test]-fn prune_flow_runs_never_removes_pending_approval_run() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();-- // An OLD parked pending_approval run (day 1) plus newer completed runs.- seed_run(&config, &flow.id, "parked", 1, "pending_approval");- for i in 2..=5 {- seed_run(&config, &flow.id, &format!("run-{i}"), i, "completed");- }-- // keep=1 would normally leave only the newest run; the parked one must- // still survive despite being the oldest and outside the newest-1 window.- let deleted = prune_flow_runs(&config, &flow.id, 1).unwrap();- let remaining = list_flow_runs(&config, &flow.id, 100).unwrap();- let ids: std::collections::HashSet<_> = remaining.iter().map(|r| r.id.as_str()).collect();- assert!(- ids.contains("parked"),- "a pending_approval run must never be pruned out from under a resume"- );- assert!(ids.contains("run-5"), "newest terminal run kept");- // Only terminal runs 2..4 were eligible; 5 kept by window => 3 deleted.- assert_eq!(deleted, 3);-}--#[test]-fn prune_flow_runs_leaves_running_rows_alone() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();-- seed_run(&config, &flow.id, "live", 1, "running");- for i in 2..=4 {- seed_run(&config, &flow.id, &format!("run-{i}"), i, "completed");- }-- prune_flow_runs(&config, &flow.id, 1).unwrap();- let remaining = list_flow_runs(&config, &flow.id, 100).unwrap();- let ids: std::collections::HashSet<_> = remaining.iter().map(|r| r.id.as_str()).collect();- assert!(ids.contains("live"), "a running run is never pruned");-}--#[test]-fn insert_flow_run_auto_prunes_beyond_retention_cap() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();-- // Seed exactly MAX_FLOW_RUNS_PER_FLOW completed runs.- let cap = MAX_FLOW_RUNS_PER_FLOW;- for i in 0..cap {- let id = format!("run-{i:04}");- insert_flow_run(- &config,- &id,- &flow.id,- &id,- &format!("2026-01-01T00:00:{i:02}Z"),- )- .unwrap();- finish_flow_run(- &config,- &id,- "completed",- "2026-01-01T00:01:00Z",- &[],- &[],- None,- None,- )- .unwrap();- }- assert_eq!(- list_flow_runs(&config, &flow.id, cap * 2).unwrap().len(),- cap- );-- // One more insert should trigger the retention prune, keeping <= cap.- let extra = "run-extra";- insert_flow_run(&config, extra, &flow.id, extra, "2026-01-02T00:00:00Z").unwrap();- let count = list_flow_runs(&config, &flow.id, cap * 2).unwrap().len();- assert!(- count <= cap,- "auto-prune should keep run count within cap ({count} > {cap})"- );-}--#[test]-fn list_flow_runs_respects_limit() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();-- for i in 0..3 {- let id = format!("run-{i}");- insert_flow_run(- &config,- &id,- &flow.id,- &id,- &format!("2026-01-0{}T00:00:00Z", i + 1),- )- .unwrap();- }-- let limited = list_flow_runs(&config, &flow.id, 2).unwrap();- assert_eq!(limited.len(), 2);-}--// ── flow_suggestions ─────────────────────────────────────────────────────────--fn sample_suggestion(id: &str, title: &str) -> FlowSuggestion {- FlowSuggestion {- id: id.to_string(),- title: title.to_string(),- one_liner: "does a useful thing".to_string(),- rationale: "grounded in your data".to_string(),- trigger_hint: Some("schedule".to_string()),- steps_outline: vec!["step one".to_string(), "step two".to_string()],- suggested_connections: vec!["composio:gmail:conn_1".to_string()],- suggested_slugs: vec!["GMAIL_SEND_EMAIL".to_string()],- build_prompt: "Build a workflow that…".to_string(),- confidence: 0.7,- status: SuggestionStatus::New,- created_at: "2026-07-05T00:00:00Z".to_string(),- source_run_id: Some("run-1".to_string()),- }-}--#[test]-fn suggestions_upsert_list_roundtrip() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let written = upsert_suggestions(- &config,- &[- sample_suggestion("s1", "Alpha"),- sample_suggestion("s2", "Beta"),- ],- )- .unwrap();- assert_eq!(written, 2);-- let all = list_suggestions(&config, Some(SuggestionStatus::New), 50).unwrap();- assert_eq!(all.len(), 2);- // Round-trips the JSON-encoded vec columns.- let alpha = all.iter().find(|s| s.id == "s1").unwrap();- assert_eq!(alpha.steps_outline.len(), 2);- assert_eq!(alpha.suggested_connections, vec!["composio:gmail:conn_1"]);- assert_eq!(alpha.suggested_slugs, vec!["GMAIL_SEND_EMAIL"]);- assert_eq!(alpha.trigger_hint.as_deref(), Some("schedule"));-}--#[test]-fn upsert_suggestions_preserves_user_status_on_rerun() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- upsert_suggestions(&config, &[sample_suggestion("s1", "Alpha")]).unwrap();- // User dismisses it.- assert!(set_suggestion_status(&config, "s1", SuggestionStatus::Dismissed).unwrap());-- // A later discovery run re-proposes the identical idea (same id) with a- // refreshed pitch — the dismissal must survive.- let mut refreshed = sample_suggestion("s1", "Alpha (refined)");- refreshed.status = SuggestionStatus::New; // agent always emits `New`- upsert_suggestions(&config, &[refreshed]).unwrap();-- let dismissed = list_suggestions(&config, Some(SuggestionStatus::Dismissed), 50).unwrap();- assert_eq!(dismissed.len(), 1);- assert_eq!(dismissed[0].title, "Alpha (refined)"); // pitch fields refreshed- // …but it is NOT back in the active `New` list.- let active = list_suggestions(&config, Some(SuggestionStatus::New), 50).unwrap();- assert!(active.is_empty());-}--#[test]-fn set_suggestion_status_returns_false_for_unknown_id() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- assert!(!set_suggestion_status(&config, "missing", SuggestionStatus::Built).unwrap());-}--#[test]-fn list_suggestions_without_status_returns_all() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- upsert_suggestions(&config, &[sample_suggestion("s1", "Alpha")]).unwrap();- set_suggestion_status(&config, "s1", SuggestionStatus::Built).unwrap();- // Filtered to `New` → empty; unfiltered → present.- assert!(list_suggestions(&config, Some(SuggestionStatus::New), 50)- .unwrap()- .is_empty());- assert_eq!(list_suggestions(&config, None, 50).unwrap().len(), 1);-}--#[test]-fn upsert_suggestions_empty_is_noop() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- assert_eq!(upsert_suggestions(&config, &[]).unwrap(), 0);-}--// ── Orphaned-running-run reconciliation (bug B42) ──────────────────────────--#[test]-fn list_running_run_ids_returns_only_running_rows() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();-- insert_flow_run(- &config,- "run-live-1",- &flow.id,- "run-live-1",- "2026-01-01T00:00:00Z",- )- .unwrap();- insert_flow_run(- &config,- "run-live-2",- &flow.id,- "run-live-2",- "2026-01-01T00:00:01Z",- )- .unwrap();- insert_flow_run(- &config,- "run-done",- &flow.id,- "run-done",- "2026-01-01T00:00:02Z",- )- .unwrap();- finish_flow_run(- &config,- "run-done",- "completed",- "2026-01-01T00:00:03Z",- &[],- &[],- None,- None,- )- .unwrap();-- let mut running = list_running_run_ids(&config, "2099-01-01T00:00:00Z").unwrap();- running.sort();- assert_eq!(- running,- vec![- ("run-live-1".to_string(), flow.id.clone()),- ("run-live-2".to_string(), flow.id.clone()),- ],- "only the two still-running rows must be listed, not the completed one"- );-}--#[test]-fn list_running_run_ids_excludes_rows_started_at_or_after_the_floor() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();-- insert_flow_run(- &config,- "run-old",- &flow.id,- "run-old",- "2026-01-01T00:00:00Z",- )- .unwrap();- insert_flow_run(- &config,- "run-at",- &flow.id,- "run-at",- "2026-01-01T00:00:05Z",- )- .unwrap();- insert_flow_run(- &config,- "run-new",- &flow.id,- "run-new",- "2026-01-01T00:00:09Z",- )- .unwrap();-- // The floor is exclusive: a row stamped exactly at the boot floor was- // inserted by THIS process (`start_flow_run_row` anchors the floor before- // stamping), so it must fall outside the candidate set along with newer- // rows — otherwise the sweep could interrupt a live run and drop its- // checkpoint mid-flight.- let running = list_running_run_ids(&config, "2026-01-01T00:00:05Z").unwrap();- assert_eq!(- running,- vec![("run-old".to_string(), flow.id.clone())],- "only rows strictly older than the floor are sweep candidates"- );-}--#[test]-fn mark_run_interrupted_reconciles_a_running_row_with_reason() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();- insert_flow_run(&config, "run-x", &flow.id, "run-x", "2026-01-01T00:00:00Z").unwrap();-- let flipped =- mark_run_interrupted(&config, "run-x", "2026-01-01T00:05:00Z", "boom reason").unwrap();- assert!(flipped, "a running row must be reconciled");-- let row = get_flow_run(&config, "run-x").unwrap().unwrap();- assert_eq!(row.status, "interrupted");- assert_eq!(row.finished_at.as_deref(), Some("2026-01-01T00:05:00Z"));- assert_eq!(row.error.as_deref(), Some("boom reason"));-}--#[test]-fn mark_run_interrupted_is_a_noop_for_a_terminal_row() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();- insert_flow_run(&config, "run-y", &flow.id, "run-y", "2026-01-01T00:00:00Z").unwrap();- finish_flow_run(- &config,- "run-y",- "completed",- "2026-01-01T00:00:01Z",- &[],- &[],- None,- None,- )- .unwrap();-- // The `status = 'running'` guard must protect an already-settled run.- let flipped =- mark_run_interrupted(&config, "run-y", "2026-01-01T00:05:00Z", "should not apply").unwrap();- assert!(- !flipped,- "a completed run must never be clobbered to interrupted"- );-- let row = get_flow_run(&config, "run-y").unwrap().unwrap();- assert_eq!(row.status, "completed");- assert!(row.error.is_none());-}--/// `expire_parked_runs` must return only the runs it ACTUALLY flipped, not the-/// candidates its `SELECT` saw.-///-/// The `SELECT` and each row's guarded `UPDATE` are separate statements on an-/// autocommit connection, so a concurrent `mark_run_resuming` can claim a row in-/// between. The per-row `WHERE status = 'pending_approval'` keeps that row safe,-/// but returning the unfiltered candidate list would let the caller act on a run-/// it never expired — dropping the checkpoint out from under a live resume and-/// publishing a terminal `FlowRunFinished` for a run still executing. That false-/// event is the worse half: the frontend de-dupes terminal events per-/// `flow_id:run_id`, so the run's real completion would later be discarded.-#[test]-fn expire_parked_runs_returns_only_rows_it_actually_flipped() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "ttl".to_string(), trigger_graph(), false, true).unwrap();-- let stale_at = "2000-01-01T00:00:00+00:00";- for id in ["claimed-run", "genuinely-stale-run"] {- insert_flow_run(&config, id, &flow.id, id, stale_at).unwrap();- finish_flow_run(- &config,- id,- "pending_approval",- stale_at,- &[],- &["gate".to_string()],- None,- // No graph pin (T-M1): this fixture is about the TTL sweep's- // candidates-vs-sweeps behaviour, not stale-approval detection, so- // these rows stand in for pre-pin legacy parks.- None,- )- .unwrap();- }-- // Simulate the race: one candidate is claimed by a resume after the sweep's- // SELECT would have seen it, but before its UPDATE lands.- assert!(mark_run_resuming(&config, "claimed-run").unwrap());-- let swept = expire_parked_runs(- &config,- "2099-01-01T00:00:00+00:00",- "2026-01-01T00:00:00+00:00",- "expired",- )- .unwrap();-- let swept_ids: Vec<&str> = swept.iter().map(|(id, _)| id.as_str()).collect();- assert_eq!(- swept_ids,- vec!["genuinely-stale-run"],- "only the row whose guarded UPDATE matched may be reported as swept"- );- assert_eq!(- get_flow_run(&config, "claimed-run")- .unwrap()- .unwrap()- .status,- "running",- "the claimed run must keep executing, untouched by the sweep"- );- assert_eq!(- get_flow_run(&config, "genuinely-stale-run")- .unwrap()- .unwrap()- .status,- "cancelled"- );-}--// ── R-M4: corrupt/unmigratable graph_json rows must not brick a list ────────--#[test]-fn list_flows_skips_a_corrupt_row_and_reports_the_count() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let good_a = create_flow(&config, "good-a".to_string(), trigger_graph(), false, true).unwrap();- let bad = create_flow(&config, "bad".to_string(), trigger_graph(), false, true).unwrap();- let good_b = create_flow(&config, "good-b".to_string(), trigger_graph(), false, true).unwrap();- force_corrupt_graph_json_for_test(&config, &bad.id, "{ not even valid json").unwrap();-- let (flows, skipped) = list_flows(&config).unwrap();- assert_eq!(- skipped, 1,- "exactly the one corrupt row must be counted as skipped"- );- let ids: Vec<&str> = flows.iter().map(|f| f.id.as_str()).collect();- assert_eq!(- flows.len(),- 2,- "the two good rows must still be returned: {ids:?}"- );- assert!(ids.contains(&good_a.id.as_str()));- assert!(ids.contains(&good_b.id.as_str()));- assert!(!ids.contains(&bad.id.as_str()));-}--#[test]-fn list_flows_skips_a_row_whose_schema_version_is_newer_than_this_build_supports() {- // The real-world R-M4 scenario: a user ran a newer build that persisted a- // graph at a `schema_version` this build's `tinyflows::migrate::migrate`- // cannot step backward from, then downgraded.- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let good = create_flow(&config, "good".to_string(), trigger_graph(), false, true).unwrap();- let too_new =- create_flow(&config, "too-new".to_string(), trigger_graph(), false, true).unwrap();- let newer_schema_json = serde_json::json!({- "schema_version": 999,- "name": "from-the-future",- "nodes": [],- "edges": []- })- .to_string();- force_corrupt_graph_json_for_test(&config, &too_new.id, &newer_schema_json).unwrap();-- let (flows, skipped) = list_flows(&config).unwrap();- assert_eq!(skipped, 1);- assert_eq!(flows.len(), 1);- assert_eq!(flows[0].id, good.id);-}--#[test]-fn list_enabled_flows_still_returns_the_good_rows_when_one_is_corrupt() {- // This is the blast-radius scenario R-M4 flags for `bus.rs::handle_app_event`:- // `list_enabled_flows` backs ALL `app_event` trigger dispatch, so one- // corrupt enabled flow must not blackhole matching for every other one.- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let good = create_flow(&config, "good".to_string(), trigger_graph(), false, true).unwrap();- let bad = create_flow(&config, "bad".to_string(), trigger_graph(), false, true).unwrap();- force_corrupt_graph_json_for_test(&config, &bad.id, "not json at all").unwrap();-- let (enabled, skipped) = list_enabled_flows(&config).unwrap();- assert_eq!(skipped, 1);- assert_eq!(enabled.len(), 1);- assert_eq!(enabled[0].id, good.id);-}--#[test]-fn list_enabled_flows_excludes_a_corrupt_disabled_row_without_counting_it_as_skipped() {- // A corrupt row that was never enabled must not even be attempted for- // decode by `list_enabled_flows` (the WHERE clause filters it out at the- // SQL layer before `map_flow_row` ever runs) — it is neither returned nor- // counted as skipped by this particular listing.- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let good = create_flow(&config, "good".to_string(), trigger_graph(), false, true).unwrap();- let disabled_and_corrupt = create_flow(- &config,- "disabled-bad".to_string(),- trigger_graph(),- false,- true,- )- .unwrap();- set_enabled(&config, &disabled_and_corrupt.id, false).unwrap();- force_corrupt_graph_json_for_test(&config, &disabled_and_corrupt.id, "{{{").unwrap();-- let (enabled, skipped) = list_enabled_flows(&config).unwrap();- assert_eq!(skipped, 0);- assert_eq!(enabled.len(), 1);- assert_eq!(enabled[0].id, good.id);-}--// ── R-m1: concurrent step upserts must not lose a step ──────────────────────--#[test]-fn concurrent_step_upserts_do_not_lose_a_step() {- // Two observer callbacks for parallel branch nodes of the same run,- // racing to persist their step. Before the `BEGIN IMMEDIATE` fix this was- // a classic untransacted read-modify-write: both threads could read the- // same pre-write `steps_json`, and whichever `UPDATE` landed last would- // silently discard the other thread's step — permanently, since the- // post-hoc `settle_steps` reconstruction only refills a missing node with- // `status: None`, not its real outcome.- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();- let run_id = "run-concurrent";- insert_flow_run(&config, run_id, &flow.id, run_id, "2026-01-01T00:00:00Z").unwrap();-- let barrier = std::sync::Arc::new(std::sync::Barrier::new(2));-- let config_a = config.clone();- let barrier_a = barrier.clone();- let handle_a = std::thread::spawn(move || {- barrier_a.wait();- upsert_flow_run_step(- &config_a,- run_id,- &FlowRunStep {- node_id: "branch-a".to_string(),- output: serde_json::json!([{"json": {"a": 1}}]),- status: Some("success".to_string()),- ..Default::default()- },- )- });-- let config_b = config.clone();- let barrier_b = barrier.clone();- let handle_b = std::thread::spawn(move || {- barrier_b.wait();- upsert_flow_run_step(- &config_b,- run_id,- &FlowRunStep {- node_id: "branch-b".to_string(),- output: serde_json::json!([{"json": {"b": 1}}]),- status: Some("success".to_string()),- ..Default::default()- },- )- });-- handle_a.join().unwrap().unwrap();- handle_b.join().unwrap().unwrap();-- let row = get_flow_run(&config, run_id).unwrap().unwrap();- let node_ids: std::collections::HashSet<&str> =- row.steps.iter().map(|s| s.node_id.as_str()).collect();- assert_eq!(- row.steps.len(),- 2,- "both concurrent steps must survive, none silently dropped: {:?}",- row.steps- );- assert!(node_ids.contains("branch-a"));- assert!(node_ids.contains("branch-b"));-}--#[test]-fn concurrent_upserts_to_the_same_node_id_do_not_corrupt_the_step_list() {- // Same run, same node_id, racing "replace" writes — the transaction must- // still leave exactly one entry for that node (whichever write wins the- // serialization order), never a torn/duplicated list.- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let flow = create_flow(&config, "demo".to_string(), trigger_graph(), false, true).unwrap();- let run_id = "run-same-node";- insert_flow_run(&config, run_id, &flow.id, run_id, "2026-01-01T00:00:00Z").unwrap();-- let barrier = std::sync::Arc::new(std::sync::Barrier::new(2));- let mut handles = Vec::new();- for i in 0..2 {- let config = config.clone();- let barrier = barrier.clone();- handles.push(std::thread::spawn(move || {- barrier.wait();- upsert_flow_run_step(- &config,- run_id,- &FlowRunStep {- node_id: "same-node".to_string(),- output: serde_json::json!([{"json": {"attempt": i}}]),- status: Some("success".to_string()),- ..Default::default()- },- )- }));- }- for h in handles {- h.join().unwrap().unwrap();- }-- let row = get_flow_run(&config, run_id).unwrap().unwrap();- assert_eq!(- row.steps.len(),- 1,- "a re-upsert of the same node_id must replace, not duplicate: {:?}",- row.steps- );- assert_eq!(row.steps[0].node_id, "same-node");-}--// ── R-m8: schema init is gated to once per process per database path ───────--#[test]-fn schema_initializes_correctly_on_a_fresh_database_and_is_idempotent_across_calls() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- // First-ever call against this database file in the process: exercises- // the full schema DDL (CREATE TABLE batch + indexes) plus the- // `require_approval` `add_column_if_missing` migration on a database that- // has never been opened before.- let flow = create_flow(- &config,- "fresh-db".to_string(),- trigger_graph(),- true, // require_approval- true,- )- .unwrap();- assert!(- flow.require_approval,- "the post-hoc require_approval column must exist and be writable on a brand-new db"- );-- // Repeat calls against the SAME path must not need (or re-run) DDL —- // proves the cached "already initialized" state doesn't break ordinary- // reads/writes on reuse.- let (listed, skipped) = list_flows(&config).unwrap();- assert_eq!(skipped, 0);- assert_eq!(listed.len(), 1);- assert!(listed[0].require_approval);-- let reloaded = get_flow(&config, &flow.id).unwrap().unwrap();- assert!(reloaded.require_approval);-- let run_id = "run-schema-check";- insert_flow_run(&config, run_id, &flow.id, run_id, "2026-01-01T00:00:00Z").unwrap();- assert!(get_flow_run(&config, run_id).unwrap().is_some());-}--#[test]-fn schema_initializes_independently_for_each_distinct_database_path() {- // Regression guard for the once-per-process cache: if it were keyed by a- // single process-wide flag instead of by database path, opening a SECOND- // independent workspace after the first would silently skip schema- // creation and every write against it would fail with "no such table".- let tmp_a = TempDir::new().unwrap();- let config_a = test_config(&tmp_a);- let flow_a = create_flow(&config_a, "a".to_string(), trigger_graph(), false, true).unwrap();-- let tmp_b = TempDir::new().unwrap();- let config_b = test_config(&tmp_b);- let flow_b = create_flow(&config_b, "b".to_string(), trigger_graph(), false, true).unwrap();-- assert_eq!(list_flows(&config_a).unwrap().0.len(), 1);- assert_eq!(list_flows(&config_b).unwrap().0.len(), 1);- assert_eq!(- get_flow(&config_a, &flow_a.id).unwrap().unwrap().id,- flow_a.id- );- assert_eq!(- get_flow(&config_b, &flow_b.id).unwrap().unwrap().id,- flow_b.id- );-}--/// R-m8 regression: gating the DDL behind a per-path "already initialized" set-/// must not cost the store its self-healing.-///-/// Before the gate existed, the DDL ran on every `with_connection` call, so a-/// database deleted or replaced at runtime (workspace reset, manual deletion,-/// a restore) recovered on the very next call — `Connection::open` creates a-/// fresh empty file and `CREATE TABLE IF NOT EXISTS` repopulates it. With a-/// naive cache the set still reports "initialized" while the file behind it is-/// empty, and every query afterwards fails `no such table: flow_definitions`-/// until the process restarts. This pins the verify-on-hit that restores it.-#[test]-fn schema_reinitializes_when_the_database_file_is_deleted_at_runtime() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- // First use populates the per-path cache and creates the schema.- let flow = create_flow(- &config,- "before-deletion".to_string(),- trigger_graph(),- false,- true,- )- .unwrap();- let (flows, _skipped) = list_flows(&config).unwrap();- assert_eq!(flows.len(), 1, "sanity: the flow was persisted");-- // Simulate a workspace reset / manual deletion while the process lives on.- let db_path = config.workspace_dir.join("flows").join("flows.db");- assert!(- db_path.exists(),- "sanity: the flows db exists before deletion"- );- std::fs::remove_file(&db_path).unwrap();- // WAL sidecars must go too, or SQLite can resurrect pages from them.- let _ = std::fs::remove_file(db_path.with_extension("db-wal"));- let _ = std::fs::remove_file(db_path.with_extension("db-shm"));-- // The cache still says this path is initialized. Without the verify-on-hit- // this errors with `no such table: flow_definitions`.- let (flows_after, skipped_after) = list_flows(&config)- .expect("a deleted database must be re-initialized, not left wedged at 'no such table'");- assert!(- flows_after.is_empty(),- "the recreated database starts empty — the prior flow is genuinely gone"- );- assert_eq!(skipped_after, 0, "an empty database skips nothing");-- // And the store is fully usable again, not merely readable.- let recreated = create_flow(- &config,- "after-deletion".to_string(),- trigger_graph(),- false,- true,- )- .expect("writes must work against the re-initialized schema");- assert_ne!(recreated.id, flow.id);- let (flows_final, _) = list_flows(&config).unwrap();- assert_eq!(flows_final.len(), 1);-}diff --git a/src/openhuman/flows/tinyflows/checkpoint_sqlite.rs b/src/openhuman/flows/tinyflows/checkpoint_sqlite.rsdeleted file mode 100644index 632503f1f0..0000000000--- a/src/openhuman/flows/tinyflows/checkpoint_sqlite.rs+++ /dev/null@@ -1,706 +0,0 @@-//! SQLite-backed [`Checkpointer`] for flow runs — the host's own port of the-//! backend tinyflows dropped when it vendored its state-graph runtime in-crate-//! (tinyflows PR #43).-//!-//! Flow runs are durable and cross-process: `flows_run` resumes an interrupted-//! run from `<workspace_dir>/flows/checkpoints.db`. That database predates the-//! engine change, so switching to tinyflows' `FileCheckpointer` would have-//! stranded every in-flight run rather than merely changing a backend. The-//! trait tinyflows vendored is method-for-method the one `tinyagents` defines,-//! so this is that crate's `graph::checkpoint::sqlite` retargeted at-//! `tinyflows::graph` — same SQL, same schema, same on-disk format, so an-//! existing `checkpoints.db` is read and written exactly as before.-//!-//! Keep it that way: this file is a port, not a rewrite. A behavioural change-//! here is a divergence from the runtime that reads the rows.--use std::marker::PhantomData;-use std::path::Path;-use std::sync::{Arc, Mutex};--use async_trait::async_trait;-use rusqlite::{params, Connection, OptionalExtension};-use serde::de::DeserializeOwned;-use serde::Serialize;--use tinyflows::graph::checkpoint::merge_writes;-use tinyflows::graph::error::{GraphError, Result};-use tinyflows::graph::ids::{CheckpointId, NodeId};-use tinyflows::graph::{- Checkpoint, CheckpointConfig, CheckpointMetadata, CheckpointSource, CheckpointTuple,- Checkpointer, PendingWrite,-};--/// A [`Checkpointer`] that persists checkpoints in a SQLite database.-///-/// Cheap to clone; clones share the same underlying connection (and therefore-/// the same data, including for in-memory databases). Generic over `State`; the-/// [`Checkpointer`] impl requires `State: Serialize + DeserializeOwned`.-pub struct SqliteCheckpointer<State> {- conn: Arc<Mutex<Connection>>,- _marker: PhantomData<fn() -> State>,-}--impl<State> Clone for SqliteCheckpointer<State> {- fn clone(&self) -> Self {- Self {- conn: self.conn.clone(),- _marker: PhantomData,- }- }-}--fn sqlite_err(context: &str, err: impl std::fmt::Display) -> GraphError {- GraphError::Checkpoint(format!("sqlite checkpointer: {context}: {err}"))-}--impl<State> SqliteCheckpointer<State> {- /// Opens (creating if needed) a SQLite-backed checkpointer at `path`.- ///- /// Pass `":memory:"` for an ephemeral in-memory database (see- /// [`SqliteCheckpointer::in_memory`]).- pub fn open(path: impl AsRef<Path>) -> Result<Self> {- let conn = Connection::open(path.as_ref()).map_err(|e| sqlite_err("open database", e))?;- Self::from_connection(conn)- }-- /// Opens an ephemeral in-memory checkpointer (`":memory:"`).- ///- /// The database lives only as long as this handle and its clones, which share- /// the single underlying connection.- pub fn in_memory() -> Result<Self> {- let conn = Connection::open_in_memory().map_err(|e| sqlite_err("open in-memory", e))?;- Self::from_connection(conn)- }-- /// Wraps a caller-owned open [`Connection`], ensuring the checkpoint schema- /// exists.- ///- /// Use this to share a connection from your own pool or an existing- /// application database instead of letting the checkpointer own its handle.- /// The schema is idempotent (`CREATE TABLE IF NOT EXISTS`), so it is safe to- /// call on a database that already has the tables.- ///- /// If your application depends on a *different* `rusqlite`/`libsqlite3-sys`- /// version (a native-link conflict that prevents passing a `Connection`- /// across the boundary), apply [`SqliteCheckpointer::schema_sql`] to your own- /// connection instead and drive the tables directly.- pub fn from_connection(conn: Connection) -> Result<Self> {- conn.execute_batch(SCHEMA)- .map_err(|e| sqlite_err("create schema", e))?;- Ok(Self {- conn: Arc::new(Mutex::new(conn)),- _marker: PhantomData,- })- }-- /// Returns the checkpoint table + index DDL as a reusable, dependency-free- /// SQL string.- ///- /// This is the schema-helper escape hatch for applications that own their- /// own SQLite connection (possibly at an incompatible native-link version):- /// execute this DDL on your connection to create the tables the checkpoint- /// projection expects, without linking this crate's `rusqlite`.- pub fn schema_sql() -> &'static str {- SCHEMA- }-- fn lock(&self) -> Result<std::sync::MutexGuard<'_, Connection>> {- self.conn.lock().map_err(|_| {- GraphError::Checkpoint("sqlite checkpointer: connection lock poisoned".to_string())- })- }-}--/// Table + indexes. `seq` preserves insertion order; the indexes serve thread-/// listing, `(thread_id, checkpoint_id)` parent-chain lookups, and — since the-/// namespace-scoped overrides landed — `(thread_id, namespace, …)` scoped-/// lookups.-///-/// # `namespace` is a first-class, indexed column-///-/// It holds the canonical JSON encoding of the namespace vector, which-/// `serde_json` emits deterministically, so equality on the column is exactly-/// equality on the namespace. It was already stored this way; what was missing-/// were the indexes, and therefore the ability to *push the scope down into-/// SQL* at all. Without them `get_scoped`, `get_tuple` and `state_history` all-/// fell back to the trait defaults, which scan the whole thread once per-/// lineage hop — O(H²) per namespaced read on the one backend that had no-/// business being in that class. Both are `CREATE INDEX IF NOT EXISTS`, so an-/// existing database picks them up on the next open with no migration step.-///-/// `checkpoint_writes` is the partial-failure ledger. Its primary key-/// `(thread_id, namespace, checkpoint_id, task_id, idx)` mirrors LangGraph's-/// writes table and is what makes `put_writes` idempotent in SQL rather than in-/// application code.-const SCHEMA: &str = "\-CREATE TABLE IF NOT EXISTS checkpoints (- seq INTEGER PRIMARY KEY AUTOINCREMENT,- thread_id TEXT NOT NULL,- checkpoint_id TEXT NOT NULL,- parent_checkpoint_id TEXT,- run_id TEXT,- namespace TEXT NOT NULL,- next_nodes TEXT NOT NULL,- source TEXT NOT NULL,- step INTEGER NOT NULL,- has_interrupts INTEGER NOT NULL,- record TEXT NOT NULL-);-CREATE INDEX IF NOT EXISTS idx_checkpoints_thread ON checkpoints (thread_id, seq);-CREATE INDEX IF NOT EXISTS idx_checkpoints_lookup ON checkpoints (thread_id, checkpoint_id);-CREATE INDEX IF NOT EXISTS idx_checkpoints_scoped ON checkpoints (thread_id, namespace, seq);-CREATE INDEX IF NOT EXISTS idx_checkpoints_scoped_lookup- ON checkpoints (thread_id, namespace, checkpoint_id, seq);--CREATE TABLE IF NOT EXISTS checkpoint_writes (- thread_id TEXT NOT NULL,- namespace TEXT NOT NULL,- checkpoint_id TEXT NOT NULL,- task_id TEXT NOT NULL,- idx INTEGER NOT NULL,- node TEXT NOT NULL,- channel TEXT NOT NULL,- payload TEXT NOT NULL,- PRIMARY KEY (thread_id, namespace, checkpoint_id, task_id, idx)-);-CREATE INDEX IF NOT EXISTS idx_checkpoint_writes_thread- ON checkpoint_writes (thread_id, checkpoint_id);-";--/// tinyflows keeps its own copy `pub(crate)`, so the port carries one. Same-/// message: a caller comparing the two backends' errors sees no difference.-fn require_checkpoint_id(config: &CheckpointConfig) -> Result<String> {- config.checkpoint_id.clone().ok_or_else(|| {- GraphError::Checkpoint(format!(- "put_writes requires an explicit checkpoint_id (thread `{}`)",- config.thread_id- ))- })-}--/// The projected listing columns read from one `checkpoints` row.-struct MetaRow {- thread_id: String,- checkpoint_id: String,- run_id: Option<String>,- parent_checkpoint_id: Option<String>,- namespace_json: String,- next_nodes_json: String,- source: String,- step: i64,- has_interrupts: i64,-}--/// Reconstructs a [`CheckpointMetadata`] from the projected listing columns,-/// without touching the full serialized record.-fn row_metadata(row: MetaRow) -> Result<CheckpointMetadata> {- let namespace: Vec<String> =- serde_json::from_str(&row.namespace_json).map_err(|e| sqlite_err("decode namespace", e))?;- let next_nodes: Vec<NodeId> = serde_json::from_str(&row.next_nodes_json)- .map_err(|e| sqlite_err("decode next_nodes", e))?;- Ok(CheckpointMetadata {- thread_id: row.thread_id,- checkpoint_id: row.checkpoint_id,- run_id: row.run_id,- parent_checkpoint_id: row.parent_checkpoint_id,- namespace,- next_nodes,- has_interrupts: row.has_interrupts != 0,- source: CheckpointSource::parse(&row.source).unwrap_or(CheckpointSource::Loop),- step: row.step as usize,- })-}--#[async_trait]-impl<State> Checkpointer<State> for SqliteCheckpointer<State>-where- State: Serialize + DeserializeOwned + Send + Sync + 'static,-{- async fn put(&self, checkpoint: Checkpoint<State>) -> Result<CheckpointId> {- let id = CheckpointId::new(checkpoint.checkpoint_id.clone());- // Serialize + the synchronous rusqlite insert (which also blocks on the- // connection mutex) is blocking work; run it on the blocking pool so it- // never stalls a tokio worker on the step-critical path.- let conn = self.conn.clone();- tokio::task::spawn_blocking(move || -> Result<()> {- let meta = checkpoint.to_metadata();- let namespace = serde_json::to_string(&checkpoint.namespace)- .map_err(|e| sqlite_err("encode namespace", e))?;- let next_nodes = serde_json::to_string(&checkpoint.next_nodes)- .map_err(|e| sqlite_err("encode next_nodes", e))?;- let record =- serde_json::to_string(&checkpoint).map_err(|e| sqlite_err("encode record", e))?;-- let conn = conn.lock().map_err(|_| {- GraphError::Checkpoint("sqlite checkpointer: connection lock poisoned".to_string())- })?;- conn.execute(- "INSERT INTO checkpoints (- thread_id, checkpoint_id, parent_checkpoint_id, run_id,- namespace, next_nodes, source, step, has_interrupts, record- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",- params![- checkpoint.thread_id,- checkpoint.checkpoint_id,- checkpoint.parent_checkpoint_id,- checkpoint.run_id,- namespace,- next_nodes,- meta.source.as_str(),- meta.step as i64,- i64::from(meta.has_interrupts),- record,- ],- )- .map_err(|e| sqlite_err("insert checkpoint", e))?;- Ok(())- })- .await- .map_err(|e| sqlite_err("join blocking put task", e))??;- Ok(id)- }-- async fn get(- &self,- thread_id: &str,- checkpoint_id: Option<&str>,- ) -> Result<Option<Checkpoint<State>>> {- let conn = self.lock()?;- // Latest matching row (highest seq) for either the whole thread or a- // specific id, mirroring the append-only history of the other backends.- let record: Option<String> = match checkpoint_id {- Some(id) => conn- .query_row(- "SELECT record FROM checkpoints- WHERE thread_id = ?1 AND checkpoint_id = ?2- ORDER BY seq DESC LIMIT 1",- params![thread_id, id],- |row| row.get(0),- )- .optional()- .map_err(|e| sqlite_err("query checkpoint", e))?,- None => conn- .query_row(- "SELECT record FROM checkpoints- WHERE thread_id = ?1- ORDER BY seq DESC LIMIT 1",- params![thread_id],- |row| row.get(0),- )- .optional()- .map_err(|e| sqlite_err("query latest checkpoint", e))?,- };- match record {- Some(json) => Ok(Some(- serde_json::from_str(&json).map_err(|e| sqlite_err("decode record", e))?,- )),- None => Ok(None),- }- }-- async fn get_scoped(- &self,- thread_id: &str,- checkpoint_id: Option<&str>,- namespace: &[String],- ) -> Result<Option<Checkpoint<State>>> {- // Pushed down to one indexed query. The trait default lists the whole- // thread and then re-`get`s the winner, which costs a full thread scan- // per call — and `state_history` calls it once per lineage hop.- let namespace_json =- serde_json::to_string(namespace).map_err(|e| sqlite_err("encode namespace", e))?;- let conn = self.lock()?;- let record: Option<String> = match checkpoint_id {- Some(id) => conn- .query_row(- "SELECT record FROM checkpoints- WHERE thread_id = ?1 AND namespace = ?2 AND checkpoint_id = ?3- ORDER BY seq DESC LIMIT 1",- params![thread_id, namespace_json, id],- |row| row.get(0),- )- .optional()- .map_err(|e| sqlite_err("query scoped checkpoint", e))?,- None => conn- .query_row(- "SELECT record FROM checkpoints- WHERE thread_id = ?1 AND namespace = ?2- ORDER BY seq DESC LIMIT 1",- params![thread_id, namespace_json],- |row| row.get(0),- )- .optional()- .map_err(|e| sqlite_err("query latest scoped checkpoint", e))?,- };- match record {- Some(json) => Ok(Some(- serde_json::from_str(&json).map_err(|e| sqlite_err("decode record", e))?,- )),- None => Ok(None),- }- }-- async fn state_history(- &self,- thread_id: &str,- namespace: &[String],- limit: Option<usize>,- ) -> Result<Vec<CheckpointTuple<State>>> {- // One indexed range read of the namespace's rows, then the lineage walk- // in memory — instead of the default's `get_tuple` (and therefore- // `get_scoped`) per hop.- let namespace_json =- serde_json::to_string(namespace).map_err(|e| sqlite_err("encode namespace", e))?;- let (records, writes) = {- let conn = self.lock()?;- let mut stmt = conn- .prepare(- "SELECT record FROM checkpoints- WHERE thread_id = ?1 AND namespace = ?2 ORDER BY seq ASC",- )- .map_err(|e| sqlite_err("prepare state_history", e))?;- let rows = stmt- .query_map(params![thread_id, namespace_json], |row| {- row.get::<_, String>(0)- })- .map_err(|e| sqlite_err("query state_history", e))?;- let mut records: Vec<Checkpoint<State>> = Vec::new();- for row in rows {- let json = row.map_err(|e| sqlite_err("read record row", e))?;- records- .push(serde_json::from_str(&json).map_err(|e| sqlite_err("decode record", e))?);- }- let writes = read_writes_by_checkpoint(&conn, thread_id, &namespace_json)?;- (records, writes)- };- if records.is_empty() {- return Ok(Vec::new());- }-- // Last write wins for a re-used id, matching `get`.- let mut by_id: std::collections::HashMap<String, Checkpoint<State>> =- std::collections::HashMap::with_capacity(records.len());- let mut cursor: Option<String> = None;- for record in records {- cursor = Some(record.checkpoint_id.clone());- by_id.insert(record.checkpoint_id.clone(), record);- }-- let mut out = Vec::new();- while let Some(id) = cursor {- // Written as a nested `if` rather than the source's let-chain:- // this crate is edition 2021, where let-chains do not parse.- if let Some(limit) = limit {- if out.len() >= limit {- break;- }- }- // `remove` doubles as the cycle guard: each id is visited once.- let Some(checkpoint) = by_id.remove(&id) else {- break;- };- cursor = checkpoint.parent_checkpoint_id.clone();- let config = CheckpointConfig {- thread_id: checkpoint.thread_id.clone(),- checkpoint_id: Some(checkpoint.checkpoint_id.clone()),- namespace: checkpoint.namespace.clone(),- };- let parent_config =- checkpoint- .parent_checkpoint_id- .as_ref()- .map(|parent| CheckpointConfig {- thread_id: checkpoint.thread_id.clone(),- checkpoint_id: Some(parent.clone()),- namespace: checkpoint.namespace.clone(),- });- let pending_writes = writes- .get(&checkpoint.checkpoint_id)- .cloned()- .unwrap_or_else(|| checkpoint.pending_writes.clone());- out.push(CheckpointTuple {- config,- checkpoint,- parent_config,- pending_writes,- });- }- Ok(out)- }-- async fn list(&self, thread_id: &str) -> Result<Vec<CheckpointMetadata>> {- let conn = self.lock()?;- let mut stmt = conn- .prepare(- "SELECT thread_id, checkpoint_id, run_id, parent_checkpoint_id,- namespace, next_nodes, source, step, has_interrupts- FROM checkpoints WHERE thread_id = ?1 ORDER BY seq ASC",- )- .map_err(|e| sqlite_err("prepare list", e))?;- let rows = stmt- .query_map(params![thread_id], |row| {- Ok(MetaRow {- thread_id: row.get(0)?,- checkpoint_id: row.get(1)?,- run_id: row.get(2)?,- parent_checkpoint_id: row.get(3)?,- namespace_json: row.get(4)?,- next_nodes_json: row.get(5)?,- source: row.get(6)?,- step: row.get(7)?,- has_interrupts: row.get(8)?,- })- })- .map_err(|e| sqlite_err("query list", e))?;- let mut out = Vec::new();- for row in rows {- out.push(row_metadata(- row.map_err(|e| sqlite_err("read list row", e))?,- )?);- }- Ok(out)- }-- async fn get_thread(&self, thread_id: &str) -> Result<Vec<Checkpoint<State>>> {- // Single-pass bulk read: one indexed range query over the thread's- // rows in insertion order, instead of the default's one point query- // per listed id.- let conn = self.lock()?;- let mut stmt = conn- .prepare("SELECT record FROM checkpoints WHERE thread_id = ?1 ORDER BY seq ASC")- .map_err(|e| sqlite_err("prepare get_thread", e))?;- let rows = stmt- .query_map(params![thread_id], |row| row.get::<_, String>(0))- .map_err(|e| sqlite_err("query get_thread", e))?;- let mut out = Vec::new();- for row in rows {- let json = row.map_err(|e| sqlite_err("read record row", e))?;- out.push(serde_json::from_str(&json).map_err(|e| sqlite_err("decode record", e))?);- }- Ok(out)- }-- async fn list_threads(&self) -> Result<Vec<String>> {- let conn = self.lock()?;- let mut stmt = conn- .prepare("SELECT DISTINCT thread_id FROM checkpoints")- .map_err(|e| sqlite_err("prepare list_threads", e))?;- let rows = stmt- .query_map([], |row| row.get::<_, String>(0))- .map_err(|e| sqlite_err("query list_threads", e))?;- let mut out = Vec::new();- for row in rows {- out.push(row.map_err(|e| sqlite_err("read thread row", e))?);- }- Ok(out)- }-- async fn delete_thread(&self, thread_id: &str) -> Result<()> {- let mut conn = self.lock()?;- let tx = conn- .transaction()- .map_err(|e| sqlite_err("begin delete_thread", e))?;- tx.execute(- "DELETE FROM checkpoints WHERE thread_id = ?1",- params![thread_id],- )- .map_err(|e| sqlite_err("delete thread", e))?;- // Writes go with the thread — and across *every* namespace, not just- // the root one, or an embedded subgraph's ledger outlives its thread.- tx.execute(- "DELETE FROM checkpoint_writes WHERE thread_id = ?1",- params![thread_id],- )- .map_err(|e| sqlite_err("delete thread writes", e))?;- tx.commit()- .map_err(|e| sqlite_err("commit delete_thread", e))?;- Ok(())- }-- async fn delete_checkpoints(&self, thread_id: &str, ids: &[String]) -> Result<usize> {- if ids.is_empty() {- return Ok(0);- }- let mut conn = self.lock()?;- let tx = conn- .transaction()- .map_err(|e| sqlite_err("begin transaction", e))?;- let mut removed = 0usize;- for id in ids {- removed += tx- .execute(- "DELETE FROM checkpoints WHERE thread_id = ?1 AND checkpoint_id = ?2",- params![thread_id, id],- )- .map_err(|e| sqlite_err("delete checkpoint", e))?;- tx.execute(- "DELETE FROM checkpoint_writes WHERE thread_id = ?1 AND checkpoint_id = ?2",- params![thread_id, id],- )- .map_err(|e| sqlite_err("delete checkpoint writes", e))?;- }- tx.commit().map_err(|e| sqlite_err("commit delete", e))?;- Ok(removed)- }-- async fn put_writes(&self, config: &CheckpointConfig, writes: &[PendingWrite]) -> Result<()> {- let checkpoint_id = require_checkpoint_id(config)?;- if writes.is_empty() {- return Ok(());- }- let namespace_json = serde_json::to_string(&config.namespace)- .map_err(|e| sqlite_err("encode namespace", e))?;- let mut conn = self.lock()?;- let tx = conn- .transaction()- .map_err(|e| sqlite_err("begin put_writes", e))?;- let mut stored = 0usize;- for write in writes {- // The replace-vs-ignore rule pushed into SQL: a control-plane write- // (`idx < 0`) legitimately changes on a retry and upserts, while a- // data write is append-once so a retried `put_writes` is a no-op.- // Doing it with two conflict clauses rather than a read-then-write- // keeps it correct under concurrent writers.- let sql = if write.is_control_plane() {- "INSERT INTO checkpoint_writes- (thread_id, namespace, checkpoint_id, task_id, idx, node, channel, payload)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)- ON CONFLICT(thread_id, namespace, checkpoint_id, task_id, idx) DO UPDATE SET- node = excluded.node,- channel = excluded.channel,- payload = excluded.payload"- } else {- "INSERT INTO checkpoint_writes- (thread_id, namespace, checkpoint_id, task_id, idx, node, channel, payload)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)- ON CONFLICT(thread_id, namespace, checkpoint_id, task_id, idx) DO NOTHING"- };- let payload = serde_json::to_string(&write.payload)- .map_err(|e| sqlite_err("encode write payload", e))?;- stored += tx- .execute(- sql,- params![- config.thread_id,- namespace_json,- checkpoint_id,- write.task_id,- write.idx,- write.node.as_str(),- write.channel,- payload,- ],- )- .map_err(|e| sqlite_err("insert checkpoint write", e))?;- }- tx.commit()- .map_err(|e| sqlite_err("commit put_writes", e))?;- tracing::debug!(- "[checkpoint:sqlite] put_writes thread={} checkpoint={checkpoint_id} offered={} stored={stored}",- config.thread_id,- writes.len()- );- Ok(())- }-- async fn get_writes(&self, config: &CheckpointConfig) -> Result<Vec<PendingWrite>> {- let Some(checkpoint_id) = self.resolve_write_target(config).await? else {- return Ok(Vec::new());- };- let namespace_json = serde_json::to_string(&config.namespace)- .map_err(|e| sqlite_err("encode namespace", e))?;- let conn = self.lock()?;- let mut stmt = conn- .prepare(- "SELECT node, task_id, idx, channel, payload FROM checkpoint_writes- WHERE thread_id = ?1 AND namespace = ?2 AND checkpoint_id = ?3- ORDER BY rowid ASC",- )- .map_err(|e| sqlite_err("prepare get_writes", e))?;- let rows = stmt- .query_map(- params![config.thread_id, namespace_json, checkpoint_id],- map_write_row,- )- .map_err(|e| sqlite_err("query get_writes", e))?;- let mut out = Vec::new();- for row in rows {- out.push(row.map_err(|e| sqlite_err("read write row", e))??);- }- Ok(out)- }-}--/// Decodes one `checkpoint_writes` row into a [`PendingWrite`].-///-/// Returns a nested `Result` because the payload decode can fail with a serde-/// error that `rusqlite`'s row-mapper signature has no room for.-#[allow(clippy::type_complexity)]-fn map_write_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Result<PendingWrite>> {- let node: String = row.get(0)?;- let task_id: String = row.get(1)?;- let idx: i64 = row.get(2)?;- let channel: String = row.get(3)?;- let payload_json: String = row.get(4)?;- Ok(- match serde_json::from_str::<serde_json::Value>(&payload_json) {- Ok(payload) => Ok(PendingWrite {- node: NodeId::from(node),- task_id,- idx,- channel,- payload,- }),- Err(e) => Err(sqlite_err("decode write payload", e)),- },- )-}--/// Reads every write in `thread_id`/`namespace`, grouped by checkpoint id.-///-/// One query for the whole lineage, so `state_history` does not issue a-/// `get_writes` per hop.-fn read_writes_by_checkpoint(- conn: &Connection,- thread_id: &str,- namespace_json: &str,-) -> Result<std::collections::HashMap<String, Vec<PendingWrite>>> {- let mut stmt = conn- .prepare(- "SELECT checkpoint_id, node, task_id, idx, channel, payload FROM checkpoint_writes- WHERE thread_id = ?1 AND namespace = ?2 ORDER BY rowid ASC",- )- .map_err(|e| sqlite_err("prepare writes-by-checkpoint", e))?;- let rows = stmt- .query_map(params![thread_id, namespace_json], |row| {- let checkpoint_id: String = row.get(0)?;- let node: String = row.get(1)?;- let task_id: String = row.get(2)?;- let idx: i64 = row.get(3)?;- let channel: String = row.get(4)?;- let payload_json: String = row.get(5)?;- Ok((checkpoint_id, node, task_id, idx, channel, payload_json))- })- .map_err(|e| sqlite_err("query writes-by-checkpoint", e))?;- let mut out: std::collections::HashMap<String, Vec<PendingWrite>> =- std::collections::HashMap::new();- for row in rows {- let (checkpoint_id, node, task_id, idx, channel, payload_json) =- row.map_err(|e| sqlite_err("read write row", e))?;- let payload = serde_json::from_str(&payload_json)- .map_err(|e| sqlite_err("decode write payload", e))?;- let write = PendingWrite {- node: NodeId::from(node),- task_id,- idx,- channel,- payload,- };- let slot = out.entry(checkpoint_id).or_default();- // `merge_writes` keeps the shared dedupe semantics even here, where the- // primary key already guarantees uniqueness — one rule, one place.- merge_writes(slot, std::slice::from_ref(&write));- }- Ok(out)-}diff --git a/src/openhuman/flows/tinyflows/checkpoint_sqlite_tests.rs b/src/openhuman/flows/tinyflows/checkpoint_sqlite_tests.rsdeleted file mode 100644index c127741c1f..0000000000--- a/src/openhuman/flows/tinyflows/checkpoint_sqlite_tests.rs+++ /dev/null@@ -1,349 +0,0 @@-//! Coverage for the host-owned SQLite checkpointer.-//!-//! The port's whole value is that it is *not* new code: the durable flow-run-//! database predates it, and a run interrupted before the upgrade has to-//! resume after it. So the tests here are about equivalence and durability-//! rather than about the SQL — `schema_is_identical_to_the_backend_it_replaced`-//! is the load-bearing one, and the rest exercise the trait surface-//! `flows_run` / `flows_resume` actually drive.--use serde_json::json;-use tempfile::TempDir;-use tinyflows::graph::ids::NodeId;-use tinyflows::graph::{Checkpoint, CheckpointConfig, Checkpointer, PendingWrite};--use super::checkpoint_sqlite::SqliteCheckpointer;--/// One checkpoint in `thread`, at `step`, chained to `parent`.-fn checkpoint(- thread: &str,- id: &str,- parent: Option<&str>,- step: u64,- state: serde_json::Value,-) -> Checkpoint<serde_json::Value> {- Checkpoint {- thread_id: thread.to_string(),- checkpoint_id: id.to_string(),- run_id: Some("run-1".to_string()),- parent_checkpoint_id: parent.map(str::to_string),- namespace: Vec::new(),- state,- next_nodes: vec![NodeId::new("next")],- completed_tasks: vec![NodeId::new("done")],- pending_writes: Vec::new(),- interrupts: Vec::new(),- pending_activations: None,- barrier_arrivals: Vec::new(),- metadata: json!({ "source": "loop", "step": step }),- }-}--/// The reason this file exists. The port is a retarget of the backend-/// `tinyagents` shipped, and the two must agree on the bytes on disk: an-/// existing `<workspace>/flows/checkpoints.db` is read and written by this-/// code after the upgrade, and a divergence would surface as an interrupted-/// flow that cannot resume — at the worst possible moment, on a user's-/// machine, with the run already half-done.-///-/// Comparing the DDL is the cheapest total statement of that: same tables,-/// same columns, same primary keys, same indexes.-#[test]-fn schema_is_identical_to_the_backend_it_replaced() {- assert_eq!(- SqliteCheckpointer::<serde_json::Value>::schema_sql(),- tinyagents::graph::SqliteCheckpointer::<serde_json::Value>::schema_sql(),- "the ported schema drifted from the tinyagents backend that wrote every \- checkpoints.db in the field — an existing database would stop resuming"- );-}--/// A database written by the backend this replaced must be readable here, and-/// the schema check above is a statement about DDL rather than about-/// behaviour. This writes through the old type and reads back through the new-/// one, against one file.-#[tokio::test]-async fn reads_a_database_written_by_the_previous_backend() {- let tmp = TempDir::new().unwrap();- let db = tmp.path().join("checkpoints.db");-- // Fully qualified: the two `Checkpointer` traits share a method set, so- // importing both here would make every call in this file ambiguous.- use tinyagents::Checkpointer as LegacyCheckpointer;-- let old = tinyagents::graph::SqliteCheckpointer::<serde_json::Value>::open(&db).unwrap();- let written = tinyagents::graph::Checkpoint {- thread_id: "flow:f1:run-a".to_string(),- checkpoint_id: "cp-1".to_string(),- run_id: Some("run-1".to_string()),- parent_checkpoint_id: None,- namespace: Vec::new(),- state: json!({ "counter": 7 }),- next_nodes: vec![tinyagents::harness::ids::NodeId::new("next")],- completed_tasks: vec![tinyagents::harness::ids::NodeId::new("done")],- pending_writes: Vec::new(),- interrupts: Vec::new(),- pending_activations: None,- barrier_arrivals: Vec::new(),- metadata: json!({ "source": "loop", "step": 3 }),- };- LegacyCheckpointer::put(&old, written).await.unwrap();- drop(old);-- let new = SqliteCheckpointer::<serde_json::Value>::open(&db).unwrap();- let read = new- .get("flow:f1:run-a", None)- .await- .unwrap()- .expect("the pre-upgrade checkpoint must still load");- assert_eq!(read.checkpoint_id, "cp-1");- assert_eq!(read.state, json!({ "counter": 7 }));- assert_eq!(read.next_nodes, vec![NodeId::new("next")]);- assert_eq!(read.metadata["step"], 3);-}--/// `get(None)` is what resume calls, and "latest" has to mean latest by-/// insertion, not by id — the ids are opaque and nothing orders them.-#[tokio::test]-async fn get_without_an_id_returns_the_most_recently_written_checkpoint() {- let store = SqliteCheckpointer::<serde_json::Value>::in_memory().unwrap();- store- .put(checkpoint("t1", "cp-1", None, 1, json!({ "n": 1 })))- .await- .unwrap();- store- .put(checkpoint("t1", "cp-2", Some("cp-1"), 2, json!({ "n": 2 })))- .await- .unwrap();-- let latest = store.get("t1", None).await.unwrap().expect("latest");- assert_eq!(latest.checkpoint_id, "cp-2");- assert_eq!(latest.state, json!({ "n": 2 }));-- let addressed = store.get("t1", Some("cp-1")).await.unwrap().expect("cp-1");- assert_eq!(addressed.state, json!({ "n": 1 }));-- assert!(store.get("t1", Some("nope")).await.unwrap().is_none());- assert!(store.get("other-thread", None).await.unwrap().is_none());-}--/// Threads must not see each other: a flow run addresses its own thread id,-/// and one flow's checkpoints leaking into another's resume would replay the-/// wrong graph.-#[tokio::test]-async fn threads_are_isolated_and_listed_in_insertion_order() {- let store = SqliteCheckpointer::<serde_json::Value>::in_memory().unwrap();- store- .put(checkpoint("t1", "a", None, 1, json!(1)))- .await- .unwrap();- store- .put(checkpoint("t2", "b", None, 1, json!(2)))- .await- .unwrap();- store- .put(checkpoint("t1", "c", Some("a"), 2, json!(3)))- .await- .unwrap();-- let listed: Vec<String> = store- .list("t1")- .await- .unwrap()- .into_iter()- .map(|m| m.checkpoint_id)- .collect();- assert_eq!(listed, vec!["a".to_string(), "c".to_string()]);-- let mut threads = store.list_threads().await.unwrap();- threads.sort();- assert_eq!(threads, vec!["t1".to_string(), "t2".to_string()]);-}--/// A namespaced read is how a parent run and the sub-workflows it embeds stay-/// out of each other's checkpoints — they share a thread id and differ only-/// here.-#[tokio::test]-async fn scoped_reads_see_only_their_own_namespace() {- let store = SqliteCheckpointer::<serde_json::Value>::in_memory().unwrap();- let mut root = checkpoint("t1", "root-1", None, 1, json!("root"));- root.namespace = Vec::new();- let mut child = checkpoint("t1", "child-1", None, 1, json!("child"));- child.namespace = vec!["sub".to_string()];- store.put(root).await.unwrap();- store.put(child).await.unwrap();-- let scoped = store- .get_scoped("t1", None, &["sub".to_string()])- .await- .unwrap()- .expect("child checkpoint");- assert_eq!(scoped.state, json!("child"));-- let at_root = store- .get_scoped("t1", None, &[])- .await- .unwrap()- .expect("root checkpoint");- assert_eq!(at_root.state, json!("root"));-}--/// The partial-failure ledger, and its replace-vs-ignore rule — the thing in-/// this file most likely to be got subtly wrong, because both halves look like-/// "write it again".-///-/// A **data** write (`idx >= 0`) is append-once: a superstep that is retried-/// after a partial failure re-emits what it already emitted, and taking the-/// second copy would fold the same emission twice on resume. A-/// **control-plane** write (`idx < 0`, e.g. a resume value) legitimately-/// changes on a retry and must upsert. Both are pushed into SQL as two-/// conflict clauses rather than a read-then-write, so they stay correct under-/// concurrent writers.-#[tokio::test]-async fn data_writes_are_append_once_and_control_plane_writes_upsert() {- let store = SqliteCheckpointer::<serde_json::Value>::in_memory().unwrap();- store- .put(checkpoint("t1", "cp-1", None, 1, json!({})))- .await- .unwrap();- let config = CheckpointConfig {- thread_id: "t1".to_string(),- checkpoint_id: Some("cp-1".to_string()),- namespace: Vec::new(),- };-- // Data write, then the same (task_id, idx) again: the first value stands.- store- .put_writes(- &config,- &[PendingWrite::data("n1", "task-a", 0, "out", json!("first"))],- )- .await- .unwrap();- store- .put_writes(- &config,- &[PendingWrite::data(- "n1",- "task-a",- 0,- "out",- json!("second"),- )],- )- .await- .unwrap();-- let writes = store.get_writes(&config).await.unwrap();- assert_eq!(- writes.len(),- 1,- "a re-run task must not duplicate its write"- );- assert_eq!(- writes[0].payload,- json!("first"),- "a data write is append-once — a retry must not overwrite what already landed"- );-- // Control-plane write at the reserved resume index: the newest value wins.- let resume = |payload| {- PendingWrite::data(- "n1",- "task-a",- tinyflows::graph::checkpoint::WRITES_IDX_RESUME,- "__resume__",- payload,- )- };- store- .put_writes(&config, &[resume(json!("old"))])- .await- .unwrap();- store- .put_writes(&config, &[resume(json!("new"))])- .await- .unwrap();-- let writes = store.get_writes(&config).await.unwrap();- let control: Vec<_> = writes.iter().filter(|w| w.is_control_plane()).collect();- assert_eq!(- control.len(),- 1,- "control-plane writes are keyed, not appended"- );- assert_eq!(- control[0].payload,- json!("new"),- "a control-plane write must upsert — a resume value changes on a retry"- );-}--/// Deleting a thread is how a flow's history is dropped when the flow is-/// deleted; it must take that thread's writes with it and leave every other-/// thread alone.-#[tokio::test]-async fn deleting_a_thread_removes_its_checkpoints_and_leaves_others() {- let store = SqliteCheckpointer::<serde_json::Value>::in_memory().unwrap();- store- .put(checkpoint("doomed", "a", None, 1, json!(1)))- .await- .unwrap();- store- .put(checkpoint("kept", "b", None, 1, json!(2)))- .await- .unwrap();-- store.delete_thread("doomed").await.unwrap();-- assert!(store.get("doomed", None).await.unwrap().is_none());- assert!(store.list("doomed").await.unwrap().is_empty());- assert!(store.get("kept", None).await.unwrap().is_some());-}--/// Pruning bounds a long-running flow's history. It keeps the newest N, which-/// is the end resume reads from.-#[tokio::test]-async fn prune_keeps_the_newest_checkpoints() {- let store = SqliteCheckpointer::<serde_json::Value>::in_memory().unwrap();- for i in 1..=5 {- store- .put(checkpoint("t1", &format!("cp-{i}"), None, i, json!(i)))- .await- .unwrap();- }-- let removed = store.prune("t1", 2).await.unwrap();- assert_eq!(removed, 3);-- let remaining: Vec<String> = store- .list("t1")- .await- .unwrap()- .into_iter()- .map(|m| m.checkpoint_id)- .collect();- assert_eq!(remaining, vec!["cp-4".to_string(), "cp-5".to_string()]);-}--/// An in-memory database lives on its connection, so clones have to share one-/// — a clone that silently got its own empty database would be a resume that-/// finds nothing.-#[tokio::test]-async fn clones_share_one_in_memory_database() {- let store = SqliteCheckpointer::<serde_json::Value>::in_memory().unwrap();- let clone = store.clone();- store- .put(checkpoint(- "t1",- "cp-1",- None,- 1,- json!("written via original"),- ))- .await- .unwrap();-- let seen = clone.get("t1", None).await.unwrap().expect("shared data");- assert_eq!(seen.state, json!("written via original"));-}diff --git a/src/openhuman/flows/types.rs b/src/openhuman/flows/types.rsdeleted file mode 100644index 8778057419..0000000000--- a/src/openhuman/flows/types.rs+++ /dev/null@@ -1,637 +0,0 @@-//! The [`Flow`] entity: a saved automation workflow definition.-//!-//! Wraps `tinyflows::model::WorkflowGraph` with the metadata OpenHuman needs to-//! store, list, and track runs for a saved flow. The graph itself is the-//! portable, tinyflows-owned contract (validated + migrated on load); this-//! struct is the OpenHuman-side record around it.--use serde::{Deserialize, Serialize};-use serde_json::Value;-use tinyflows::model::WorkflowGraph;--/// How a flow run was started. Stamped onto the run's Langfuse trace as a-/// `trigger:<kind>` tag plus `trigger` metadata so runs can be filtered by-/// origin in the Langfuse UI.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum FlowRunTrigger {- /// An explicit run request over RPC/CLI (the Workflows UI "Run" button).- Rpc,- /// A `FlowScheduleTick` cron dispatch (`schedule` trigger node).- Schedule,- /// A `ComposioTriggerReceived` dispatch (`app_event` trigger node).- AppEvent,- /// A human-in-the-loop resume of a paused run (`flows_resume`).- Resume,-}--impl FlowRunTrigger {- /// Stable snake_case identifier used in Langfuse tags/metadata.- pub fn as_str(&self) -> &'static str {- match self {- FlowRunTrigger::Rpc => "rpc",- FlowRunTrigger::Schedule => "schedule",- FlowRunTrigger::AppEvent => "app_event",- FlowRunTrigger::Resume => "resume",- }- }-}--/// The result of validating a candidate `tinyflows` graph without persisting-/// it — returned by `openhuman.flows_validate` (PHASE 3c) and used to surface-/// structural errors and non-fatal warnings (e.g. "this trigger kind never-/// fires automatically yet") to an authoring surface *before* a flow is saved.-///-/// A graph is `valid` when it passes `tinyflows::validate::validate_all` after-/// migration; `errors` carries **every** structural error when it does not (a-/// pre-validation failure — unparseable JSON or an unmigrateable schema — is-/// still a single entry). `warnings` is orthogonal to validity — a `valid`-/// graph can still carry warnings (it saves and enables fine, it just won't-/// behave as an author might expect), and an invalid graph reports no warnings-/// (there's nothing to warn about a graph that won't compile).-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]-pub struct FlowValidation {- /// True when the graph is structurally valid (migrates + validates).- pub valid: bool,- /// Human-readable structural validation errors (empty when `valid`). As of- /// the multi-error work this carries **all** independent structural- /// problems in one pass — an author fixing five costs one validate call,- /// not five round-trips. See [`FlowValidation::error_details`] for the- /// machine-readable, per-node form.- pub errors: Vec<String>,- /// Structured, machine-readable counterpart to [`FlowValidation::errors`]:- /// one entry per structural error, carrying a stable `code`, the anchoring- /// `node_id` when node-specific, and the human `message`. Additive and- /// `#[serde(default)]` so existing clients that only read `errors` are- /// unaffected; agent tools and richer UIs consume this to attach errors to- /// the right node and switch on `code`.- #[serde(default, skip_serializing_if = "Vec::is_empty")]- pub error_details: Vec<FlowValidationError>,- /// Non-fatal warnings: the graph is accepted, but something about it is- /// worth flagging (e.g. an unfired trigger kind). Never blocks save/enable.- pub warnings: Vec<String>,-}--/// A single structural validation error in machine-readable form — the-/// structured counterpart to a [`FlowValidation::errors`] string.-///-/// Mirrors `tinyflows::error::ValidationError` (via its `code()` / `node_id()`-/// accessors) so a host surface can attach the error to a specific node and-/// switch on a stable `code` rather than parsing the `message`. `field` is-/// reserved for future config-level errors that can name the offending config-/// key; it is `None` for today's graph/edge-level checks.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]-pub struct FlowValidationError {- /// Stable, machine-readable identifier for the error kind (e.g.- /// `missing_trigger`, `unknown_node`, `invalid_condition_routing`).- pub code: String,- /// Human-readable description — identical to the matching- /// [`FlowValidation::errors`] string.- pub message: String,- /// The node id this error is anchored to, when node-specific; `None` for- /// graph-wide errors (missing trigger, schema-too-new, multiple triggers).- #[serde(default, skip_serializing_if = "Option::is_none")]- pub node_id: Option<String>,- /// The offending config field, when the error is config-key-specific.- /// Reserved for future use; `None` today.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub field: Option<String>,-}--/// The result of importing a workflow definition (native tinyflows JSON or an-/// n8n export) via `openhuman.flows_import` (PHASE 4d) — the normalized,-/// migrated + validated [`WorkflowGraph`] plus any non-fatal import warnings-/// (unmapped n8n node types, untranslated expressions, a synthesized/demoted-/// trigger, …).-///-/// **Import never persists.** This is the same contract as-/// [`FlowValidation`]: the graph comes back ready for the editable canvas as a-/// *draft*, and only the user's explicit Save (the existing `flows_create`-/// gate) writes it. A structurally invalid graph is reported as an `Err` on the-/// RPC (validation is authoritative), not as an `FlowImport` with `valid:-/// false` — there is no partial-import row.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-pub struct FlowImport {- /// The normalized workflow graph, migrated to the current schema and- /// structurally validated. Ready to open on the canvas as an unsaved draft.- pub graph: WorkflowGraph,- /// Non-fatal import warnings surfaced next to the draft. Empty for a clean- /// native import; an n8n import populates it with any approximations made.- pub warnings: Vec<String>,-}--/// A snapshot of a flow's graph captured just before an update overwrote it —-/// the safety rail behind `flows_rollback` / `get_flow_history` (audit F6).-///-/// Rows live in the `flow_revisions` table, capped (e.g. last 20 per flow).-/// `graph` is the prior graph as raw JSON so a snapshot never fails to load-/// even if the schema later evolves.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-pub struct FlowRevision {- /// Stable revision id (UUID).- pub id: String,- /// The flow this snapshot belongs to.- pub flow_id: String,- /// The flow's graph at the time this revision was captured (raw JSON).- pub graph: Value,- /// The flow's name at capture time.- pub name: String,- /// The flow's `require_approval` at capture time.- pub require_approval: bool,- /// RFC3339 time the snapshot was captured (i.e. when it was superseded).- pub created_at: String,-}--/// Where a [`FlowDraft`] came from — carried through so the UI can label a-/// draft and the agent can reason about it.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum DraftOrigin {- /// Created from a chat/copilot build turn.- Chat,- /// Created from the canvas (e.g. "new workflow", or an accepted proposal).- Canvas,- /// Created from an import (native tinyflows JSON or an n8n export).- Import,-}--impl DraftOrigin {- /// The serde wire discriminator, for logging.- pub fn as_str(&self) -> &'static str {- match self {- Self::Chat => "chat",- Self::Canvas => "canvas",- Self::Import => "import",- }- }-}--/// A durable, core-managed **draft** of a workflow graph — the shared working-/// copy the agent tools and the canvas both read/write across turns and reloads-/// (audit F5).-///-/// Stored as a plain JSON file on disk (`{workspace_dir}/flows/drafts/<id>.json`),-/// not in SQLite — trivially inspectable and deletable, no schema/migration.-/// A draft is **never live**: promoting it (`flows_draft_promote`) runs the-/// existing `flows_create`/`flows_update` gates (same forced `require_approval`-/// floor, same human-in-the-loop) and removes the file. `graph` is a raw JSON-/// value (not a typed `WorkflowGraph`) because a work-in-progress draft is-/// explicitly allowed to be incomplete or not-yet-valid.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-pub struct FlowDraft {- /// Stable draft id (UUID). Distinct from any `flow_id`.- pub id: String,- /// The saved flow this draft edits, if any. `None` for a from-scratch draft- /// (promote → `flows_create`); `Some` for an edit of an existing flow- /// (promote → `flows_update`).- #[serde(default, skip_serializing_if = "Option::is_none")]- pub flow_id: Option<String>,- /// Human-readable name carried into the flow on promote.- pub name: String,- /// The work-in-progress graph as raw JSON (may be incomplete/invalid).- pub graph: Value,- /// Where the draft originated.- pub origin: DraftOrigin,- /// RFC3339 creation time.- pub created_at: String,- /// RFC3339 last-update time.- pub updated_at: String,-}--/// A saved automation workflow: a `tinyflows` graph plus OpenHuman-side-/// bookkeeping (enablement, run history summary).-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct Flow {- /// Stable identifier (UUID) for this flow.- pub id: String,- /// Human-readable name shown in the Workflows UI.- pub name: String,- /// Whether this flow may currently be triggered (B2) / run.- pub enabled: bool,- /// The validated, migrated workflow graph.- pub graph: WorkflowGraph,- /// RFC3339 creation timestamp.- pub created_at: String,- /// RFC3339 last-update timestamp.- pub updated_at: String,- /// RFC3339 timestamp of the most recent run, if any.- pub last_run_at: Option<String>,- /// Outcome of the most recent run: `"completed"` | `"pending_approval"` | `"failed"`.- pub last_status: Option<String>,- /// "Require approval for outbound actions" (issue B2). When `true`, the- /// approval gate does NOT auto-allow this flow's `TrustedAutomation- /// { Workflow }` trust root — every external_effect tool/HTTP call the- /// flow makes still parks for a real decision, regardless of how the run- /// was triggered. See `src/openhuman/security/approval/gate.rs` and- /// `src/openhuman/agent/turn_origin.rs::TrustedAutomationSource::Workflow`.- #[serde(default)]- pub require_approval: bool,-}--/// One step of a persisted [`FlowRun`] (run-history inspector).-///-/// As of issue G2 (live run observation) these are persisted **incrementally**-/// as each non-trigger node finishes, by-/// `flows::observability::FlowRunObserver::on_step_finish`, which maps a live-/// `tinyflows::observability::ExecutionStep` (carrying real `status` +-/// `duration_ms`) onto this type. The prior post-hoc reconstruction from-/// `RunOutcome.output["nodes"]` (see `flows::ops::reconstruct_steps`) now only-/// fills in steps the observer missed (e.g. a trigger node, which does not-/// emit an `on_step_finish`) — those carry no `status`/`duration_ms` and keep-/// the `port` the reconstruction recovers.-#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]-pub struct FlowRunStep {- /// The node's id within the flow's graph.- pub node_id: String,- /// The node's emitted items for this run (`output["nodes"][id]["items"]`,- /// or the live `ExecutionStep.output` when observed incrementally).- pub output: serde_json::Value,- /// The output port the node routed on, if it picked one (branching /- /// switch nodes) — `output["nodes"][id]["port"]`. Only recovered by the- /// post-hoc reconstruction; the live observer does not carry a port.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub port: Option<String>,- /// Live step outcome, when this step was observed incrementally:- /// `"success"` | `"error"`. `None` for a step recovered post-hoc.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub status: Option<String>,- /// Wall-clock duration of the node's executor in milliseconds, when- /// observed incrementally. `None` for a step recovered post-hoc.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub duration_ms: Option<u64>,- /// Data-binding diagnostics from the engine: each config `=`-expression- /// that resolved to `null` during this step, as- /// `{ "location": "args.to", "expression": "=item.to" }`. Lets the run- /// view point at the exact unresolved wiring. Empty for clean steps and- /// for steps recovered post-hoc.- #[serde(default, skip_serializing_if = "Vec::is_empty")]- pub diagnostics: Vec<serde_json::Value>,-}--/// A resolvable connection the flows UI / agent picker can attach to a node's-/// `connection_ref`. Aggregated by `openhuman.flows_list_connections` from two-/// host-side sources:-///-/// - **Composio connected accounts** (`kind = "composio"`) — each active OAuth-/// integration instance, emitted as a ready-to-use-/// `"composio:<toolkit>:<connection_id>"` ref (the exact shape-/// `tinyflows::caps::composio_connection_id` parses back on execution).-/// - **Named HTTP credentials** (`kind = "http"`) — each stored injection-/// template, emitted as `"http_cred:<name>"` (the shape-/// `tinyflows::caps::http_cred_name` parses).-///-/// **Security contract:** carries only non-secret identity — the-/// `connection_ref` string plus a display label (and toolkit/scheme hints).-/// It NEVER carries secret material (OAuth tokens, bearer tokens, passwords,-/// API keys). Those stay server-side and are injected only inside the-/// `tinyflows::caps` adapters at execution time.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]-pub struct FlowConnection {- /// The ready-to-use `connection_ref` value to stamp onto a node:- /// `"composio:<toolkit>:<connection_id>"` or `"http_cred:<name>"`.- pub connection_ref: String,- /// Source kind: `"composio"` | `"http"`.- pub kind: String,- /// Human-readable label for the picker, e.g. `"Gmail · [email protected]"`- /// or `"stripe (bearer)"`. Never contains secret material.- pub display: String,- /// Composio toolkit slug (`kind = "composio"` only), e.g. `"gmail"`.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub toolkit: Option<String>,- /// HTTP credential injection scheme (`kind = "http"` only):- /// `"bearer"` | `"basic"` | `"header"`. Not a secret.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub scheme: Option<String>,- /// The connected account's own platform user id (`kind = "composio"`- /// only), e.g. Slack's `"U123ABC"` — resolved from the provider profile- /// synced via `SLACK_TEST_AUTH`/auth.test on connection sync (see- /// `memory_sync::composio::providers::profile::load_connected_identities`).- /// Non-secret identity metadata: lets the workflow builder wire a- /// self-targeted action (e.g. "DM me") to the user's own account instead- /// of guessing a public channel. `None` when no identity has synced yet.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub platform_user_id: Option<String>,-}--/// A persisted record of one `flows_run` / `flows_resume` invocation, for the-/// B3 run-history inspector. Written by `flows::store` from `flows::ops`.-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct FlowRun {- /// Stable identifier for this run — the same value as `thread_id` (the- /// tinyflows checkpointer key), so a run row can be found either way.- pub id: String,- /// The flow this run belongs to.- pub flow_id: String,- /// The tinyflows checkpointer thread id (needed to `flows_resume`).- pub thread_id: String,- /// Run status. Not an enum (kept a free-form `String` for forward-compat- /// with statuses added by newer builds), but the vocabulary is fixed:- /// `"running"` | `"completed"` | `"completed_with_warnings"` |- /// `"pending_approval"` | `"failed"` | `"cancelled"` (issue G4 — a run- /// cancelled via `flows_cancel_run`, or a parked `pending_approval` run- /// swept by the TTL expiry) | `"interrupted"` (bug B42 — a run whose future- /// was dropped mid-flight, reconciled either by the in-process- /// `RunRowFinalizer` drop-guard or the boot-time orphan sweep, so a- /// cancelled/timed-out/crashed run always settles to a terminal row instead- /// of wedging at `running`). `"completed_with_warnings"` (run honesty,- /// PR2) is a terminal status like `"completed"`, but at least one settled- /// [`FlowRunStep`] carries non-empty `diagnostics` (a `=`-binding that- /// resolved to `null`) even though no step outright errored. All of- /// `completed` / `completed_with_warnings` / `failed` / `cancelled` /- /// `interrupted` are terminal.- pub status: String,- /// RFC3339 timestamp when the run started.- pub started_at: String,- /// RFC3339 timestamp when the run last settled — stamped for every terminal- /// status (completed/paused/failed/cancelled/`"interrupted"`; the B42- /// drop-guard and boot sweep stamp it exactly like a normal terminal- /// write). `None` only while a run row is still `"running"`.- pub finished_at: Option<String>,- /// Reconstructed per-node steps (see [`FlowRunStep`]).- #[serde(default)]- pub steps: Vec<FlowRunStep>,- /// Node ids paused awaiting human approval when `status ==- /// "pending_approval"`; empty otherwise.- #[serde(default)]- pub pending_approvals: Vec<String>,- /// Human-readable failure reason. Set when `status == "failed"`, and also- /// when `status == "interrupted"` (bug B42) — there it carries the- /// reconciliation reason (tool abort / chat turn end / app restart) so the- /// run-details sidebar can explain *why* the run stopped instead of- /// rendering a bare terminal state.- #[serde(default)]- pub error: Option<String>,- /// Content hash of the graph this run was executing when it parked at- /// `status == "pending_approval"` (T-M1 — stale-approval guard). `None`- /// for a run that never parked, or for a row written before this pin- /// existed (a legacy `pending_approval` row) — `flows_resume` treats a- /// `None` on a currently-parked row as "unknown, allow with a warning"- /// rather than a hard refusal, so upgrading mid-park cannot strand an- /// in-flight approval. See `flows::ops::compute_graph_hash` and- /// `flows_resume`'s doc for the full mechanics.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub graph_hash: Option<String>,-}--/// Lifecycle status of a [`FlowSuggestion`] discovery card.-///-/// A freshly discovered suggestion starts `New`. The user can `Dismiss` it (it-/// stays persisted so a later discovery run can dedupe against it and won't-/// re-surface a rejected idea) or act on it — once the suggestion's flow is-/// actually saved via `flows_create`, the frontend marks it `Built`.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-#[derive(Default)]-pub enum SuggestionStatus {- /// Freshly discovered, awaiting the user's decision. The default.- #[default]- New,- /// The user dismissed the card; kept for dedupe, never re-surfaced.- Dismissed,- /// The user built (saved) a flow from this suggestion.- Built,-}--impl SuggestionStatus {- /// The stable lowercase token persisted in SQLite / crossed over RPC.- pub fn as_str(self) -> &'static str {- match self {- Self::New => "new",- Self::Dismissed => "dismissed",- Self::Built => "built",- }- }-- /// Parse a persisted/RPC token back into a status. Unknown tokens fall- /// back to [`SuggestionStatus::New`] (forward-compatible with any status a- /// newer build might persist), so a stale row never hard-errors a read.- pub fn from_str_lossy(s: &str) -> Self {- match s {- "dismissed" => Self::Dismissed,- "built" => Self::Built,- _ => Self::New,- }- }-}--/// A concrete, buildable workflow idea proposed by the `flow_discovery` agent-/// (the "Flow Scout"). Persisted to the `flow_suggestions` table and surfaced-/// as a card in the Flows page "Suggested for you" section.-///-/// **Not a graph.** A suggestion is a *pitch* the user can accept, not a-/// validated [`WorkflowGraph`]. Its [`Self::build_prompt`] is the natural-language-/// brief handed to the `workflow_builder` agent when the user clicks "Build-/// this"; that agent turns it into a real graph proposal for the user to save.-/// This keeps the discovery agent read-only and the authoring pipeline unchanged.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-pub struct FlowSuggestion {- /// Stable identifier (a content hash of the normalized title, so re-running- /// discovery dedupes identical ideas rather than piling duplicates).- pub id: String,- /// Short, human-friendly title, e.g. `"Auto-file email receipts"`.- pub title: String,- /// One-sentence description of what the workflow would do, e.g.- /// `"When a Gmail receipt arrives, add a row to your expenses sheet."`- pub one_liner: String,- /// Why this is being suggested to *this* user — grounded in what the agent- /// observed (a recurring thread, a stated goal in memory, a connected app),- /// e.g. `"You forward receipts to yourself most weeks."`- pub rationale: String,- /// Which trigger the workflow would likely use, as a hint for the card and- /// the builder: `"schedule"` | `"app_event"` | `"manual"` (free-form; only- /// those three self-fire in this host).- #[serde(default, skip_serializing_if = "Option::is_none")]- pub trigger_hint: Option<String>,- /// Plain-language outline of the steps, one per element, e.g.- /// `["Watch Gmail for receipts", "Extract amount + vendor", "Append a Sheet row"]`.- #[serde(default)]- pub steps_outline: Vec<String>,- /// `connection_ref` values the agent grounded against real- /// `flows_list_connections` output (never invented), so the card can show- /// "uses your Gmail" and the builder can stamp them verbatim.- #[serde(default)]- pub suggested_connections: Vec<String>,- /// Real Composio action slugs the agent grounded via `search_tool_catalog`- /// (never hallucinated). Empty when the workflow is HTTP/agent-only.- #[serde(default)]- pub suggested_slugs: Vec<String>,- /// The natural-language brief handed to `workflow_builder` on "Build this".- /// Self-contained: trigger + steps + connections, enough for the builder to- /// author a graph without re-deriving the idea.- pub build_prompt: String,- /// Agent's self-rated confidence in `[0.0, 1.0]` that this is a genuinely- /// useful, buildable automation for the user — used to rank cards.- #[serde(default)]- pub confidence: f64,- /// Lifecycle status (see [`SuggestionStatus`]).- #[serde(default)]- pub status: SuggestionStatus,- /// RFC3339 timestamp when the suggestion was first discovered.- pub created_at: String,- /// The `flows_discover` run that produced this suggestion (correlation for- /// observability); `None` for suggestions authored outside a tracked run.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub source_run_id: Option<String>,-}--#[cfg(test)]-mod tests {- use super::*;- use tinyflows::model::{Node, NodeKind};-- fn sample_graph() -> WorkflowGraph {- WorkflowGraph {- nodes: vec![Node {- id: "t".to_string(),- kind: NodeKind::Trigger,- type_version: 1,- name: "Trigger".to_string(),- config: serde_json::Value::Null,- ports: Vec::new(),- position: None,- }],- ..Default::default()- }- }-- #[test]- fn flow_round_trips_through_json() {- let flow = Flow {- id: "flow_1".to_string(),- name: "demo".to_string(),- enabled: true,- graph: sample_graph(),- created_at: "2026-01-01T00:00:00Z".to_string(),- updated_at: "2026-01-01T00:00:00Z".to_string(),- last_run_at: None,- last_status: None,- require_approval: false,- };- let json = serde_json::to_string(&flow).expect("serialize");- let back: Flow = serde_json::from_str(&json).expect("deserialize");- assert_eq!(back.id, flow.id);- assert_eq!(back.graph, flow.graph);- assert!(back.last_run_at.is_none());- assert!(!back.require_approval);- }-- #[test]- fn flow_require_approval_defaults_false_when_omitted_from_json() {- // Legacy/serialized JSON authored before the field existed must still- // deserialize (SQLite rows are migrated via `add_column_if_missing`,- // but any bare JSON fixture should also default safely).- let json = serde_json::json!({- "id": "flow_1",- "name": "demo",- "enabled": true,- "graph": sample_graph(),- "created_at": "2026-01-01T00:00:00Z",- "updated_at": "2026-01-01T00:00:00Z",- });- let flow: Flow = serde_json::from_value(json).expect("deserialize");- assert!(!flow.require_approval);- }-- #[test]- fn flow_run_round_trips_through_json() {- let run = FlowRun {- id: "flow:flow_1:run-uuid".to_string(),- flow_id: "flow_1".to_string(),- thread_id: "flow:flow_1:run-uuid".to_string(),- status: "completed".to_string(),- started_at: "2026-01-01T00:00:00Z".to_string(),- finished_at: Some("2026-01-01T00:00:01Z".to_string()),- steps: vec![FlowRunStep {- node_id: "t".to_string(),- output: serde_json::json!([{"json": {"hello": "world"}}]),- port: None,- ..Default::default()- }],- pending_approvals: Vec::new(),- error: None,- graph_hash: None,- };- let json = serde_json::to_string(&run).expect("serialize");- let back: FlowRun = serde_json::from_str(&json).expect("deserialize");- assert_eq!(back.id, run.id);- assert_eq!(back.steps.len(), 1);- assert_eq!(back.steps[0].node_id, "t");- assert!(back.steps[0].port.is_none());- }-- #[test]- fn flow_run_step_omits_port_when_none() {- let step = FlowRunStep {- node_id: "n".to_string(),- output: serde_json::Value::Null,- port: None,- ..Default::default()- };- let v = serde_json::to_value(&step).unwrap();- assert!(v.get("port").is_none());- }-- #[test]- fn suggestion_status_token_round_trips() {- for st in [- SuggestionStatus::New,- SuggestionStatus::Dismissed,- SuggestionStatus::Built,- ] {- assert_eq!(SuggestionStatus::from_str_lossy(st.as_str()), st);- }- // Unknown tokens fall back to New rather than erroring.- assert_eq!(- SuggestionStatus::from_str_lossy("something_new"),- SuggestionStatus::New- );- assert_eq!(SuggestionStatus::default(), SuggestionStatus::New);- }-- #[test]- fn flow_suggestion_round_trips_through_json() {- let s = FlowSuggestion {- id: "sug_abc".to_string(),- title: "Auto-file email receipts".to_string(),- one_liner: "When a Gmail receipt arrives, add a row to your expenses sheet."- .to_string(),- rationale: "You forward receipts to yourself most weeks.".to_string(),- trigger_hint: Some("app_event".to_string()),- steps_outline: vec![- "Watch Gmail for receipts".to_string(),- "Extract amount + vendor".to_string(),- ],- suggested_connections: vec!["composio:gmail:conn_1".to_string()],- suggested_slugs: vec!["GMAIL_NEW_GMAIL_MESSAGE".to_string()],- build_prompt: "Build a workflow that…".to_string(),- confidence: 0.82,- status: SuggestionStatus::New,- created_at: "2026-07-05T00:00:00Z".to_string(),- source_run_id: Some("run-1".to_string()),- };- let json = serde_json::to_string(&s).expect("serialize");- let back: FlowSuggestion = serde_json::from_str(&json).expect("deserialize");- assert_eq!(back, s);- }-- #[test]- fn flow_suggestion_defaults_optional_fields() {- // A minimal pitch (no trigger/steps/connections/slugs/status/run) must- // deserialize with safe defaults.- let json = serde_json::json!({- "id": "sug_min",- "title": "Daily digest",- "one_liner": "Summarize your unread mail each morning.",- "rationale": "You check mail first thing.",- "build_prompt": "Build a scheduled digest…",- "created_at": "2026-07-05T00:00:00Z",- });- let s: FlowSuggestion = serde_json::from_value(json).expect("deserialize");- assert!(s.trigger_hint.is_none());- assert!(s.steps_outline.is_empty());- assert!(s.suggested_connections.is_empty());- assert!(s.suggested_slugs.is_empty());- assert_eq!(s.confidence, 0.0);- assert_eq!(s.status, SuggestionStatus::New);- assert!(s.source_run_id.is_none());- }-}