checkpoint

⚒️ Generated with [Fabro](https://fabro.sh)
This commit is contained in:
Fabro 2026-05-23 16:46:05 -04:00
parent cc71f748e8
commit b0cfd8543e
5 changed files with 1091 additions and 35 deletions

379
run.json

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,427 @@
diff --git a/lib/crates/fabro-workflow/src/handler/agent.rs b/lib/crates/fabro-workflow/src/handler/agent.rs
index 0f2118df8..95bc502b4 100644
--- a/lib/crates/fabro-workflow/src/handler/agent.rs
+++ b/lib/crates/fabro-workflow/src/handler/agent.rs
@@ -2,9 +2,10 @@ use std::path::Path;
use std::sync::Arc;
use async_trait::async_trait;
-use fabro_agent::{Sandbox, shell_quote};
+use fabro_agent::Sandbox;
use fabro_graphviz::graph::{Graph, Node};
use fabro_types::{RunId, StageModelUsage};
+pub(crate) use structured_output::extract_status_fields;
use tokio_util::sync::CancellationToken;
use super::llm::api::EffectiveRequestControls;
@@ -133,15 +134,6 @@ impl AgentHandler {
}
}
-/// Extract routing directives from LLM response text.
-///
-/// Searches for the last JSON object in the response that contains at least
-/// one status field (`preferred_next_label`, `outcome`, `suggested_next_ids`,
-/// `context_updates`). Merges extracted fields into the outcome.
-pub(crate) fn extract_status_fields(text: &str, outcome: &mut Outcome) -> bool {
- structured_output::extract_status_fields_loose(text, outcome)
-}
-
pub(crate) async fn validate_agent_output_sources(
schema: &OutputSchemaKind,
response_text: &str,
@@ -152,18 +144,18 @@ pub(crate) async fn validate_agent_output_sources(
return structured_output::validate_response_text(schema, response_text);
}
- match structured_output::validate_response_text(schema, response_text) {
+ let initial_error = match structured_output::validate_response_text(schema, response_text) {
Ok(validated) => return Ok(validated),
- Err(error) if error.allows_routing_fallback() => {}
+ Err(error) if error.allows_routing_fallback() => error,
Err(error) => return Err(error),
- }
+ };
- let mut fallback_error = None;
+ let mut fallback_error = initial_error;
if let Some(status_json) = read_sandbox_file(sandbox, "status.json").await {
match structured_output::validate_response_text(schema, &status_json) {
Ok(validated) => return Ok(validated),
Err(error) if error.allows_routing_fallback() => {
- fallback_error = Some(error);
+ fallback_error = error;
}
Err(error) => return Err(error),
}
@@ -175,23 +167,11 @@ pub(crate) async fn validate_agent_output_sources(
}
}
- Err(fallback_error.unwrap_or_else(|| {
- structured_output::validate_response_text(schema, response_text)
- .expect_err("response text should have failed routing validation")
- }))
+ Err(fallback_error)
}
async fn read_sandbox_file(sandbox: &Arc<dyn Sandbox>, path: &str) -> Option<String> {
- let cmd = format!("cat {}", shell_quote(path));
- let result = sandbox
- .exec_command(&cmd, 5_000, None, None, None)
- .await
- .ok()?;
- if result.is_success() {
- Some(result.stdout)
- } else {
- None
- }
+ sandbox.read_file_text(path).await.ok()
}
/// Truncate a string to at most `max_chars` characters (char-boundary safe).
diff --git a/lib/crates/fabro-workflow/src/handler/llm/api.rs b/lib/crates/fabro-workflow/src/handler/llm/api.rs
index 22d08dc4b..8a92973df 100644
--- a/lib/crates/fabro-workflow/src/handler/llm/api.rs
+++ b/lib/crates/fabro-workflow/src/handler/llm/api.rs
@@ -474,6 +474,10 @@ fn file_tracking_snapshot(
(files, state.last.clone())
}
+fn last_touched_file(file_tracking: &Arc<Mutex<FileTracking>>) -> Option<String> {
+ file_tracking.lock().unwrap().last.clone()
+}
+
fn last_assistant_response(session: &Session) -> String {
session
.history()
@@ -553,10 +557,8 @@ pub struct AgentApiBackend {
}
struct OneShotCompletion {
- response: Response,
- actual_model: String,
- actual_provider: String,
- actual_speed: Option<Speed>,
+ response: Response,
+ model: ModelRef,
}
impl AgentApiBackend {
@@ -864,16 +866,17 @@ impl AgentApiBackend {
let result = client.complete(request).await;
let default_provider = self.provider_id.to_string();
- let (response, actual_model, actual_provider, actual_speed) = match result {
- Ok(resp) => (
- resp,
- request.model.clone(),
- request
- .provider
- .clone()
- .unwrap_or_else(|| default_provider.clone()),
- controls.speed,
- ),
+ let (response, model) = match result {
+ Ok(resp) => (resp, ModelRef {
+ provider: ProviderId::from(
+ request
+ .provider
+ .clone()
+ .unwrap_or_else(|| default_provider.clone()),
+ ),
+ model_id: request.model.clone(),
+ speed: controls.speed,
+ }),
Err(sdk_err) if sdk_err.failover_eligible() && !fallback_chain.is_empty() => {
let error_msg = sdk_err.to_string();
let from_provider = request
@@ -916,10 +919,12 @@ impl AgentApiBackend {
match client.complete(&fallback_request).await {
Ok(resp) => {
found = Some(OneShotCompletion {
- response: resp,
- actual_model: target.model.clone(),
- actual_provider: target.provider.clone(),
- actual_speed: controls.speed,
+ response: resp,
+ model: ModelRef {
+ provider: ProviderId::from(target.provider.clone()),
+ model_id: target.model.clone(),
+ speed: controls.speed,
+ },
});
break;
}
@@ -938,12 +943,7 @@ impl AgentApiBackend {
Err(sdk_err) => return Err(Error::Llm(sdk_err)),
};
- Ok(OneShotCompletion {
- response,
- actual_model,
- actual_provider,
- actual_speed,
- })
+ Ok(OneShotCompletion { response, model })
}
}
@@ -1053,11 +1053,7 @@ impl CodergenBackend for AgentApiBackend {
let stage_usage = billed_model_usage_from_llm(
self.catalog.as_ref(),
- &ModelRef {
- provider: ProviderId::from(completion.actual_provider),
- model_id: completion.actual_model,
- speed: completion.actual_speed,
- },
+ &completion.model,
&total_usage,
)?;
@@ -1362,7 +1358,7 @@ impl CodergenBackend for AgentApiBackend {
if let Some(schema) = &output_schema {
let mut repair_attempts = 0_i64;
loop {
- let (_, last_file_touched) = file_tracking_snapshot(&file_tracking);
+ let last_file_touched = last_touched_file(&file_tracking);
match validate_agent_output_sources(
schema,
&response,
diff --git a/lib/crates/fabro-workflow/src/handler/structured_output.rs b/lib/crates/fabro-workflow/src/handler/structured_output.rs
index d98a42afb..855d6e456 100644
--- a/lib/crates/fabro-workflow/src/handler/structured_output.rs
+++ b/lib/crates/fabro-workflow/src/handler/structured_output.rs
@@ -1,10 +1,15 @@
+use std::sync::{Arc, LazyLock};
+
use fabro_graphviz::graph::Node;
use fabro_llm::types::{ResponseFormat, ResponseFormatType};
+use jsonschema::Validator;
use serde_json::Value;
use crate::error::Error;
use crate::outcome::{FailureCategory, FailureDetail, Outcome, StageOutcome};
+pub(crate) const ROUTING_KEYWORD: &str = "routing";
+
pub(crate) const ROUTING_STATUS_FIELDS: &[&str] = &[
"preferred_next_label",
"outcome",
@@ -13,10 +18,15 @@ pub(crate) const ROUTING_STATUS_FIELDS: &[&str] = &[
"context_updates",
];
-#[derive(Debug, Clone, PartialEq)]
+/// Parsed `output_schema` declaration with a precompiled validator so that
+/// repair turns don't recompile the schema on every iteration.
+#[derive(Debug, Clone)]
pub(crate) enum OutputSchemaKind {
Routing,
- JsonSchema { schema: Value },
+ JsonSchema {
+ schema: Value,
+ validator: Arc<Validator>,
+ },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -135,7 +145,7 @@ pub(crate) fn parse_node_output_schema(node: &Node) -> Result<Option<OutputSchem
node.id
)));
}
- if value == "routing" {
+ if value == ROUTING_KEYWORD {
return Ok(Some(OutputSchemaKind::Routing));
}
if value.starts_with('@') {
@@ -151,13 +161,16 @@ pub(crate) fn parse_node_output_schema(node: &Node) -> Result<Option<OutputSchem
node.id
))
})?;
- compile_schema(&schema).map_err(|err| {
+ let validator = jsonschema::validator_for(&schema).map_err(|err| {
Error::Validation(format!(
"Invalid output_schema for node \"{}\": {err}",
node.id
))
})?;
- Ok(Some(OutputSchemaKind::JsonSchema { schema }))
+ Ok(Some(OutputSchemaKind::JsonSchema {
+ schema,
+ validator: Arc::new(validator),
+ }))
}
#[must_use]
@@ -168,7 +181,7 @@ pub(crate) fn prompt_response_format(schema: &OutputSchemaKind) -> ResponseForma
json_schema: None,
strict: false,
},
- OutputSchemaKind::JsonSchema { schema } => ResponseFormat {
+ OutputSchemaKind::JsonSchema { schema, .. } => ResponseFormat {
kind: ResponseFormatType::JsonSchema,
json_schema: Some(schema.clone()),
strict: true,
@@ -182,7 +195,9 @@ pub(crate) fn validate_response_text(
) -> Result<ValidatedStructuredOutput, StructuredOutputError> {
match schema {
OutputSchemaKind::Routing => validate_routing_response_text(text),
- OutputSchemaKind::JsonSchema { schema } => validate_custom_response_text(schema, text),
+ OutputSchemaKind::JsonSchema { validator, .. } => {
+ validate_custom_response_text(validator, text)
+ }
}
}
@@ -203,7 +218,7 @@ pub(crate) fn apply_validated_output(
}
/// Find all balanced `{...}` JSON object substrings in the text.
-pub(crate) fn find_json_objects(text: &str) -> Vec<&str> {
+fn find_json_objects(text: &str) -> Vec<&str> {
let mut results = Vec::new();
let bytes = text.as_bytes();
let mut i = 0;
@@ -241,7 +256,7 @@ pub(crate) fn find_json_objects(text: &str) -> Vec<&str> {
results
}
-pub(crate) fn extract_status_fields_loose(text: &str, outcome: &mut Outcome) -> bool {
+pub(crate) fn extract_status_fields(text: &str, outcome: &mut Outcome) -> bool {
let candidates = find_json_objects(text);
let parsed = candidates.iter().rev().find_map(|candidate| {
@@ -286,7 +301,7 @@ fn validate_routing_response_text(
if !contains_routing_field(obj) {
continue;
}
- validate_value_against_schema(&routing_schema(), &parsed)?;
+ validate_value_against_validator(routing_validator(), &parsed)?;
return Ok(ValidatedStructuredOutput { value: parsed });
}
@@ -300,7 +315,7 @@ fn validate_routing_response_text(
}
fn validate_custom_response_text(
- schema: &Value,
+ validator: &Validator,
text: &str,
) -> Result<ValidatedStructuredOutput, StructuredOutputError> {
let candidates = find_json_objects(text);
@@ -316,20 +331,14 @@ fn validate_custom_response_text(
format!("invalid JSON object: {err}"),
)
})?;
- validate_value_against_schema(schema, &parsed)?;
+ validate_value_against_validator(validator, &parsed)?;
Ok(ValidatedStructuredOutput { value: parsed })
}
-fn validate_value_against_schema(
- schema: &Value,
+fn validate_value_against_validator(
+ validator: &Validator,
value: &Value,
) -> Result<(), StructuredOutputError> {
- let validator = compile_schema(schema).map_err(|err| {
- StructuredOutputError::new(
- StructuredOutputErrorKind::SchemaValidation,
- format!("invalid JSON Schema: {err}"),
- )
- })?;
let errors = validator
.iter_errors(value)
.map(|error| error.to_string())
@@ -342,12 +351,6 @@ fn validate_value_against_schema(
}
}
-fn compile_schema(
- schema: &Value,
-) -> Result<jsonschema::Validator, jsonschema::ValidationError<'static>> {
- jsonschema::validator_for(schema)
-}
-
fn contains_routing_field(obj: &serde_json::Map<String, Value>) -> bool {
ROUTING_STATUS_FIELDS
.iter()
@@ -360,28 +363,32 @@ fn raw_mentions_routing_field(candidate: &str) -> bool {
.any(|field| candidate.contains(&format!("\"{field}\"")))
}
-fn routing_schema() -> Value {
- serde_json::json!({
- "type": "object",
- "additionalProperties": true,
- "properties": {
- "preferred_next_label": { "type": "string" },
- "outcome": {
- "type": "string",
- "enum": ["succeeded", "partially_succeeded", "failed", "skipped"]
- },
- "failure_reason": { "type": "string" },
- "suggested_next_ids": {
- "type": "array",
- "items": { "type": "string" }
+fn routing_validator() -> &'static Validator {
+ static ROUTING_VALIDATOR: LazyLock<Validator> = LazyLock::new(|| {
+ let schema = serde_json::json!({
+ "type": "object",
+ "additionalProperties": true,
+ "properties": {
+ "preferred_next_label": { "type": "string" },
+ "outcome": {
+ "type": "string",
+ "enum": ["succeeded", "partially_succeeded", "failed", "skipped"]
+ },
+ "failure_reason": { "type": "string" },
+ "suggested_next_ids": {
+ "type": "array",
+ "items": { "type": "string" }
+ },
+ "context_updates": { "type": "object" }
},
- "context_updates": { "type": "object" }
- },
- "anyOf": ROUTING_STATUS_FIELDS
- .iter()
- .map(|field| serde_json::json!({ "required": [field] }))
- .collect::<Vec<_>>()
- })
+ "anyOf": ROUTING_STATUS_FIELDS
+ .iter()
+ .map(|field| serde_json::json!({ "required": [field] }))
+ .collect::<Vec<_>>()
+ });
+ jsonschema::validator_for(&schema).expect("built-in routing schema must compile")
+ });
+ &ROUTING_VALIDATOR
}
fn apply_routing_fields(value: &Value, outcome: &mut Outcome) {
@@ -433,7 +440,12 @@ mod tests {
}
fn schema(value: Value) -> OutputSchemaKind {
- OutputSchemaKind::JsonSchema { schema: value }
+ let validator =
+ jsonschema::validator_for(&value).expect("test schema should be a valid JSON Schema");
+ OutputSchemaKind::JsonSchema {
+ schema: value,
+ validator: Arc::new(validator),
+ }
}
#[test]
@@ -572,7 +584,7 @@ mod tests {
let parsed = parse_node_output_schema(&node).unwrap();
- assert_eq!(parsed, Some(OutputSchemaKind::Routing));
+ assert!(matches!(parsed, Some(OutputSchemaKind::Routing)));
}
#[test]

View file

@ -0,0 +1,6 @@
{
"outcome": "succeeded",
"notes": "Stage completed: simplify_opus",
"failure_reason": null,
"timestamp": "2026-05-23T20:42:41.067539Z"
}

View file

@ -0,0 +1,309 @@
Goal: # Output Schema Validation Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add `output_schema` validation for agent and prompt nodes, with context-preserving repair turns when structured output does not validate.
**Architecture:** Introduce a small structured-output layer in `fabro-workflow` that resolves node-level schema declarations, extracts JSON output, validates it, and produces either routing side effects or a parsed custom output context update. Agent and prompt execution must perform schema repair inside the active LLM conversation instead of using the workflow executor retry path.
**Tech Stack:** Rust, Graphviz workflow attrs, `serde_json`, workspace `jsonschema`, existing `fabro-llm::ResponseFormat`, Fabro agent sessions, `cargo nextest`.
---
## Public Interface
Workflow authors can opt in on agent and prompt nodes:
```dot
review [
shape=tab,
output_schema="routing",
output_retries=2
]
audit [
shape=tab,
output_schema="@schemas/audit-result.schema.json",
output_retries=2
]
```
- `output_schema="routing"` uses Fabro's built-in routing directive schema.
- `output_schema="@path/to/schema.json"` loads a JSON Schema file through existing workflow file-reference rules.
- `output_retries` controls corrective turns inside the same node execution. Default: `2`. `0` means validate once and fail without a repair turn.
- Schema failures are terminal node failures after `output_retries` is exhausted. They are not `retry_requested` outcomes and do not consume `max_retries`.
- `backend="acp"` with `output_schema` is unsupported in v1 and returns a clear validation error.
## Implementation Tasks
### Task 1: Node Attributes And File Reference Resolution
**Files:**
- Modify: `lib/crates/fabro-types/src/graph.rs`
- Modify: `lib/crates/fabro-workflow/src/static_reference.rs`
- Modify: `lib/crates/fabro-workflow/src/transforms/file_inlining.rs`
- Test: existing unit tests in those files
- [ ] Add `Node::output_schema(&self) -> Option<&str>` next to other agent/prompt attrs.
- [ ] Add `Node::output_retries(&self) -> i64` returning `self.int_attr("output_retries").unwrap_or(2).max(0)`.
- [ ] Teach static reference validation that node attr `output_schema` values starting with `@` are file inline references.
- [ ] Extend file inlining so `output_schema="@schemas/foo.json"` is replaced with the schema file contents before execution, while `output_schema="routing"` stays unchanged.
- [ ] Add tests for absent attrs, default retries, zero retries, file inlining, and unresolved schema reference diagnostics.
Run:
```bash
cargo nextest run -p fabro-types -p fabro-workflow graph:: file_inlining static_reference
```
Expected: targeted tests pass.
### Task 2: Structured Output Module
**Files:**
- Create: `lib/crates/fabro-workflow/src/handler/structured_output.rs`
- Modify: `lib/crates/fabro-workflow/src/handler/mod.rs`
- Modify: `lib/crates/fabro-workflow/Cargo.toml`
- Test: unit tests in `structured_output.rs`
- [ ] Add `jsonschema.workspace = true` to `fabro-workflow` dependencies.
- [ ] Define `OutputSchemaKind` with `Routing` and `JsonSchema { schema: serde_json::Value }`.
- [ ] Parse `node.output_schema()` into `None`, `Routing`, or custom JSON Schema. Treat literal `routing` as the only built-in keyword.
- [ ] Add a built-in routing schema requiring an object with at least one recognized field: `preferred_next_label`, `outcome`, `failure_reason`, `suggested_next_ids`, or `context_updates`.
- [ ] Reuse balanced-object scanning semantics for response text: validate the last JSON object that is relevant to the selected schema.
- [ ] Return a structured validation result containing the parsed JSON object, concise error messages, and enough information to build a repair prompt.
- [ ] Add tests for valid routing JSON, missing routing fields, wrong routing field types, valid custom schema, invalid custom schema, invalid JSON, and no JSON object.
Run:
```bash
cargo nextest run -p fabro-workflow structured_output
```
Expected: structured-output unit tests pass.
### Task 3: Routing Extraction Compatibility
**Files:**
- Modify: `lib/crates/fabro-workflow/src/handler/agent.rs`
- Test: existing agent handler unit tests
- [ ] Keep the loose default unchanged when `output_schema` is absent.
- [ ] Move current `STATUS_FIELDS`, balanced JSON scanning, and routing-field application behind reusable functions in `structured_output.rs` or call the new module from `agent.rs`.
- [ ] For `output_schema="routing"`, require schema-valid routing JSON and surface validation failures for repair instead of silently ignoring bad candidates.
- [ ] Preserve existing routing fallback priority for agent nodes: response text first, then `status.json`, then last file touched.
- [ ] Keep prompt-node routing behavior response-only unless later tasks explicitly add prompt `status.json` support.
Run:
```bash
cargo nextest run -p fabro-workflow handler::agent
```
Expected: existing loose routing tests still pass, plus new strict routing tests pass.
### Task 4: Prompt Node Same-Context Repair
**Files:**
- Modify: `lib/crates/fabro-workflow/src/handler/llm/api.rs`
- Modify: `lib/crates/fabro-workflow/src/handler/prompt.rs`
- Test: prompt/API backend tests in those files
- [ ] In `AgentApiBackend::one_shot`, keep `messages` mutable across attempts.
- [ ] When a prompt node has a custom JSON Schema, set `response_format=JsonSchema` on the initial and repair LLM requests. For `routing`, use `JsonObject` or no provider-native schema if provider behavior would conflict with Fabro's routing extraction.
- [ ] After each LLM response, validate according to `output_schema`.
- [ ] On validation failure with repair attempts remaining, append `Message::assistant(response.text())`, then append a corrective `Message::user(repair_message)`, and call `client.complete` again with the same messages.
- [ ] On success, return the validated response text and aggregate usage across all attempts.
- [ ] On exhaustion, return a terminal failed outcome with failure reason `output schema validation failed after N repair attempt(s)`.
- [ ] Update `PromptHandler` so validated custom output is added to `context_updates["output.{node_id}"]`; routing output still updates outcome routing fields.
Run:
```bash
cargo nextest run -p fabro-workflow handler::prompt handler::llm::api
```
Expected: prompt repair keeps previous assistant output in the message list and succeeds after a corrective response.
### Task 5: Agent Node Same-Session Repair
**Files:**
- Modify: `lib/crates/fabro-workflow/src/handler/llm/api.rs`
- Modify: `lib/crates/fabro-workflow/src/handler/agent.rs`
- Test: agent/API backend tests in those files
- [ ] In `AgentApiBackend::run`, validate the final assistant response before releasing, closing, or caching the session.
- [ ] On validation failure with repair attempts remaining, call `session.process_input(repair_message)` on the same `Session`.
- [ ] Recompute the final assistant response after each repair turn from `session.history()`.
- [ ] Aggregate usage across all new assistant turns, including repair turns, without double-counting reused session history.
- [ ] Do not set provider-native `response_format` for agent sessions in v1, because agent sessions may need normal tool-use messages before final output.
- [ ] Return terminal failure after exhaustion; do not return a retryable backend error and do not request workflow node retry.
- [ ] Update `AgentHandler` to apply validated routing/custom output to the final `Outcome`.
Run:
```bash
cargo nextest run -p fabro-workflow handler::agent handler::llm::api
```
Expected: agent repair sends a second `process_input` to the same session and final validated output drives outcome/context updates.
### Task 6: ACP Guardrail
**Files:**
- Modify: `lib/crates/fabro-workflow/src/handler/llm/acp.rs`
- Test: ACP backend tests in that file
- [ ] At the start of `AgentAcpBackend::run`, reject nodes where `node.output_schema().is_some()`.
- [ ] Use a clear error message: `output_schema is not supported with backend="acp" in this release`.
- [ ] Add a test proving the ACP backend does not launch a process when `output_schema` is present.
Run:
```bash
cargo nextest run -p fabro-workflow handler::llm::acp
```
Expected: ACP guardrail test passes.
### Task 7: Docs
**Files:**
- Modify: `docs/public/agents/outputs.mdx`
- Modify: `docs/public/reference/dot-language.mdx`
- [ ] Document `output_schema="routing"` and `output_schema="@schema.json"` under routing/structured outputs.
- [ ] Document same-context repair behavior explicitly: Fabro sends validation feedback to the same agent/prompt context before failing.
- [ ] Document `output_retries`, default `2`, and distinction from `max_retries`.
- [ ] Document v1 scope: agent/prompt nodes only; ACP unsupported; custom schema output stored at `output.{node_id}`.
Run:
```bash
rg -n "output_schema|output_retries|output\\." docs/public/agents/outputs.mdx docs/public/reference/dot-language.mdx
```
Expected: docs mention the new attrs and storage behavior.
### Task 8: Full Verification
**Files:**
- No new files beyond prior tasks
- [ ] Run focused workflow tests:
```bash
cargo nextest run -p fabro-workflow
```
- [ ] Run formatting check:
```bash
cargo +nightly-2026-04-14 fmt --check --all
```
- [ ] Run clippy:
```bash
cargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warnings
```
- [ ] If snapshots change, inspect before accepting:
```bash
cargo insta pending-snapshots
```
Only run `cargo insta accept` after verifying every pending snapshot is expected.
## Acceptance Criteria
- Existing workflows without `output_schema` behave exactly as before.
- `output_schema="routing"` prevents malformed/missing routing JSON from silently falling through to normal edge selection.
- Invalid structured output results in a corrective LLM turn in the same context window.
- Prompt repair preserves previous assistant output in the message list.
- Agent repair preserves the same live session and does not re-run the node from scratch.
- Exhausted output repair attempts produce a clear terminal failure.
- Custom schema output is available to downstream nodes at `output.{node_id}`.
- Docs clearly distinguish `output_retries` from `max_retries`.
## Assumptions
- `output_retries=2` is the default.
- Custom schema validation targets the final JSON object in the response text.
- `status.json` fallback remains routing-specific.
- Provider-native response schema is used for prompt nodes only where it is safe.
- ACP support can be added later after there is a guaranteed context-preserving repair mechanism.
## Completed stages
- **toolchain**: succeeded
- Script: `command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1`
- Output:
```
cargo 1.95.0 (f2d3ce0bd 2026-03-21)
```
- **preflight_compile**: succeeded
- Script: `cargo check -q --workspace 2>&1`
- Output: (empty)
- **preflight_lint**: succeeded
- Script: `cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1`
- Output: (empty)
- **implement**: succeeded
- Model: gpt-5.5, 329.8k tokens in / 54.8k out
- Files: /home/daytona/workspace/fabro/lib/crates/fabro-workflow/src/handler/structured_output.rs
- **simplify_opus**: succeeded
- Model: claude-opus-4-7, 141.5k tokens in / 35.9k out
- Files: /home/daytona/workspace/fabro/lib/crates/fabro-workflow/src/handler/agent.rs, /home/daytona/workspace/fabro/lib/crates/fabro-workflow/src/handler/llm/api.rs, /home/daytona/workspace/fabro/lib/crates/fabro-workflow/src/handler/structured_output.rs
# Simplify: Code Review and Cleanup
Review changes vs. origin for reuse, quality, and efficiency. Fix any issues found.
## Phase 1: Identify Changes
Run git diff (or git diff HEAD if there are staged changes) to see what changed. If there are no git changes, review the most recently modified files that the user mentioned or that you edited earlier in this conversation.
## Phase 2: Launch Three Review Agents in Parallel
Use the Agent tool to launch all three agents concurrently in a single message. Pass each agent the full diff so it has the complete context.
### Agent 1: Code Reuse Review
For each change:
1. Search for existing utilities and helpers that could replace newly written code. Use Grep to find similar patterns elsewhere in the codebase — common locations are utility directories, shared modules, and files adjacent to the changed ones.
2. Flag any new function that duplicates existing functionality. Suggest the existing function to use instead.
3. Flag any inline logic that could use an existing utility — hand-rolled string manipulation, manual path handling, custom environment checks, ad-hoc type guards, and similar patterns are common candidates.
Note: This is a greenfield app, so focus on maximizing simplicity and don't worry about changing things to achieve it.
### Agent 2: Code Quality Review
Review the same changes for hacky patterns:
1. Redundant state: state that duplicates existing state, cached values that could be derived, observers/effects that could be direct calls
2. Parameter sprawl: adding new parameters to a function instead of generalizing or restructuring existing ones
3. Copy-paste with slight variation: near-duplicate code blocks that should be unified with a shared abstraction
4. Leaky abstractions: exposing internal details that should be encapsulated, or breaking existing abstraction boundaries
5. Stringly-typed code: using raw strings where constants, enums (string unions), or branded types already exist in the codebase
Note: This is a greenfield app, so be aggressive in optimizing quality.
### Agent 3: Efficiency Review
Review the same changes for efficiency:
1. Unnecessary work: redundant computations, repeated file reads, duplicate network/API calls, N+1 patterns
2. Missed concurrency: independent operations run sequentially when they could run in parallel
3. Hot-path bloat: new blocking work added to startup or per-request/per-render hot paths
4. Unnecessary existence checks: pre-checking file/resource existence before operating (TOCTOU anti-pattern) — operate directly and handle the error
5. Memory: unbounded data structures, missing cleanup, event listener leaks
6. Overly broad operations: reading entire files when only a portion is needed, loading all items when filtering for one
## Phase 3: Fix Issues
Wait for all three agents to complete. Aggregate their findings and fix each issue directly. If a finding is a false positive or not worth addressing, note it and move on — do not argue with the finding, just skip it.
When done, briefly summarize what was fixed (or confirm the code was already clean).

View file

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