Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore: files changed crates/openhuman-core/src/flows/ops/resume.rs,crates/openhuman-core/src/flows/o

Steven Enamakel0f482b08e1f8
diff --git a/crates/openhuman-core/src/flows/ops/resume.rs b/crates/openhuman-core/src/flows/ops/resume.rs
index fe2f147c35..9e9263a0d8 100644
--- a/crates/openhuman-core/src/flows/ops/resume.rs
+++ b/crates/openhuman-core/src/flows/ops/resume.rs
@@ -462,88 +462,13 @@ pub async fn flows_resume(
))
}
-/// Computes a stable content hash of the flow configuration a run was approved
-/// against — the T-M1 stale-approval guard (see `flows_resume`'s doc).
-/// Persisted on a run row the moment it parks at `pending_approval`, and
-/// recompared against the **current** flow before a resume is allowed to
-/// execute, so a rewrite between park and resume is detected instead of
-/// silently firing the new configuration under the old approval.
-///
-/// Covers the graph **and `require_approval`**. The flag is not cosmetic: it
-/// feeds `workflow_origin(...)`, which becomes the `AgentTurnOrigin` for the
-/// whole resumed execution, and `TrustedAutomationSource::Workflow {
-/// require_approval: false }` **auto-allows every `external_effect` tool call**
-/// where `true` parks each one for its own human decision. It is also settable
-/// independently of the graph — `flows_update(.., graph_json: None,
-/// require_approval: Some(false), ..)` leaves `.graph` byte-identical. Hashing
-/// the graph alone would therefore leave the exact hole this guard exists to
-/// close: park at a gate, user approves, the flag is flipped to `false` with the
-/// graph untouched (pin still matches), and on resume every downstream
-/// outbound node that would have parked now fires unattended.
-///
-/// Hashes a *canonicalized* JSON serialization — `serde_json::Value`'s object
-/// map preserves insertion order in this crate (the `preserve_order` feature
-/// is enabled transitively via other dependencies), so the same logical graph
-/// serialized through two different code paths is not guaranteed to emit its
-/// object keys in the same order. [`canonicalize_json`] recursively sorts
-/// every object's keys before hashing so the hash depends only on graph
-/// content, never on incidental key order. Returns `None` (never panics) if
-/// the graph somehow fails to serialize.
-///
-/// **`None` means different things on the two sides, and the resume side fails
-/// CLOSED.** At park time `None` simply stores no pin, so that run later takes
-/// the legacy "unknown — allow, with a warning" path. At resume time the
-/// comparison is `Some(expected) != None`, which is *true*, so a hash failure
-/// is treated as a mismatch: the run is refused, settled terminally, and its
-/// checkpoint dropped. That is the safer direction — a run whose current graph
-/// cannot be hashed is a run whose approval cannot be verified — but it is the
-/// opposite of fail-open, so do not read this as a guarantee that a serialize
-/// failure leaves a resumable run resumable.
-pub(super) fn compute_graph_hash(graph: &WorkflowGraph, require_approval: bool) -> Option<String> {
- let raw = match serde_json::to_value(graph) {
- Ok(v) => v,
- Err(e) => {
- tracing::warn!(
- target: "flows",
- error = %e,
- "[flows] compute_graph_hash: failed to serialize graph to JSON — proceeding without a graph pin"
- );
- return None;
- }
- };
- let raw = serde_json::json!({ "graph": raw, "require_approval": require_approval });
- let canonical = canonicalize_json(&raw);
- let serialized = match serde_json::to_string(&canonical) {
- Ok(s) => s,
- Err(e) => {
- tracing::warn!(
- target: "flows",
- error = %e,
- "[flows] compute_graph_hash: failed to serialize canonicalized graph — proceeding without a graph pin"
- );
- return None;
- }
- };
- let digest = Sha256::digest(serialized.as_bytes());
- Some(hex::encode(digest))
-}
-
-/// Recursively rewrites every JSON object's keys into sorted order, leaving
-/// arrays (whose element order is semantically meaningful) and scalars
-/// unchanged. See [`compute_graph_hash`] for why this is needed before
-/// hashing rather than trusting `serde_json`'s default map order.
-fn canonicalize_json(value: &Value) -> Value {
- match value {
- Value::Object(map) => {
- let mut keys: Vec<&String> = map.keys().collect();
- keys.sort();
- let mut sorted = serde_json::Map::new();
- for key in keys {
- sorted.insert(key.clone(), canonicalize_json(&map[key]));
- }
- Value::Object(sorted)
- }
- Value::Array(items) => Value::Array(items.iter().map(canonicalize_json).collect()),
- other => other.clone(),
- }
-}
+// The T-M1 stale-approval guard's content pin. Persisted on a run row the moment
+// it parks at `pending_approval` and recompared against the **current** flow
+// before a resume executes (see `flows_resume`'s doc), so a rewrite between park
+// and resume is detected instead of silently firing the new configuration under
+// the old approval. It covers the graph AND `require_approval`: the flag becomes
+// the `AgentTurnOrigin` for the whole resumed execution and `false` auto-allows
+// every `external_effect` tool call, and it is settable without touching the
+// graph. The algorithm and its fixed-vector test live in `tinyflows-catalog`
+// because the digest is a persisted format.
+pub(super) use tinyflows_catalog::graph_hash::compute_graph_hash;
diff --git a/crates/openhuman-core/src/flows/ops/trail_off.rs b/crates/openhuman-core/src/flows/ops/trail_off.rs
index 4aee9f7d08..8522a2f8ee 100644
--- a/crates/openhuman-core/src/flows/ops/trail_off.rs
+++ b/crates/openhuman-core/src/flows/ops/trail_off.rs
@@ -1,166 +1,9 @@
use super::*;
-/// Heuristic: does `text` already contain a clear, answerable question in its
-/// final paragraph? Conservative by design (issue: builder convergence) — a
-/// false negative (an actual question this misses) no longer discards the
-/// model's text (see `combine_trail_off_fallback`), so the safe failure mode
-/// stays "add a guaranteed question on top", never "under-detect and stay
-/// silent".
-///
-/// Regression (#4887 follow-up): the original version only checked for a `?`
-/// at the very end of the text / last line, which false-negatived on the
-/// extremely common LLM pattern "What's X? You can find it at Y." — a real
-/// question immediately followed by a trailing instructional sentence. The
-/// backstop then clobbered a specific, answerable question with a generic
-/// fallback. To catch that shape, this now also scans the LAST non-empty
-/// paragraph for a `?` that isn't inside inline code or a fenced code block
-/// (so a literal `?` in a code sample, e.g. `WHERE id = ?`, doesn't count).
-///
-/// Note: the trailing-noise strip below deliberately does NOT include the
-/// backtick. Stripping a trailing backtick would peel off the CLOSING
-/// delimiter of a code span whose last character is `?` (e.g. `` `id = ?` ``
-/// at the very end of the text), exposing that `?` as if it were a bare
-/// trailing question mark and defeating the code guard entirely.
-pub(super) fn text_looks_like_question(text: &str) -> bool {
- let trimmed = text
- .trim()
- .trim_end_matches(['"', '\'', ')', ']', '*', '_', '.'])
- .trim_end();
- if trimmed.is_empty() {
- return false;
- }
- if trimmed.ends_with('?') {
- return true;
- }
- // The question may not be the literal last character (trailing markdown
- // like a closing code fence or list marker on its own line) — fall back
- // to the last non-blank line.
- if trimmed
- .lines()
- .rfind(|line| !line.trim().is_empty())
- .is_some_and(|last_line| last_line.trim_end().ends_with('?'))
- {
- return true;
- }
- // Final-paragraph scan: a question can sit mid-paragraph, followed by a
- // further trailing sentence on the SAME line/paragraph ("...ID? You can
- // find it under Profile > Copy member ID."). Take the last non-blank
- // paragraph and accept it if it contains a `?` that isn't inside inline
- // code / a code fence.
- last_paragraph(trimmed)
- .as_deref()
- .is_some_and(question_mark_outside_code)
-}
-
-/// Returns the last non-blank paragraph of `text` — a maximal run of
-/// consecutive non-blank lines, working backward from the end and skipping
-/// any trailing blank lines first. `None` if `text` has no non-blank lines.
-///
-/// CodeRabbit review follow-up: this used to split on the literal `"\n\n"`
-/// byte sequence, which mishandles two real shapes:
-/// - **CRLF input** (`"question?\r\n\r\nstatus"`): the separator is
-/// `"\r\n\r\n"`, not `"\n\n"`, so the whole text was treated as ONE
-/// paragraph — an earlier question could then suppress the fallback for a
-/// trailing non-question status paragraph.
-/// - **Whitespace-only separator lines** (`"question?\n \nstatus"` — a blank
-/// line that isn't perfectly empty): same failure, same reason.
-///
-/// Working line-by-line via [`str::lines`] (which normalizes CRLF) and
-/// treating any all-whitespace line as blank fixes both.
-fn last_paragraph(text: &str) -> Option<String> {
- let mut collected: Vec<&str> = Vec::new();
- for line in text.lines().rev() {
- if line.trim().is_empty() {
- if collected.is_empty() {
- continue; // still skipping trailing blank lines
- }
- break; // blank line marks the start of the paragraph above
- }
- collected.push(line);
- }
- if collected.is_empty() {
- return None;
- }
- collected.reverse();
- Some(collected.join("\n"))
-}
-
-/// Does `text` contain at least one *sentence-terminal* `?` that isn't
-/// inside a backtick-delimited code span (inline code like `` `U...` `` or a
-/// fenced block like `` ``` ``)? Follows the CommonMark code-span rule: a
-/// *run* of one or more consecutive backticks opens a span, and that span is
-/// closed only by the next run of the SAME length — a shorter or longer run
-/// of backticks encountered while inside a span is just literal backtick
-/// characters, not a delimiter.
-///
-/// CodeRabbit review follow-up: an earlier version tracked a running
-/// per-character backtick COUNT and used its parity (even = outside code).
-/// That misclassifies any multi-backtick span whose delimiter is more than
-/// one backtick — e.g. ``` ``SELECT ? FROM t`` ``` opens with a 2-backtick
-/// run (count 0→2, even → looks "outside" again immediately), so the `?`
-/// inside a valid double-backtick span was wrongly treated as outside code.
-/// Tracking delimiter run LENGTH (not raw backtick count) fixes this while
-/// still handling the common single-backtick and triple-backtick-fence
-/// cases, since those are just the run-length-1 and run-length-3 instances
-/// of the same rule.
-///
-/// Codex review follow-up: a bare `?` outside code isn't necessarily a real
-/// question — a status line like "Checked https://api.example/search?q=foo
-/// and got 403." has one mid-token, in a URL query string. Counting that
-/// would flip `text_looks_like_question` to `true` and skip
-/// `combine_trail_off_fallback` entirely, leaving the user with an
-/// unanswerable status note — exactly the failure mode this backstop exists
-/// to prevent. So each candidate `?` is additionally required to be
-/// sentence-terminal via [`is_sentence_terminal_question_mark`].
-pub(super) fn question_mark_outside_code(text: &str) -> bool {
- let chars: Vec<char> = text.chars().collect();
- // `Some(n)` while scanning is inside a code span opened by a run of `n`
- // backticks; that span closes only on the next run of exactly `n`.
- let mut open_run_len: Option<usize> = None;
- let mut i = 0;
- while i < chars.len() {
- if chars[i] == '`' {
- let start = i;
- while i < chars.len() && chars[i] == '`' {
- i += 1;
- }
- let run_len = i - start;
- open_run_len = match open_run_len {
- None => Some(run_len),
- Some(n) if n == run_len => None,
- Some(n) => Some(n), // mismatched run length: still inside the span
- };
- continue;
- }
- if chars[i] == '?'
- && open_run_len.is_none()
- && is_sentence_terminal_question_mark(&chars, i)
- {
- return true;
- }
- i += 1;
- }
- false
-}
-
-/// Is the `?` at `chars[index]` sentence-terminal — i.e. does it read as an
-/// actual question mark rather than a character that merely happens to be a
-/// `?` mid-token (a URL query string like `search?q=foo`, a shell glob,
-/// etc.)? Skips over any immediately-following closing quote/bracket
-/// punctuation (`"`, `'`, right single/double quotes, `)`, `]`) and requires
-/// what remains to be whitespace or the end of the text — the shape a `?`
-/// takes at the end of a real sentence or clause.
-fn is_sentence_terminal_question_mark(chars: &[char], index: usize) -> bool {
- let mut i = index + 1;
- while let Some(&c) = chars.get(i) {
- if matches!(c, '"' | '\'' | '\u{2019}' | '\u{201D}' | ')' | ']') {
- i += 1;
- continue;
- }
- return c.is_whitespace();
- }
- true // '?' was the last character in the paragraph.
-}
+// The pure text heuristics (`text_looks_like_question` and the code-span / URL /
+// paragraph checks under it) live in `tinyflows-copilot`; what stays here needs
+// the host's `ConversationMessage` history and tool names.
+pub(super) use tinyflows_copilot::text_looks_like_question;
/// Builder-authoring tools whose result body can explain a trail-off — the
/// authoring belt `dry_run_workflow`/`validate_workflow`/`propose_workflow`/
diff --git a/crates/openhuman-core/src/flows/ops/validation.rs b/crates/openhuman-core/src/flows/ops/validation.rs
index d5caf4841f..b0727427c6 100644
--- a/crates/openhuman-core/src/flows/ops/validation.rs
+++ b/crates/openhuman-core/src/flows/ops/validation.rs
@@ -94,95 +94,11 @@ pub(super) fn ensure_config_aware_engine_compatible(
}
/// Runs a raw graph JSON value through migration + deserialization **without**
-/// the structural `validate` step. Splits the two so a caller that wants
-/// *every* structural error (via `tinyflows::validate::validate_all`) can run
-/// validation itself — a pre-validation failure here (unparseable JSON, an
-/// unmigrateable schema) is genuinely a single error, whereas structural
-/// validation can surface many at once.
-pub(crate) fn migrate_and_deserialize_graph(graph_json: Value) -> Result<WorkflowGraph, String> {
- let migrated = tinyflows::migrate::migrate(graph_json).map_err(|e| e.to_string())?;
- // `serde_json` errors carry no path, and `missing field `name`` on its own
- // is unactionable here: every field of `WorkflowGraph` is
- // `#[serde(default)]`, so the fault is always in a nested object -- and an
- // agent that reads it as the top-level `name` it already set will retry
- // unchanged until it exhausts its iteration cap.
- serde_json::from_value::<WorkflowGraph>(migrated.clone())
- .map_err(|e| locate_graph_error(&migrated, &e))
-}
-
-/// The `WorkflowGraph` fields whose elements carry their own required fields.
-const ELEMENT_ARRAYS: &[&str] = &["nodes", "inputs", "agents", "edges"];
-
-/// Names the element a graph-level deserialization error came from.
-///
-/// Re-deserializes each member of the arrays that carry required fields and
-/// reports the first that fails on its own, as `nodes[1]: <serde error>`. None
-/// of these types use `deny_unknown_fields`, so an element that parses in
-/// isolation is one the graph-level parse accepted too, and a failure found
-/// here is the real fault rather than an artefact of checking it alone.
-///
-/// Runs only on the error path, and falls back to the bare message when the
-/// fault is not in a single element -- a wrong type for `nodes` itself, say.
-fn locate_graph_error(migrated: &Value, err: &serde_json::Error) -> String {
- // Re-parse with the element arrays emptied. If that still fails, the fault
- // is in the graph's own fields -- a non-string `name`, say -- and scanning
- // members would pin it on the first member that happens to be invalid too,
- // which is a confident wrong answer rather than a vague right one.
- let mut skeleton = migrated.clone();
- if let Some(fields) = skeleton.as_object_mut() {
- for field in ELEMENT_ARRAYS {
- if let Some(slot) = fields.get_mut(*field) {
- *slot = Value::Array(Vec::new());
- }
- }
- }
- if serde_json::from_value::<WorkflowGraph>(skeleton).is_err() {
- return locate_top_level_error(migrated, err);
- }
-
- macro_rules! locate {
- ($field:literal, $ty:ty) => {
- if let Some(items) = migrated.get($field).and_then(Value::as_array) {
- for (index, item) in items.iter().enumerate() {
- if let Err(inner) = serde_json::from_value::<$ty>(item.clone()) {
- return format!("{}[{}]: {}", $field, index, inner);
- }
- }
- }
- };
- }
-
- locate!("nodes", tinyflows::model::Node);
- locate!("inputs", tinyflows::model::WorkflowInput);
- locate!("agents", tinyflows::model::AgentDefinition);
- locate!("edges", tinyflows::model::Edge);
-
- err.to_string()
-}
-
-/// Names the graph's own field when the fault is at the top level.
-///
-/// `serde_json` reports a type mismatch as `invalid type: integer \`123\`,
-/// expected a string` with **no field name** -- the same unactionable shape as
-/// the missing-field case this helper exists to fix, so it gets the same
-/// treatment.
-///
-/// Every `WorkflowGraph` field is `#[serde(default)]`, so an object carrying a
-/// single field parses if and only if that field is valid. Probing one key at a
-/// time therefore names the offender without a hardcoded field list. Unknown
-/// keys parse (no `deny_unknown_fields`) and are skipped.
-fn locate_top_level_error(migrated: &Value, err: &serde_json::Error) -> String {
- if let Some(fields) = migrated.as_object() {
- for (key, value) in fields {
- let probe = Value::Object([(key.clone(), value.clone())].into_iter().collect());
- if let Err(inner) = serde_json::from_value::<WorkflowGraph>(probe) {
- return format!("{key}: {inner}");
- }
- }
- }
-
- err.to_string()
-}
+/// the structural `validate` step, attributing a deserialization failure to the
+/// member that caused it (`nodes[1]: missing field ...`). The implementation is
+/// `tinyflows::migrate::deserialize_graph`; this alias keeps the host's
+/// call sites (and the authoring tools' error text) unchanged.
+pub(crate) use tinyflows::migrate::deserialize_graph as migrate_and_deserialize_graph;
/// Maps a portable `tinyflows` [`ValidationError`](tinyflows::error::ValidationError)
/// into the host's structured [`FlowValidationError`], carrying its stable
diff --git a/crates/openhuman-core/src/flows/ops_builder_trail_off_tests.rs b/crates/openhuman-core/src/flows/ops_builder_trail_off_tests.rs
index 92e90d85b7..568c06c051 100644
--- a/crates/openhuman-core/src/flows/ops_builder_trail_off_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_builder_trail_off_tests.rs
@@ -223,145 +223,6 @@ fn extract_workflow_proposal_ignores_non_proposal_tool_results() {
assert!(extract_workflow_proposal(&history).is_none());
}
-#[test]
-fn text_looks_like_question_detects_trailing_question_mark() {
- assert!(text_looks_like_question(
- "Which Slack channel should I post to?"
- ));
- assert!(text_looks_like_question("Which channel?\n"));
- // Trailing markdown/punctuation noise after the '?' shouldn't defeat it.
- assert!(text_looks_like_question("Which channel should I use?\""));
- // A trailing blank line after the question is still detected (the last
- // NON-BLANK line is what's checked).
- assert!(text_looks_like_question(
- "Which channel should I post to?\n\n"
- ));
-}
-
-/// Regression (#4887 follow-up): a question immediately followed by a
-/// trailing pleasantry/instruction in the SAME paragraph ("...to? Let me
-/// know!") used to be an accepted false negative. That false negative let the
-/// trail-off backstop clobber real, specific questions with a generic
-/// fallback — this is now DETECTED via the final-paragraph scan in
-/// `text_looks_like_question`.
-///
-/// Note: a question mark separated from the trailing sentence by a full
-/// blank-line paragraph break (`"...to?\n\nLet me know!"`) is a DIFFERENT
-/// shape — the `?` there sits in an earlier paragraph, not the last one — and
-/// remains an intentional false negative: the final-paragraph scan only
-/// looks at the LAST non-blank paragraph, by design (see the function doc
-/// and `text_looks_like_question_ignores_question_mark_in_earlier_paragraph`
-/// below, which pins that scope decision).
-#[test]
-fn text_looks_like_question_detects_same_paragraph_trailing_pleasantry() {
- assert!(text_looks_like_question(
- "Which channel should I post to? Let me know!"
- ));
-}
-
-/// Pins the intentional cross-paragraph false negative documented above: a
-/// `?` that sits in an EARLIER paragraph than the last one is deliberately
-/// NOT detected — the final-paragraph scan only looks at the last non-blank
-/// paragraph, by design. This is harmless because the trail-off backstop's
-/// fallback is non-destructive (PREPEND, not REPLACE): even when this false
-/// negative fires, the model's original question is preserved below the
-/// fallback rather than discarded.
-#[test]
-fn text_looks_like_question_ignores_question_mark_in_earlier_paragraph() {
- assert!(!text_looks_like_question(
- "Which channel should I post to?\n\nLet me know!"
- ));
-}
-
-/// The exact shape a live tester hit (#4887 regression): a clear, specific
-/// question mid-sentence, immediately followed by a trailing instructional
-/// sentence on the SAME paragraph/line. The old last-line-only check missed
-/// this entirely; the final-paragraph scan must catch it.
-#[test]
-fn text_looks_like_question_detects_mid_sentence_question_with_trailing_instruction() {
- assert!(text_looks_like_question(
- "Alan — what's your **Slack user ID** (the `U...` code) so I can DM you the daily \
- update? You can find it in Slack under Profile > Copy member ID."
- ));
-}
-
-/// A `?` that only appears inside inline code or a fenced code block must
-/// NOT be treated as a question — the guard on `question_mark_outside_code`
-/// has to hold, or a code sample like `WHERE id = ?` would false-positive.
-#[test]
-fn text_looks_like_question_ignores_question_mark_inside_code() {
- assert!(!text_looks_like_question(
- "Run the query below to check the row.\n\n`SELECT * FROM t WHERE id = ?`"
- ));
- assert!(!text_looks_like_question(
- "Here's the query:\n\n```sql\nSELECT * FROM t WHERE id = ?\n```"
- ));
-}
-
-/// Codex review follow-up: a `?` mid-token that isn't a real question mark —
-/// e.g. a URL query string in a status update — must NOT flip
-/// `text_looks_like_question` to `true`. Counting it would make `flows_build`
-/// skip `combine_trail_off_fallback` entirely, leaving the user with an
-/// unanswerable status note and no guaranteed question — exactly the failure
-/// mode this backstop exists to prevent.
-#[test]
-fn text_looks_like_question_ignores_question_mark_in_url_query_string() {
- assert!(!text_looks_like_question(
- "Checked https://api.example/search?q=foo and got 403."
- ));
- assert!(!text_looks_like_question(
- "Ran the search with filter?status=open but the API rejected it."
- ));
-}
-
-/// CodeRabbit review follow-up: paragraph boundaries must be recognized for
-/// CRLF line endings and whitespace-only blank lines, not just a literal
-/// `"\n\n"` byte sequence — otherwise an earlier question survives into what
-/// should be treated as a separate, later, non-question status paragraph,
-/// and the fallback gets wrongly suppressed for that trailing paragraph.
-#[test]
-fn text_looks_like_question_treats_crlf_and_whitespace_lines_as_paragraph_breaks() {
- // CRLF paragraph break: the earlier "?" must not leak into the final
- // paragraph, which is a plain status line with no question of its own.
- assert!(!text_looks_like_question(
- "Which channel should I post to?\r\n\r\nPosted the update just now."
- ));
- // Whitespace-only blank line (not perfectly empty) must also count as a
- // paragraph break.
- assert!(!text_looks_like_question(
- "Which channel should I post to?\n \nPosted the update just now."
- ));
-}
-
-/// CodeRabbit review follow-up: a multi-backtick Markdown code span (e.g.
-/// double backtick, used so the span can itself contain a literal single
-/// backtick) must still be recognized as code — a naive backtick-count
-/// parity check misclassifies it because two backticks flip parity back to
-/// "even" immediately. The span must only close on a run of the SAME length
-/// that opened it.
-#[test]
-fn text_looks_like_question_ignores_question_mark_inside_double_backtick_span() {
- assert!(!text_looks_like_question(
- "Run the query below to check the row.\n\n``SELECT * FROM t WHERE id = ?``"
- ));
- // A single backtick embedded inside a double-backtick span (the classic
- // reason to use a longer delimiter) must not be mistaken for the span's
- // closing delimiter.
- assert!(!text_looks_like_question(
- "Use ``SELECT `id` FROM t WHERE id = ?`` before retrying."
- ));
-}
-
-#[test]
-fn text_looks_like_question_rejects_status_dumps_and_silence() {
- assert!(!text_looks_like_question(
- "## Done so far\n- Checked connections\n- Verified contracts"
- ));
- assert!(!text_looks_like_question(""));
- assert!(!text_looks_like_question(" "));
- assert!(!text_looks_like_question("I'll continue working on this."));
-}
-
/// The terminal-state guarantee's core invariant: whatever `build_trail_off_fallback`
/// returns, it must ALWAYS read as a question — the user is never left with
/// silence, regardless of what (if anything) the tool history contains.
diff --git a/crates/openhuman-core/src/flows/ops_migration_and_side_effect_tests.rs b/crates/openhuman-core/src/flows/ops_migration_and_side_effect_tests.rs
index 6db288e368..8fe4840cec 100644
--- a/crates/openhuman-core/src/flows/ops_migration_and_side_effect_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_migration_and_side_effect_tests.rs
@@ -605,96 +605,3 @@ async fn draft_promote_of_invalid_graph_is_rejected_and_keeps_the_draft() {
// The draft survives a failed promote so the user can fix it.
assert!(flows_draft_get(&config, &draft.id).is_ok());
}
-
-/// Regression for #6540: a graph whose *node* omits `name` must report which
-/// object is at fault, not a bare `missing field \`name\``.
-///
-/// The bare message is worse than uninformative here, because the one reading
-/// it cannot even rule out the obvious candidate: every field of
-/// `WorkflowGraph` is `#[serde(default)]`, so the top-level `name` can never be
-/// the cause — yet an authoring agent that assumes it is will re-send the same
-/// graph until it exhausts its iteration cap. That is exactly what happened
-/// live: six identical retries, 392k input tokens, no workflow created.
-#[test]
-fn migrate_and_deserialize_graph_names_the_node_that_is_missing_a_field() {
- let missing_node_name = json!({
- "name": "top-level name is present and is NOT the problem",
- "nodes": [
- { "id": "start", "kind": "trigger", "name": "Trigger" },
- { "id": "nameless", "kind": "trigger" }
- ]
- });
-
- let err = migrate_and_deserialize_graph(missing_node_name)
- .expect_err("a node without `name` must not deserialize");
-
- // The path is the point of the fix: `nodes[1]` is the second node, and
- // naming it is what distinguishes this from the two other required `name`
- // fields reachable from one graph (`Port::name`, `WorkflowInput::name`).
- assert!(
- err.contains("nodes[1]"),
- "error must name the offending node's path, got: {err}"
- );
- // ...and the original serde detail must survive the wrapping, or the fix
- // would have traded one unactionable message for another.
- assert!(
- err.contains("missing field") && err.contains("name"),
- "error must still say which field is missing, got: {err}"
- );
-}
-
-/// The premise of the test above: a graph with no top-level `name` at all
-/// deserializes fine. If this ever starts failing, `missing field \`name\``
-/// becomes genuinely ambiguous and the path in the message matters more, not
-/// less.
-#[test]
-fn migrate_and_deserialize_graph_accepts_a_graph_with_no_top_level_name() {
- let no_top_level_name = json!({
- "nodes": [ { "id": "start", "kind": "trigger", "name": "Trigger" } ]
- });
-
- let graph = migrate_and_deserialize_graph(no_top_level_name)
- .expect("top-level `name` is #[serde(default)] and must not be required");
- assert_eq!(
- graph.name, "",
- "absent top-level name must default to empty"
- );
-}
-
-/// Regression for the misattribution case raised in review on #6545: when the
-/// graph's own fields are at fault *and* a node is independently invalid, the
-/// error must not be pinned on the node.
-///
-/// Locating by "first member that fails on its own" is only sound once the
-/// top level is known good — otherwise it turns a correct vague message into a
-/// confident wrong one, which is worse than what this PR set out to fix.
-#[test]
-fn migrate_and_deserialize_graph_does_not_blame_a_node_for_a_top_level_fault() {
- let top_level_fault = json!({
- // Wrong type, not missing: `name` is `String`, so this fails the graph
- // parse on its own account.
- "name": 123,
- "nodes": [
- // Independently invalid too — the bait for the member scan.
- { "id": "nameless", "kind": "trigger" }
- ]
- });
-
- let err = migrate_and_deserialize_graph(top_level_fault)
- .expect_err("a non-string top-level `name` must not deserialize");
-
- // Assert what must NOT be claimed. Comparing the rendered string to the
- // bare serde message would pass for the wrong reason: the two messages can
- // coincide without the failing path being the same one.
- assert!(
- !err.contains("nodes["),
- "a top-level fault must not be attributed to a node, got: {err}"
- );
- assert!(
- err.contains("name"),
- "error should still name the offending field, got: {err}"
- );
-}
-
-#[path = "ops_migration_deserialize_tests.rs"]
-mod deserialize_tests;
diff --git a/crates/openhuman-core/src/flows/ops_migration_deserialize_tests.rs b/crates/openhuman-core/src/flows/ops_migration_deserialize_tests.rs
deleted file mode 100644
index 6681351da2..0000000000
--- a/crates/openhuman-core/src/flows/ops_migration_deserialize_tests.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-use super::*;
-
-/// The member scan covers four arrays, and until now only `nodes` was ever
-/// exercised — the other three arms were unreachable in the test suite while
-/// looking correct by inspection.
-#[test]
-fn migrate_and_deserialize_graph_names_the_member_in_inputs_agents_and_edges() {
- let bad_input = json!({ "inputs": [ { "type": "string" } ] });
- let err = migrate_and_deserialize_graph(bad_input).expect_err("input without `name`");
- assert!(err.starts_with("inputs[0]: "), "got: {err}");
-
- let bad_agent = json!({ "agents": [ { "name": "no id" } ] });
- let err = migrate_and_deserialize_graph(bad_agent).expect_err("agent without `id`");
- assert!(err.starts_with("agents[0]: "), "got: {err}");
-
- let bad_edge = json!({ "edges": [ { "from_port": "main" } ] });
- let err = migrate_and_deserialize_graph(bad_edge).expect_err("edge without endpoints");
- assert!(err.starts_with("edges[0]: "), "got: {err}");
-}
-
-#[test]
-fn migrate_and_deserialize_graph_falls_back_when_no_member_is_at_fault() {
- let nodes_not_an_array = json!({ "name": "valid", "nodes": "this is not an array" });
- let err = migrate_and_deserialize_graph(nodes_not_an_array)
- .expect_err("a non-array `nodes` must not deserialize");
- assert!(!err.contains("nodes["), "got: {err}");
- assert!(err.contains("invalid type"), "got: {err}");
-}
-
-#[test]
-fn migrate_and_deserialize_graph_reports_a_non_object_graph_without_inventing_a_location() {
- let err = migrate_and_deserialize_graph(json!("this is a string, not a workflow graph"))
- .expect_err("a non-object graph must not deserialize");
- // A non-object has no member to attribute: retain serde's bare type
- // diagnostic rather than manufacturing a top-level field/path prefix.
- assert!(err.starts_with("invalid type: "), "got: {err}");
- assert!(!err.contains('['), "got: {err}");
-}
diff --git a/crates/openhuman-core/src/flows/types_tests.rs b/crates/openhuman-core/src/flows/types_tests.rs
deleted file mode 100644
index 0fe8cdb33d..0000000000
--- a/crates/openhuman-core/src/flows/types_tests.rs
+++ /dev/null
@@ -1,161 +0,0 @@
-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(),
- description: "Round-trips through JSON.".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());
- }
-