From bf4a9a6eb714acb0547461a7a1ec49ae3933fa89 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Feb 2026 18:29:33 +0000 Subject: [PATCH 1/3] Proper modeling: cardinality on CliEntrypoint, typed matchers, transport From impls, error context MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add `cardinality: Cardinality` field to `CliEntrypoint`, replacing `type_id == "List"` string matching with `cardinality.allows_many()` queries throughout CLI generation and makegen registry - Add typed `OutputMatcher` variants: `IsBool`, `IsInt`, `IsString`, `IsRequest`, `IsResponse`, `IntGe(i64)`, `IntLe(i64)` — all generate real codegen assertions instead of the comment-only `Satisfies` hack - Migrate existing `Satisfies` usages in CI/makegen graph mocks to typed variants - Add `ShellResponse::ok()` and `ShellResponse::failed()` constructors - Add `From for TransportRequest/TransportResponse` for all 5 transport types - Add `ExecError::context()` method and `ResultExt` trait for structured error context - Add `propagate_skipped()` helper for skip propagation pattern (8 sites) - Update TODO docs to reflect completed work https://claude.ai/code/session_01EaBXwSmZrbVcpbFoV44Aju --- TODO/TODO_hacks.md | 22 ++- TODO/TODO_type_system.md | 27 +-- TODO/consolidation.md | 13 +- core/codegen/src/cli_gen.rs | 245 +++++++++++++++++----------- core/codegen/src/testgen/codegen.rs | 64 ++++++++ core/exec/src/error.rs | 41 +++++ core/exec/src/helpers.rs | 72 ++++++++ core/exec/src/lib.rs | 7 +- core/ir/src/transport/mod.rs | 119 ++++++++++++++ core/test/src/mock_spec.rs | 68 +++++++- gunbc-dag/src/ci/graph_mock.rs | 25 +-- gunbc-dag/src/makegen/graph_mock.rs | 5 +- gunbc-dag/src/makegen/registry.rs | 4 +- 13 files changed, 556 insertions(+), 156 deletions(-) diff --git a/TODO/TODO_hacks.md b/TODO/TODO_hacks.md index af720e04da8..c37e4680913 100644 --- a/TODO/TODO_hacks.md +++ b/TODO/TODO_hacks.md @@ -293,7 +293,11 @@ represented as empty collection). ## Tasks -- [ ] Hack 1: Replace `Satisfies` comment-only codegen with runtime callback or typed matcher variants +- [x] Hack 1: Replace `Satisfies` comment-only codegen with typed matcher variants + - Added `IsBool`, `IsInt`, `IsString`, `IsRequest`, `IsResponse`, `IntGe(i64)`, `IntLe(i64)` to `OutputMatcher` + - All typed matchers generate real assertions in codegen (via `Assert::True` with method chains) + - Migrated existing `Satisfies` usages in `ci/graph_mock.rs` and `makegen/graph_mock.rs` + - `Satisfies` remains as escape hatch for truly custom predicates - [x] Hack 2: Add `Value::Response`/`Value::Request` support (done via ValueExpr pipeline) - [ ] Hack 2: Update parse node examples to use real transport responses - [x] Hack 3: Make `NonEmpty` codegen type-aware (or add `Value::is_empty()`) @@ -311,14 +315,14 @@ represented as empty collection). The old `value_to_rust_literal` is a one-liner delegating to this pipeline; the old `value_to_code` and `to_check_code` in mock_spec.rs have been deleted as dead code. -- Hack 1 is independent — it's about closure serialization, not Value - serialization. The "typed matcher variants" approach (option 2) is - probably the cleanest since it keeps generated tests self-contained. - Typed matchers form a small finite logic language that's both - serializable to codegen and amenable to future proof generation. +- **Hack 1 resolved**: Typed matcher variants (`IsBool`, `IsInt`, etc.) + now generate real codegen assertions. These are serializable to Rust + source without closure references. `Satisfies` remains only for + complex predicates that can't be expressed as simple type/range checks. + Existing usages in CI and makegen graph mocks have been migrated. - Hack 5 is the most architecturally important — it blocks meaningful cardinality boundary testing. If Empty doesn't test absence, the B.3 tests exercise a subset of what they claim to cover. -- None of the remaining hacks are blocking. Tests compile, run, and - pass. The risk is false confidence — tests that look like they verify - behavior but actually don't. +- Only hacks 2 (parse node examples) and 5 (absence testing) remain. + Both require deeper infrastructure changes (transport serialization + and `Option` semantics respectively). diff --git a/TODO/TODO_type_system.md b/TODO/TODO_type_system.md index 2627cda0c46..625e41864be 100644 --- a/TODO/TODO_type_system.md +++ b/TODO/TODO_type_system.md @@ -117,12 +117,17 @@ Examples: --- -## 6. Cardinality-driven CLI generation (partial) ✅ +## 6. Cardinality-driven CLI generation ✅ -**Implemented**: `gunbc-dag/src/makegen/registry.rs` now checks -`ep.type_id == "List" || ep.type_id == "Set"` instead of just `"List"`. -A TODO comment marks this for replacement with `cardinality.allows_many()` -when `CliEntrypoint` carries `Cardinality` (part of codegen rework). +**Implemented**: `CliEntrypoint` now carries a `cardinality: Cardinality` +field (`core/codegen/src/cli_gen.rs`). All CLI generation logic — +`rust_type()`, `value_constructor()`, `is_repeatable()`, arg parsing, +help text — derives collection behavior from `cardinality.allows_many()` +instead of string-matching `type_id == "List"`. + +The makegen registry (`gunbc-dag/src/makegen/registry.rs`) now uses +`ep.cardinality.allows_many()` directly, eliminating the TODO that +previously marked this for replacement. **Loop pattern fixed**: `core/ir/src/patterns/loop_pattern.rs` defaults now use `"String"` as the type_id (element type) instead of `"List"`. @@ -130,10 +135,6 @@ Cardinality `ZERO_OR_MORE` handles the collection semantics — this eliminates the dual encoding where `"List"` was both a type name and a cardinality indicator. -**What's next**: Add `cardinality: Cardinality` field to `CliEntrypoint` -and replace all `type_id ==` string checks in codegen. This is being -addressed in the codegen rework. - --- ## Remaining Tasks @@ -141,7 +142,6 @@ addressed in the codegen rework. - [ ] Move toward structural type DAG comparison in Port (item 1) - [ ] Wire cardinality through to codegen emptiness checks (item 2, codegen rework) - [ ] Model target language elements as structured data (item 3, codegen rework — in progress) -- [ ] Add `cardinality` field to `CliEntrypoint` (item 6, codegen rework) - [ ] Wire `contract::witnesses()` into testgen (codegen rework) ## Completed @@ -153,6 +153,13 @@ addressed in the codegen rework. - [x] Implement `contract::witnesses()` boundary witness generation (item 5) - [x] Replace `type_id == "List"` in non-codegen locations (item 6 partial) - [x] Fix loop pattern dual encoding (type_id "List" → element type + cardinality) +- [x] Add `cardinality: Cardinality` field to `CliEntrypoint` (item 6) +- [x] Replace `type_id ==` string checks in CLI generation with `cardinality.allows_many()` +- [x] Add typed `OutputMatcher` variants (`IsBool`, `IsInt`, `IsString`, `IsRequest`, `IsResponse`, `IntGe`, `IntLe`) that generate real codegen assertions +- [x] Add `ShellResponse::ok()` / `failed()` constructors for transport response modeling +- [x] Add `From for TransportRequest` / `TransportResponse` impls for all transport types +- [x] Add `ExecError::context()` and `ResultExt` trait for structured error context +- [x] Add `propagate_skipped()` helper for skip propagation pattern ## Design Principles (from review) diff --git a/TODO/consolidation.md b/TODO/consolidation.md index d59de58514c..55329fc15c1 100644 --- a/TODO/consolidation.md +++ b/TODO/consolidation.md @@ -900,12 +900,15 @@ This is fine; it's infrastructure code, not op code. - [x] Add `TransportResponseExt::require_shell/rest/file` methods (51 call sites) — `core/exec/src/helpers.rs` - [x] Add `ShellRequest::into_transport_request()` — `core/ir/src/transport/mod.rs` -### High priority (new — widespread, low effort) -- [ ] Add `propagate_skipped` helper (8 call sites across 3 files) — §12 -- [ ] Add `ExecError::context()` + `ResultExt` trait (27 call sites across 10 files) — §13 -- [ ] Add `ShellResponse::ok()` / `ShellResponse::failed()` constructors (39 sites, 16 files) — §14 +### High priority (new — widespread, low effort) — DONE +- [x] Add `propagate_skipped` helper (8 call sites across 3 files) — §12 +- [x] Add `ExecError::context()` + `ResultExt` trait (27 call sites across 10 files) — §13 +- [x] Add `ShellResponse::ok()` / `ShellResponse::failed()` constructors (39 sites, 16 files) — §14 +- [x] Add `From for TransportRequest` (+ FileRequest, RestRequest, etc.) — all 5 request types + 5 response types + +### High priority (remaining) - [ ] Add `InputsExt` trait to replace free-function `require_*/optional_*` calls — shrinks import lists -- [ ] Add `From for TransportRequest` (+ FileRequest etc) and make `OutputMap::request` accept `impl Into` +- [ ] Migrate call sites to use `propagate_skipped`, `ExecError::context()`, `ShellResponse::ok()` etc. ### Medium priority - [ ] Migrate remaining raw `HashMap::new()` output construction to `OutputMap` (9 sites, 5 files) — §15 diff --git a/core/codegen/src/cli_gen.rs b/core/codegen/src/cli_gen.rs index e9b9f90e088..7a5ed27a9f8 100644 --- a/core/codegen/src/cli_gen.rs +++ b/core/codegen/src/cli_gen.rs @@ -9,6 +9,7 @@ //! Uses the language module for Rust type mappings and naming conventions. use gunbc_ir::language::{rust_type as lang_rust_type, NamingCase}; +use gunbc_ir::Cardinality; /// Metadata about a tool for CLI generation. #[derive(Debug, Clone)] @@ -40,6 +41,12 @@ pub struct CliEntrypoint { pub port_name: String, /// The type (String, Int, Bool, List, etc.) pub type_id: String, + /// Cardinality of this entrypoint's port. + /// + /// Used to determine CLI behavior: `allows_many()` → repeatable flag, + /// `allows_empty()` → optional argument. This replaces string matching + /// on `type_id == "List"` with proper cardinality queries. + pub cardinality: Cardinality, /// Short flag (e.g., "-r" for repo_path) pub short_flag: Option, /// Default value if not provided @@ -54,12 +61,24 @@ pub struct CliEntrypoint { impl CliEntrypoint { /// Create a new CLI entrypoint. + /// + /// Cardinality defaults to `ONE` (scalar). Use `with_cardinality()` to + /// set it explicitly, or use `list()` / `set()` constructors for + /// collection entrypoints. pub fn new(port_name: impl Into, type_id: impl Into) -> Self { let port = port_name.into(); + let type_id_str = type_id.into(); let help = format!("Value for {} port", port); + // Infer cardinality from type_id for backward compatibility. + // New code should use with_cardinality() or the typed constructors. + let cardinality = match type_id_str.as_str() { + "List" | "Set" => Cardinality::ZERO_OR_MORE, + _ => Cardinality::ONE, + }; Self { port_name: port, - type_id: type_id.into(), + type_id: type_id_str, + cardinality, short_flag: None, default_value: None, help, @@ -67,6 +86,12 @@ impl CliEntrypoint { } } + /// Set the cardinality explicitly. + pub fn with_cardinality(mut self, cardinality: Cardinality) -> Self { + self.cardinality = cardinality; + self + } + /// Set short flag. pub fn short(mut self, c: char) -> Self { self.short_flag = Some(c); @@ -109,27 +134,43 @@ impl CliEntrypoint { /// Get the Rust type for this entrypoint. /// - /// Uses the language module's type system mapping for standard types, - /// with special handling for IR-specific type names like "List". + /// Uses the language module's type system mapping for standard types. + /// Collection types are derived from cardinality, not type_id string matching. pub fn rust_type(&self) -> String { - // Map IR type names to abstract type names for language module - let abstract_type = match self.type_id.as_str() { - "List" => "List", - other => other, - }; - lang_rust_type(abstract_type) + if self.cardinality.allows_many() { + // Collection entrypoint — element type is type_id + let element = match self.type_id.as_str() { + "List" | "Set" => "String", // Legacy: "List"/"Set" as type_id means list-of-strings + other => other, + }; + lang_rust_type(&format!("List<{}>", element)) + } else { + lang_rust_type(&self.type_id) + } } /// Get the Value constructor for this type. + /// + /// Collection types are derived from cardinality, not type_id string matching. pub fn value_constructor(&self) -> &str { - match self.type_id.as_str() { - "String" => "Value::Str", - "Int" => "Value::Int", - "Bool" => "Value::Bool", - "List" => "Value::str_list", - _ => "Value::Str", + if self.cardinality.allows_many() { + "Value::str_list" + } else { + match self.type_id.as_str() { + "String" => "Value::Str", + "Int" => "Value::Int", + "Bool" => "Value::Bool", + _ => "Value::Str", + } } } + + /// Whether this entrypoint accepts multiple values (repeatable CLI flag). + /// + /// Derived from cardinality, not type_id string matching. + pub fn is_repeatable(&self) -> bool { + self.cardinality.allows_many() + } } /// A boundary node that gets mocked in dry-run. @@ -313,95 +354,99 @@ fn print_help() {{ fn generate_arg_parsing(entrypoints: &[CliEntrypoint]) -> String { let mut code = String::new(); - + // Declare variables with defaults for ep in entrypoints { let default = ep.default_value.as_deref().unwrap_or_default(); - match ep.type_id.as_str() { - "String" => { - if default.is_empty() { - code.push_str(&format!(" let mut {}: Option = None;\n", ep.var_name())); - } else { + if ep.is_repeatable() { + // Collection entrypoints: Vec + code.push_str(&format!(" let mut {}: Vec = vec![];\n", ep.var_name())); + } else { + match ep.type_id.as_str() { + "String" => { + if default.is_empty() { + code.push_str(&format!(" let mut {}: Option = None;\n", ep.var_name())); + } else { + code.push_str(&format!(" let mut {} = \"{}\".to_string();\n", ep.var_name(), default)); + } + } + "Bool" => { + let default_bool = default == "true"; + code.push_str(&format!(" let mut {} = {};\n", ep.var_name(), default_bool)); + } + "Int" => { + let default_int = default.parse::().unwrap_or(0); + code.push_str(&format!(" let mut {} = {}i64;\n", ep.var_name(), default_int)); + } + _ => { code.push_str(&format!(" let mut {} = \"{}\".to_string();\n", ep.var_name(), default)); } } - "Bool" => { - let default_bool = default == "true"; - code.push_str(&format!(" let mut {} = {};\n", ep.var_name(), default_bool)); - } - "Int" => { - let default_int = default.parse::().unwrap_or(0); - code.push_str(&format!(" let mut {} = {}i64;\n", ep.var_name(), default_int)); - } - "List" => { - code.push_str(&format!(" let mut {}: Vec = vec![];\n", ep.var_name())); - } - _ => { - code.push_str(&format!(" let mut {} = \"{}\".to_string();\n", ep.var_name(), default)); - } } } code.push_str(" let mut dry_run = false;\n"); code.push('\n'); - + // Parse loop code.push_str(" let mut i = 1;\n"); code.push_str(" while i < args.len() {\n"); code.push_str(" match args[i].as_str() {\n"); - + for ep in entrypoints { let flag = ep.flag_name(); let short = ep.short_flag.map(|c| format!("\"-{}\" | ", c)).unwrap_or_default(); - - match ep.type_id.as_str() { - "Bool" => { - code.push_str(&format!( - " {}\"--{}\" => {} = true,\n", - short, flag, ep.var_name() - )); - } - "List" => { - code.push_str(&format!( - " {}\"--{}\" => {{\n", - short, flag - )); - code.push_str(" i += 1;\n"); - code.push_str(&format!( - " if i < args.len() {{ {}.push(args[i].clone()); }}\n", - ep.var_name() - )); - code.push_str(" }\n"); - } - _ => { - code.push_str(&format!( - " {}\"--{}\" => {{\n", - short, flag - )); - code.push_str(" i += 1;\n"); - if ep.default_value.is_some() || ep.type_id != "String" { + + if ep.is_repeatable() { + // Repeatable flags: --flag val --flag val2 + code.push_str(&format!( + " {}\"--{}\" => {{\n", + short, flag + )); + code.push_str(" i += 1;\n"); + code.push_str(&format!( + " if i < args.len() {{ {}.push(args[i].clone()); }}\n", + ep.var_name() + )); + code.push_str(" }\n"); + } else { + match ep.type_id.as_str() { + "Bool" => { code.push_str(&format!( - " if i < args.len() {{ {} = args[i].clone(){}; }}\n", - ep.var_name(), - if ep.type_id == "Int" { ".parse().unwrap_or(0)" } else { "" } + " {}\"--{}\" => {} = true,\n", + short, flag, ep.var_name() )); - } else { + } + _ => { code.push_str(&format!( - " if i < args.len() {{ {} = Some(args[i].clone()); }}\n", - ep.var_name() + " {}\"--{}\" => {{\n", + short, flag )); + code.push_str(" i += 1;\n"); + if ep.default_value.is_some() || ep.type_id != "String" { + code.push_str(&format!( + " if i < args.len() {{ {} = args[i].clone(){}; }}\n", + ep.var_name(), + if ep.type_id == "Int" { ".parse().unwrap_or(0)" } else { "" } + )); + } else { + code.push_str(&format!( + " if i < args.len() {{ {} = Some(args[i].clone()); }}\n", + ep.var_name() + )); + } + code.push_str(" }\n"); } - code.push_str(" }\n"); } } } - + code.push_str(" \"-n\" | \"--dry-run\" => dry_run = true,\n"); code.push_str(" \"-h\" | \"--help\" => { print_help(); return; }\n"); code.push_str(" _ => {}\n"); code.push_str(" }\n"); code.push_str(" i += 1;\n"); code.push_str(" }\n"); - + code } @@ -421,30 +466,31 @@ fn generate_mock_setup(boundaries: &[CliBoundary]) -> String { fn generate_print_inputs(entrypoints: &[CliEntrypoint]) -> String { let mut code = String::new(); for ep in entrypoints { - match ep.type_id.as_str() { - "Bool" => { - code.push_str(&format!( - " println!(\" {}: {{}}\", {});\n", - ep.port_name, ep.var_name() - )); - } - "List" => { - code.push_str(&format!( - " println!(\" {}: {{:?}}\", {});\n", - ep.port_name, ep.var_name() - )); - } - _ => { - if ep.default_value.is_some() { + if ep.is_repeatable() { + code.push_str(&format!( + " println!(\" {}: {{:?}}\", {});\n", + ep.port_name, ep.var_name() + )); + } else { + match ep.type_id.as_str() { + "Bool" => { code.push_str(&format!( " println!(\" {}: {{}}\", {});\n", ep.port_name, ep.var_name() )); - } else { - code.push_str(&format!( - " println!(\" {}: {{}}\", {}.as_deref().unwrap_or(\"\"));\n", - ep.port_name, ep.var_name() - )); + } + _ => { + if ep.default_value.is_some() { + code.push_str(&format!( + " println!(\" {}: {{}}\", {});\n", + ep.port_name, ep.var_name() + )); + } else { + code.push_str(&format!( + " println!(\" {}: {{}}\", {}.as_deref().unwrap_or(\"\"));\n", + ep.port_name, ep.var_name() + )); + } } } } @@ -479,11 +525,14 @@ fn generate_help_options(entrypoints: &[CliEntrypoint]) -> String { for ep in entrypoints { let flag = ep.flag_name(); let short = ep.short_flag.map(|c| format!("-{}, ", c)).unwrap_or_else(|| " ".to_string()); - let type_hint = match ep.type_id.as_str() { - "Bool" => "", - "Int" => " ", - "List" => " ...", - _ => " ", + let type_hint = if ep.is_repeatable() { + " ..." + } else { + match ep.type_id.as_str() { + "Bool" => "", + "Int" => " ", + _ => " ", + } }; code.push_str(&format!( " println!(\" {}--{}{:width$} {}\");\n", diff --git a/core/codegen/src/testgen/codegen.rs b/core/codegen/src/testgen/codegen.rs index 6a967030475..1d4863831ff 100644 --- a/core/codegen/src/testgen/codegen.rs +++ b/core/codegen/src/testgen/codegen.rs @@ -1929,6 +1929,70 @@ fn render_output_matcher_check(matcher: &OutputMatcher, var_name: &str) -> Strin }; RustRenderer.render_assert(&assert, 0) } + OutputMatcher::IsBool => { + let assert = Assert::True { + expr: Expr::var(&output_var).method("as_bool", vec![]).method("is_some", vec![]), + message: format!("expected Bool for {}", output_var), + }; + RustRenderer.render_assert(&assert, 0) + } + OutputMatcher::IsInt => { + let assert = Assert::True { + expr: Expr::var(&output_var).method("as_int", vec![]).method("is_some", vec![]), + message: format!("expected Int for {}", output_var), + }; + RustRenderer.render_assert(&assert, 0) + } + OutputMatcher::IsString => { + let assert = Assert::True { + expr: Expr::var(&output_var).method("as_str", vec![]).method("is_some", vec![]), + message: format!("expected String for {}", output_var), + }; + RustRenderer.render_assert(&assert, 0) + } + OutputMatcher::IsRequest => { + let assert = Assert::True { + expr: Expr::var(&output_var).method("as_request", vec![]).method("is_some", vec![]), + message: format!("expected Request for {}", output_var), + }; + RustRenderer.render_assert(&assert, 0) + } + OutputMatcher::IsResponse => { + let assert = Assert::True { + expr: Expr::var(&output_var).method("as_response", vec![]).method("is_some", vec![]), + message: format!("expected Response for {}", output_var), + }; + RustRenderer.render_assert(&assert, 0) + } + OutputMatcher::IntGe(threshold) => { + // assert!(var.as_int().unwrap() >= threshold) + let assert = Assert::True { + expr: Expr::var(&output_var) + .method("as_int", vec![]) + .method("is_some_and", vec![ + Expr::Closure { + args: vec!["n".to_string()], + body: Box::new(Expr::Str(format!("n >= {}", threshold))), + }, + ]), + message: format!("expected Int >= {} for {}", threshold, output_var), + }; + RustRenderer.render_assert(&assert, 0) + } + OutputMatcher::IntLe(threshold) => { + let assert = Assert::True { + expr: Expr::var(&output_var) + .method("as_int", vec![]) + .method("is_some_and", vec![ + Expr::Closure { + args: vec!["n".to_string()], + body: Box::new(Expr::Str(format!("n <= {}", threshold))), + }, + ]), + message: format!("expected Int <= {} for {}", threshold, output_var), + }; + RustRenderer.render_assert(&assert, 0) + } OutputMatcher::Satisfies { description, .. } => { format!("// Custom assertion: {}\n", description) } diff --git a/core/exec/src/error.rs b/core/exec/src/error.rs index b4321173a58..42dd28993c6 100644 --- a/core/exec/src/error.rs +++ b/core/exec/src/error.rs @@ -10,6 +10,17 @@ impl ExecError { pub fn new(msg: impl Into) -> Self { Self(msg.into()) } + + /// Add context to this error, producing a new error with the context prepended. + /// + /// ```ignore + /// let err = ExecError::new("file not found"); + /// let with_ctx = err.context("reading config"); + /// assert_eq!(with_ctx.to_string(), "reading config: file not found"); + /// ``` + pub fn context(self, ctx: impl fmt::Display) -> Self { + Self(format!("{}: {}", ctx, self.0)) + } } impl fmt::Display for ExecError { @@ -31,3 +42,33 @@ impl From<&str> for ExecError { Self(s.to_string()) } } + +/// Extension trait for adding context to `Result`. +/// +/// ```ignore +/// use gunbc_exec::{ExecError, ResultExt}; +/// +/// fn load_config() -> Result { +/// Err(ExecError::new("file not found")) +/// } +/// +/// let result = load_config().context("loading config"); +/// assert_eq!(result.unwrap_err().to_string(), "loading config: file not found"); +/// ``` +pub trait ResultExt { + /// Add context to the error case. + fn context(self, ctx: impl fmt::Display) -> Result; + + /// Add lazily-evaluated context to the error case. + fn with_context String>(self, f: F) -> Result; +} + +impl ResultExt for Result { + fn context(self, ctx: impl fmt::Display) -> Result { + self.map_err(|e| e.context(ctx)) + } + + fn with_context String>(self, f: F) -> Result { + self.map_err(|e| e.context(f())) + } +} diff --git a/core/exec/src/helpers.rs b/core/exec/src/helpers.rs index dfd02005755..0a5abcd1177 100644 --- a/core/exec/src/helpers.rs +++ b/core/exec/src/helpers.rs @@ -248,6 +248,49 @@ impl Default for OutputMap { } } +// --------------------------------------------------------------------------- +// Skip propagation +// --------------------------------------------------------------------------- + +/// Check if an input is `Value::Skipped` and, if so, propagate it to all +/// listed output keys. +/// +/// Returns `Some(Ok(outputs))` when the input was skipped (caller should +/// return early), or `None` when the input was present and execution should +/// continue normally. +/// +/// This eliminates the repeated pattern: +/// ```ignore +/// if matches!(inputs.get("response"), Some(Value::Skipped)) { +/// return OutputMap::new() +/// .value("out1", Value::Skipped) +/// .value("out2", Value::Skipped) +/// .ok(); +/// } +/// ``` +/// +/// becomes: +/// ```ignore +/// if let Some(result) = propagate_skipped(&inputs, "response", &["out1", "out2"]) { +/// return result; +/// } +/// ``` +pub fn propagate_skipped( + inputs: &HashMap, + input_key: &str, + output_keys: &[&str], +) -> Option, ExecError>> { + if matches!(inputs.get(input_key), Some(Value::Skipped)) { + let mut map = OutputMap::new(); + for key in output_keys { + map = map.value(key, Value::Skipped); + } + Some(map.ok()) + } else { + None + } +} + // --------------------------------------------------------------------------- // TransportResponse extraction // --------------------------------------------------------------------------- @@ -388,4 +431,33 @@ mod tests { }); assert!(resp.require_shell().is_err()); } + + #[test] + fn propagate_skipped_returns_some_when_skipped() { + let mut inputs = HashMap::new(); + inputs.insert("response".to_string(), Value::Skipped); + + let result = propagate_skipped(&inputs, "response", &["out1", "out2"]); + assert!(result.is_some()); + + let outputs = result.unwrap().unwrap(); + assert_eq!(outputs.get("out1"), Some(&Value::Skipped)); + assert_eq!(outputs.get("out2"), Some(&Value::Skipped)); + } + + #[test] + fn propagate_skipped_returns_none_when_present() { + let mut inputs = HashMap::new(); + inputs.insert("response".to_string(), Value::Str("data".to_string())); + + let result = propagate_skipped(&inputs, "response", &["out1"]); + assert!(result.is_none()); + } + + #[test] + fn propagate_skipped_returns_none_when_missing() { + let inputs = HashMap::new(); + let result = propagate_skipped(&inputs, "response", &["out1"]); + assert!(result.is_none()); + } } diff --git a/core/exec/src/lib.rs b/core/exec/src/lib.rs index 8cd44a7b7de..e015772ba3e 100644 --- a/core/exec/src/lib.rs +++ b/core/exec/src/lib.rs @@ -37,15 +37,16 @@ pub mod pattern_op; pub mod topo; pub use ci_context::CiContext; -pub use error::ExecError; +pub use error::{ExecError, ResultExt}; pub use execute::{ execute, execute_single_node, execute_with_ci, execute_with_mode, execute_with_mode_and_ci, ExecutionLog, ExecutionMode, LogEntry, }; pub use helpers::{ optional_bool, optional_json, optional_map_str_str, optional_str, optional_str_list, - require_bool, require_int, require_json, require_map_str_str, require_request, require_response, - require_str, require_str_list, require_value, OutputMap, TransportResponseExt, + propagate_skipped, require_bool, require_int, require_json, require_map_str_str, + require_request, require_response, require_str, require_str_list, require_value, + OutputMap, TransportResponseExt, }; pub use intercept::{BoundaryMock, BoundaryMocks}; pub use lower::{lower, LowerError}; diff --git a/core/ir/src/transport/mod.rs b/core/ir/src/transport/mod.rs index c4c96c06fce..3a51cb04e25 100644 --- a/core/ir/src/transport/mod.rs +++ b/core/ir/src/transport/mod.rs @@ -210,10 +210,97 @@ impl ShellRequest { } impl ShellResponse { + /// Create a successful shell response (exit code 0). + pub fn ok(stdout: impl Into) -> Self { + Self { + exit_code: 0, + stdout: stdout.into(), + stderr: String::new(), + } + } + + /// Create a failed shell response with the given exit code and stderr. + pub fn failed(exit_code: i32, stderr: impl Into) -> Self { + Self { + exit_code, + stdout: String::new(), + stderr: stderr.into(), + } + } + /// Check if the command succeeded (exit code 0). pub fn success(&self) -> bool { self.exit_code == 0 } + + /// Wrap this response in a [`TransportResponse::Shell`]. + pub fn into_transport_response(self) -> TransportResponse { + TransportResponse::Shell(self) + } +} + +// --------------------------------------------------------------------------- +// From impls for transport request/response types +// --------------------------------------------------------------------------- + +impl From for TransportRequest { + fn from(req: ShellRequest) -> Self { + TransportRequest::Shell(req) + } +} + +impl From for TransportRequest { + fn from(req: RestRequest) -> Self { + TransportRequest::Rest(req) + } +} + +impl From for TransportRequest { + fn from(req: HttpRequest) -> Self { + TransportRequest::Http(req) + } +} + +impl From for TransportRequest { + fn from(req: FileRequest) -> Self { + TransportRequest::File(req) + } +} + +impl From for TransportRequest { + fn from(req: TcpRequest) -> Self { + TransportRequest::Tcp(req) + } +} + +impl From for TransportResponse { + fn from(resp: ShellResponse) -> Self { + TransportResponse::Shell(resp) + } +} + +impl From for TransportResponse { + fn from(resp: RestResponse) -> Self { + TransportResponse::Rest(resp) + } +} + +impl From for TransportResponse { + fn from(resp: HttpResponse) -> Self { + TransportResponse::Http(resp) + } +} + +impl From for TransportResponse { + fn from(resp: FileResponse) -> Self { + TransportResponse::File(resp) + } +} + +impl From for TransportResponse { + fn from(resp: TcpResponse) -> Self { + TransportResponse::Tcp(resp) + } } #[cfg(test)] @@ -234,4 +321,36 @@ mod tests { assert_eq!(req.cwd, Some("/tmp".to_string())); assert_eq!(req.stdin, Some("# Test".to_string())); } + + #[test] + fn test_shell_response_ok() { + let resp = ShellResponse::ok("hello"); + assert!(resp.success()); + assert_eq!(resp.stdout, "hello"); + assert_eq!(resp.stderr, ""); + assert_eq!(resp.exit_code, 0); + } + + #[test] + fn test_shell_response_failed() { + let resp = ShellResponse::failed(1, "error"); + assert!(!resp.success()); + assert_eq!(resp.stdout, ""); + assert_eq!(resp.stderr, "error"); + assert_eq!(resp.exit_code, 1); + } + + #[test] + fn test_from_shell_request() { + let req = ShellRequest::new("ls"); + let transport: TransportRequest = req.into(); + assert!(matches!(transport, TransportRequest::Shell(_))); + } + + #[test] + fn test_from_shell_response() { + let resp = ShellResponse::ok("ok"); + let transport: TransportResponse = resp.into(); + assert!(matches!(transport, TransportResponse::Shell(_))); + } } diff --git a/core/test/src/mock_spec.rs b/core/test/src/mock_spec.rs index 64789e27e54..1f88b7a3432 100644 --- a/core/test/src/mock_spec.rs +++ b/core/test/src/mock_spec.rs @@ -702,7 +702,9 @@ impl NodeExample { /// - Exact: value must equal expected exactly /// - Contains: string output must contain substring /// - NonEmpty: value must be non-empty (strings, lists) -/// - Satisfies: custom predicate function +/// - Typed matchers: IsBool, IsInt, IsString, IsRequest, IsResponse +/// - IntGe/IntLe: integer range checks +/// - Satisfies: custom predicate function (fallback for complex checks) #[derive(Clone)] pub enum OutputMatcher { /// Output must equal this value exactly @@ -711,7 +713,27 @@ pub enum OutputMatcher { Contains(String), /// Output must be non-empty NonEmpty, - /// Output must satisfy a custom predicate + /// Output must be a boolean (any value). + /// + /// Unlike `Satisfies`, this generates a real codegen assertion. + IsBool, + /// Output must be an integer (any value). + IsInt, + /// Output must be a string (any value). + IsString, + /// Output must be a transport request. + IsRequest, + /// Output must be a transport response. + IsResponse, + /// Integer must be >= threshold. + IntGe(i64), + /// Integer must be <= threshold. + IntLe(i64), + /// Output must satisfy a custom predicate. + /// + /// Prefer typed matchers (IsBool, IntGe, etc.) when possible, since + /// codegen can emit real assertions for them. `Satisfies` currently + /// emits a comment in generated tests. Satisfies { description: String, predicate: fn(&Value) -> bool, @@ -726,6 +748,13 @@ impl std::fmt::Debug for OutputMatcher { OutputMatcher::Exact(v) => write!(f, "Exact({:?})", v), OutputMatcher::Contains(s) => write!(f, "Contains(\"{}\")", s), OutputMatcher::NonEmpty => write!(f, "NonEmpty"), + OutputMatcher::IsBool => write!(f, "IsBool"), + OutputMatcher::IsInt => write!(f, "IsInt"), + OutputMatcher::IsString => write!(f, "IsString"), + OutputMatcher::IsRequest => write!(f, "IsRequest"), + OutputMatcher::IsResponse => write!(f, "IsResponse"), + OutputMatcher::IntGe(n) => write!(f, "IntGe({})", n), + OutputMatcher::IntLe(n) => write!(f, "IntLe({})", n), OutputMatcher::Satisfies { description, .. } => { write!(f, "Satisfies({})", description) } @@ -782,6 +811,36 @@ impl OutputMatcher { Value::Set(_) => Err("expected non-empty set".into()), _ => Ok(()), // Other types considered non-empty }, + OutputMatcher::IsBool => match value { + Value::Bool(_) => Ok(()), + _ => Err(format!("expected Bool, got {:?}", value)), + }, + OutputMatcher::IsInt => match value { + Value::Int(_) => Ok(()), + _ => Err(format!("expected Int, got {:?}", value)), + }, + OutputMatcher::IsString => match value { + Value::Str(_) => Ok(()), + _ => Err(format!("expected String, got {:?}", value)), + }, + OutputMatcher::IsRequest => match value { + Value::Request(_) => Ok(()), + _ => Err(format!("expected Request, got {:?}", value)), + }, + OutputMatcher::IsResponse => match value { + Value::Response(_) => Ok(()), + _ => Err(format!("expected Response, got {:?}", value)), + }, + OutputMatcher::IntGe(threshold) => match value { + Value::Int(n) if n >= threshold => Ok(()), + Value::Int(n) => Err(format!("expected Int >= {}, got {}", threshold, n)), + _ => Err(format!("expected Int, got {:?}", value)), + }, + OutputMatcher::IntLe(threshold) => match value { + Value::Int(n) if n <= threshold => Ok(()), + Value::Int(n) => Err(format!("expected Int <= {}, got {}", threshold, n)), + _ => Err(format!("expected Int, got {:?}", value)), + }, OutputMatcher::Satisfies { description, predicate } => { if predicate(value) { Ok(()) @@ -796,10 +855,11 @@ impl OutputMatcher { /// Whether this matcher produces an executable assertion (vs. a comment). /// /// Used by codegen to decide whether to prefix the output variable with `_`. + /// All typed matchers (IsBool, IntGe, etc.) generate real assertions. + /// Only `Satisfies` and `Any` don't. pub fn generates_assertion(&self) -> bool { - matches!(self, OutputMatcher::Exact(_) | OutputMatcher::Contains(_) | OutputMatcher::NonEmpty) + !matches!(self, OutputMatcher::Satisfies { .. } | OutputMatcher::Any) } - } #[cfg(test)] diff --git a/gunbc-dag/src/ci/graph_mock.rs b/gunbc-dag/src/ci/graph_mock.rs index b0152b8114e..14b79a79e48 100644 --- a/gunbc-dag/src/ci/graph_mock.rs +++ b/gunbc-dag/src/ci/graph_mock.rs @@ -159,26 +159,17 @@ pub fn ci_mock_spec() -> MockSpec { ) .node_example( NodeExample::new("prepare_codegen_cmd") - .output("skip", OutputMatcher::Satisfies { - description: "skip is a boolean".into(), - predicate: |v| matches!(v, Value::Bool(_)), - }) + .output("skip", OutputMatcher::IsBool) .description("Codegen command prepare emits skip flag"), ) .node_example( NodeExample::new("prepare_build") - .output("skip", OutputMatcher::Satisfies { - description: "skip is a boolean".into(), - predicate: |v| matches!(v, Value::Bool(_)), - }) + .output("skip", OutputMatcher::IsBool) .description("Build prepare emits skip flag"), ) .node_example( NodeExample::new("prepare_test") - .output("skip", OutputMatcher::Satisfies { - description: "skip is a boolean".into(), - predicate: |v| matches!(v, Value::Bool(_)), - }) + .output("skip", OutputMatcher::IsBool) .description("Test prepare emits skip flag"), ) .node_example( @@ -195,14 +186,8 @@ pub fn ci_mock_spec() -> MockSpec { ) .node_example( NodeExample::new("parse_clippy_lint") - .output("lint_success", OutputMatcher::Satisfies { - description: "lint_success is a boolean".into(), - predicate: |v| matches!(v, Value::Bool(_)), - }) - .output("lint_skipped", OutputMatcher::Satisfies { - description: "lint_skipped is a boolean".into(), - predicate: |v| matches!(v, Value::Bool(_)), - }) + .output("lint_success", OutputMatcher::IsBool) + .output("lint_skipped", OutputMatcher::IsBool) .description("Clippy result parse produces success/skipped flags"), ) // Primitive nodes — tested in their own crates diff --git a/gunbc-dag/src/makegen/graph_mock.rs b/gunbc-dag/src/makegen/graph_mock.rs index 55db7553b7a..4da1a201a60 100644 --- a/gunbc-dag/src/makegen/graph_mock.rs +++ b/gunbc-dag/src/makegen/graph_mock.rs @@ -66,10 +66,7 @@ pub fn makegen_mock_spec() -> MockSpec { // Node I/O examples: verify pure node behavior .node_example( NodeExample::new("load_registry") - .output("tool_count", OutputMatcher::Satisfies { - description: "at least 2 tools registered".into(), - predicate: |v| matches!(v, Value::Int(n) if *n >= 2), - }) + .output("tool_count", OutputMatcher::IntGe(2)) .output("tool_names", OutputMatcher::non_empty()) .description("Default registry loads with expected tools"), ) diff --git a/gunbc-dag/src/makegen/registry.rs b/gunbc-dag/src/makegen/registry.rs index 36057a46442..c7a14e4f724 100644 --- a/gunbc-dag/src/makegen/registry.rs +++ b/gunbc-dag/src/makegen/registry.rs @@ -416,9 +416,7 @@ impl ToolInfo { cli_flag: format!("--{}", ep.flag_name()), type_hint: ep.type_id.clone(), default: ep.default_value.clone(), - // TODO: Replace with cardinality.allows_many() when CliEntrypoint - // carries Cardinality instead of type_id string. - repeatable: ep.type_id == "List" || ep.type_id == "Set", + repeatable: ep.cardinality.allows_many(), }); } } From fe1afe33df761328553c74221f7afb29a164fb32 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Feb 2026 18:55:14 +0000 Subject: [PATCH 2/3] Call-site migrations + fix cardinality Empty absence testing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Migrate all call sites to use the new helpers introduced in the previous commit, eliminating boilerplate and manual construction: - propagate_skipped(): 8 sites in 3 files (bootstrap/ops, ci/ops, llm-ops) — replaces 5-10 line if-matches-return blocks - ShellResponse::ok()/failed(): graph_mock files, bin/ci, ops tests, git-ops tests — replaces 3-field struct literals - From impls: TransportResponse/TransportRequest wrapping replaced with .into() across graph_mock files, bin/ci, ops tests Fix cardinality Empty absence testing (Hack 5): - cardinality_case_mock_value() now emits Value::Unit for scalar Empty (String, Bool, Int) instead of concrete "empty content" (false, 0, ""). Collection types keep empty collections. - Aligns with contract::witnesses() which already uses Value::Unit for absence. Cardinality boundary tests now exercise the actual absent-vs-present boundary. 14 files changed, -84 net lines. 1062 tests pass, zero clippy warnings. https://claude.ai/code/session_01EaBXwSmZrbVcpbFoV44Aju --- TODO/TODO_hacks.md | 20 ++++++--- TODO/TODO_type_system.md | 3 ++ TODO/consolidation.md | 4 +- core/codegen/src/testgen/codegen.rs | 16 +++++-- core/exec/src/helpers.rs | 6 +-- gunbc-dag/src/bin/ci.rs | 28 ++++-------- gunbc-dag/src/bootstrap/graph_mock.rs | 20 ++------- gunbc-dag/src/bootstrap/ops.rs | 10 ++--- gunbc-dag/src/ci/graph_mock.rs | 22 +++------ gunbc-dag/src/ci/ops.rs | 65 +++++++-------------------- gunbc-dag/src/makegen/graph_mock.rs | 8 +--- lib/git-ops/src/lib.rs | 12 +---- lib/llm-ops/src/lib.rs | 22 +++------ lib/review/src/graph_mock.rs | 22 +++------ 14 files changed, 87 insertions(+), 171 deletions(-) diff --git a/TODO/TODO_hacks.md b/TODO/TODO_hacks.md index c37e4680913..ccfd92e013a 100644 --- a/TODO/TODO_hacks.md +++ b/TODO/TODO_hacks.md @@ -303,7 +303,12 @@ represented as empty collection). - [x] Hack 3: Make `NonEmpty` codegen type-aware (or add `Value::is_empty()`) - [x] Hack 4: Replace `value_to_rust_literal` catch-all with `panic!()` or `compile_error!()` - [x] Hack 4: Fix `Value::List` filter_map silent dropping of non-string elements -- [ ] Hack 5: Make cardinality Empty tests represent absence, not empty content +- [x] Hack 5: Make cardinality Empty tests represent absence, not empty content + - `cardinality_case_mock_value()` now emits `Value::Unit` for scalar Empty + (String, Bool, Int) instead of concrete "empty content" (`false`, `0`, `""`) + - Collection types (List, Set) still use empty collections (correct: zero elements) + - Aligns with `contract::witnesses()` which already uses `Value::Unit` for absence + - Cardinality boundary tests now exercise the actual absent-vs-present boundary ## Notes @@ -320,9 +325,10 @@ represented as empty collection). source without closure references. `Satisfies` remains only for complex predicates that can't be expressed as simple type/range checks. Existing usages in CI and makegen graph mocks have been migrated. -- Hack 5 is the most architecturally important — it blocks meaningful - cardinality boundary testing. If Empty doesn't test absence, the - B.3 tests exercise a subset of what they claim to cover. -- Only hacks 2 (parse node examples) and 5 (absence testing) remain. - Both require deeper infrastructure changes (transport serialization - and `Option` semantics respectively). +- **Hack 5 resolved**: Scalar Empty now uses `Value::Unit` (absence), + matching the behavior of `contract::witnesses()`. No infrastructure + change to `BoundaryMocks` was needed — `Value::Unit` already serves + as the "absent" signal within the existing `Value` type. +- Only hack 2 (parse node examples with real transport responses) remains. + This requires serializing full transport response constructors in + generated test code, which the `ValueExpr` pipeline already supports. diff --git a/TODO/TODO_type_system.md b/TODO/TODO_type_system.md index 625e41864be..c1db8d8cc0c 100644 --- a/TODO/TODO_type_system.md +++ b/TODO/TODO_type_system.md @@ -160,6 +160,9 @@ a cardinality indicator. - [x] Add `From for TransportRequest` / `TransportResponse` impls for all transport types - [x] Add `ExecError::context()` and `ResultExt` trait for structured error context - [x] Add `propagate_skipped()` helper for skip propagation pattern +- [x] Migrate all `propagate_skipped()` call sites (8 sites in 3 files) +- [x] Migrate `ShellResponse::ok()/failed()` and `From` impls to call sites +- [x] Fix cardinality Empty codegen to use `Value::Unit` (absence) for scalar types ## Design Principles (from review) diff --git a/TODO/consolidation.md b/TODO/consolidation.md index 55329fc15c1..a456ef33c96 100644 --- a/TODO/consolidation.md +++ b/TODO/consolidation.md @@ -908,7 +908,9 @@ This is fine; it's infrastructure code, not op code. ### High priority (remaining) - [ ] Add `InputsExt` trait to replace free-function `require_*/optional_*` calls — shrinks import lists -- [ ] Migrate call sites to use `propagate_skipped`, `ExecError::context()`, `ShellResponse::ok()` etc. +- [x] Migrate call sites to use `propagate_skipped` (8 sites, 3 files) +- [x] Migrate call sites to use `ShellResponse::ok()/failed()` + `From` impls (graph_mock, bin, ops, tests) +- [ ] Migrate remaining call sites to use `ExecError::context()` / `ResultExt` (~42 sites, 12 files) ### Medium priority - [ ] Migrate remaining raw `HashMap::new()` output construction to `OutputMap` (9 sites, 5 files) — §15 diff --git a/core/codegen/src/testgen/codegen.rs b/core/codegen/src/testgen/codegen.rs index 1d4863831ff..b34fd112c7e 100644 --- a/core/codegen/src/testgen/codegen.rs +++ b/core/codegen/src/testgen/codegen.rs @@ -2009,13 +2009,21 @@ fn render_output_matcher_check(matcher: &OutputMatcher, var_name: &str) -> Strin /// Builds a ValueExpr and renders it via RustRenderer. The type_id string /// matching is a known limitation — ideally this should consult DagAnalysis /// cardinality data instead (see TODO_codegen_dag.md, "severed analysis"). +/// +/// For the `Empty` case, scalar types emit `Value::Unit` (absence), not +/// concrete "empty content" like `false` or `0`. This matches the behavior +/// of `contract::witnesses()` and ensures cardinality boundary tests actually +/// verify the absent-vs-present boundary rather than exercising the "one +/// element" path with a zero-like value. Collection types emit empty +/// collections (which correctly represent zero elements). fn cardinality_case_mock_value(case: CardinalityCase, type_id: &str) -> String { let expr = match case { CardinalityCase::Empty => match type_id { - "String" => ValueExpr::Str(String::new()), - "Bool" => ValueExpr::Bool(false), - "Int" | "i64" | "i32" => ValueExpr::Int(0), - _ => ValueExpr::List(vec![]), + // Collection types: empty collection = zero elements (correct) + "List" => ValueExpr::List(vec![]), + "Set" => ValueExpr::List(vec![]), // rendered as empty set + // Scalar types: Value::Unit = absent (not a value with empty content) + _ => ValueExpr::Unit, }, CardinalityCase::One => match type_id { "String" => ValueExpr::Str("".to_string()), diff --git a/core/exec/src/helpers.rs b/core/exec/src/helpers.rs index 0a5abcd1177..a90dcc2569d 100644 --- a/core/exec/src/helpers.rs +++ b/core/exec/src/helpers.rs @@ -413,11 +413,7 @@ mod tests { #[test] fn require_shell_on_shell_response() { - let resp = TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: "ok".to_string(), - stderr: String::new(), - }); + let resp: TransportResponse = ShellResponse::ok("ok").into(); let shell = resp.require_shell().unwrap(); assert_eq!(shell.stdout, "ok"); } diff --git a/gunbc-dag/src/bin/ci.rs b/gunbc-dag/src/bin/ci.rs index 1375719ea0c..7000da4dbc0 100644 --- a/gunbc-dag/src/bin/ci.rs +++ b/gunbc-dag/src/bin/ci.rs @@ -16,7 +16,7 @@ use gunbc_dag::build_ci_graph; use gunbc_exec::{execute_with_mode_and_ci, BoundaryMocks, CiContext, ExecutionMode}; -use gunbc_ir::transport::{FileOp, FileResponse, ShellResponse, TransportResponse}; +use gunbc_ir::transport::{FileOp, FileResponse, ShellResponse}; use gunbc_ir::Value; use std::env; use std::process; @@ -50,55 +50,43 @@ fn main() { // execute_deps_exists: file exists check for deps.toml mocks.set_value("execute_deps_exists", "response", Value::Response( - TransportResponse::File(FileResponse { + FileResponse { path: "deps.toml".to_string(), operation: FileOp::Exists, success: true, content: None, exists: Some(false), error: None, - }) + }.into() )); // execute_codegen_exists: file exists check for buck-out/gen/bin mocks.set_value("execute_codegen_exists", "response", Value::Response( - TransportResponse::File(FileResponse { + FileResponse { path: "buck-out/gen/bin".to_string(), operation: FileOp::Exists, success: true, content: None, exists: Some(true), // Pretend codegen already exists error: None, - }) + }.into() )); // execute_codegen: shell command (skipped when codegen exists) mocks.set_value("execute_codegen", "response", Value::Response( - TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: String::new(), - stderr: String::new(), - }) + ShellResponse::ok("").into() )); mocks.set_value("execute_codegen", "skip", Value::Bool(true)); // execute_build: shell command for cargo build mocks.set_value("execute_build", "response", Value::Response( - TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: "".to_string(), - stderr: String::new(), - }) + ShellResponse::ok("").into() )); mocks.set_value("execute_build", "skip", Value::Bool(false)); // execute_test: shell command for cargo test mocks.set_value("execute_test", "response", Value::Response( - TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: "".to_string(), - stderr: String::new(), - }) + ShellResponse::ok("").into() )); mocks.set_value("execute_test", "skip", Value::Bool(false)); diff --git a/gunbc-dag/src/bootstrap/graph_mock.rs b/gunbc-dag/src/bootstrap/graph_mock.rs index c9473d84d9d..6c87bab09d0 100644 --- a/gunbc-dag/src/bootstrap/graph_mock.rs +++ b/gunbc-dag/src/bootstrap/graph_mock.rs @@ -4,7 +4,7 @@ //! - What mock values boundary nodes provide //! - Resource simulations for file system operations -use gunbc_ir::transport::{ShellResponse, TransportResponse}; +use gunbc_ir::transport::ShellResponse; use gunbc_ir::Value; use gunbc_test::{MockSpec, NodeExample, OutputMatcher}; @@ -43,20 +43,12 @@ pub fn bootstrap_mock_spec() -> MockSpec { .transport_mock( "execute_scan_workspace", "response", - Value::Response(TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: "crates/bar\ncrates/foo\n".to_string(), - stderr: String::new(), - })), + Value::Response(ShellResponse::ok("crates/bar\ncrates/foo\n").into()), ) .transport_mock( "execute_makefile_transport", "makefile_response", - Value::Response(TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: String::new(), - stderr: String::new(), - })), + Value::Response(ShellResponse::ok("").into()), ) .transport_mock( "execute_makefile_transport", @@ -71,11 +63,7 @@ pub fn bootstrap_mock_spec() -> MockSpec { .transport_mock( "execute_gitignore_transport", "gitignore_response", - Value::Response(TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: String::new(), - stderr: String::new(), - })), + Value::Response(ShellResponse::ok("").into()), ) .transport_mock( "execute_gitignore_transport", diff --git a/gunbc-dag/src/bootstrap/ops.rs b/gunbc-dag/src/bootstrap/ops.rs index 44840688ca9..1bd924bd77a 100644 --- a/gunbc-dag/src/bootstrap/ops.rs +++ b/gunbc-dag/src/bootstrap/ops.rs @@ -3,7 +3,7 @@ //! All I/O happens through explicit `TransportOps::Execute` nodes in the DAG. //! The ops here are PURE (no I/O) - they prepare requests and parse responses. -use gunbc_exec::{ExecError, Executable, OutputMap, require_response}; +use gunbc_exec::{ExecError, Executable, OutputMap, propagate_skipped, require_response}; use gunbc_ir::transport::{ShellRequest, TransportRequest, TransportResponse}; use gunbc_ir::Value; use std::collections::HashMap; @@ -75,12 +75,8 @@ fn execute_prepare_scan_workspace(_inputs: HashMap) -> Result) -> Result, ExecError> { - // Handle skipped response (upstream transport was skipped) - if matches!(inputs.get("response"), Some(Value::Skipped)) { - return OutputMap::new() - .value("crate_count", Value::Skipped) - .value("crate_names", Value::Skipped) - .ok(); + if let Some(result) = propagate_skipped(&inputs, "response", &["crate_count", "crate_names"]) { + return result; } let response = require_response(&inputs, "response")?; diff --git a/gunbc-dag/src/ci/graph_mock.rs b/gunbc-dag/src/ci/graph_mock.rs index 14b79a79e48..beb7e9b43de 100644 --- a/gunbc-dag/src/ci/graph_mock.rs +++ b/gunbc-dag/src/ci/graph_mock.rs @@ -4,7 +4,7 @@ //! - What mock values boundary nodes provide //! - Resource simulations for CI operations -use gunbc_ir::transport::{FileOp, FileResponse, ShellResponse, TransportResponse}; +use gunbc_ir::transport::{FileOp, FileResponse, ShellResponse}; use gunbc_ir::Value; use gunbc_test::{MockSpec, NodeExample, OutputMatcher}; @@ -39,27 +39,27 @@ pub fn ci_mock_spec() -> MockSpec { .transport_mock( "execute_deps_exists", "response", - Value::Response(TransportResponse::File(FileResponse { + Value::Response(FileResponse { path: "deps.toml".into(), operation: FileOp::Exists, success: true, content: None, exists: Some(true), error: None, - })), + }.into()), ) // -- Prep: codegen output already exists .transport_mock( "execute_codegen_exists", "response", - Value::Response(TransportResponse::File(FileResponse { + Value::Response(FileResponse { path: "buck-out/gen/bin".into(), operation: FileOp::Exists, success: true, content: None, exists: Some(true), error: None, - })), + }.into()), ) // -- Codegen: skipped (already exists) .transport_mock("execute_codegen", "response", Value::Skipped) @@ -68,11 +68,7 @@ pub fn ci_mock_spec() -> MockSpec { .transport_mock( "execute_build", "response", - Value::Response(TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: "Compiling gunbc v0.1.0\n Finished dev target(s)".into(), - stderr: String::new(), - })), + Value::Response(ShellResponse::ok("Compiling gunbc v0.1.0\n Finished dev target(s)").into()), ) .transport_mock("execute_build", "skip", Value::Bool(false)) .transport_mock("execute_build", "skip_reason", Value::Str(String::new())) @@ -80,11 +76,7 @@ pub fn ci_mock_spec() -> MockSpec { .transport_mock( "execute_test", "response", - Value::Response(TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: "running 42 tests\ntest result: ok. 42 passed".into(), - stderr: String::new(), - })), + Value::Response(ShellResponse::ok("running 42 tests\ntest result: ok. 42 passed").into()), ) .transport_mock("execute_test", "skip", Value::Bool(false)) .transport_mock("execute_test", "skip_reason", Value::Str(String::new())) diff --git a/gunbc-dag/src/ci/ops.rs b/gunbc-dag/src/ci/ops.rs index d0a84a9cb6a..815ecf8c735 100644 --- a/gunbc-dag/src/ci/ops.rs +++ b/gunbc-dag/src/ci/ops.rs @@ -12,7 +12,7 @@ //! (pure) (boundary) (pure) //! ``` -use gunbc_exec::{ExecError, Executable, OutputMap, TransportResponseExt, optional_bool, optional_str, require_response}; +use gunbc_exec::{ExecError, Executable, OutputMap, TransportResponseExt, optional_bool, optional_str, propagate_skipped, require_response}; use gunbc_ir::transport::{FileRequest, TransportRequest, TransportResponse}; use gunbc_ir::Value; use crate::makegen::BuildConfig; @@ -101,14 +101,8 @@ impl Executable for CIOp { /// Parse the deps.toml exists check result (pure). fn execute_parse_deps_exists(inputs: HashMap) -> Result, ExecError> { - // Handle skipped response (upstream transport was skipped) - if matches!(inputs.get("response"), Some(Value::Skipped)) { - return OutputMap::new() - .value("deps_exists", Value::Skipped) - .value("deps_checked", Value::Skipped) - .value("deps_installed", Value::Skipped) - .value("message", Value::Skipped) - .ok(); + if let Some(result) = propagate_skipped(&inputs, "response", &["deps_exists", "deps_checked", "deps_installed", "message"]) { + return result; } let response = require_response(&inputs, "response")?; @@ -148,14 +142,8 @@ fn execute_prepare_codegen_exists_check(_inputs: HashMap) -> Resu /// Parse the codegen exists check result (pure). fn execute_parse_codegen_exists(inputs: HashMap) -> Result, ExecError> { - // Handle skipped response (upstream transport was skipped) - if matches!(inputs.get("response"), Some(Value::Skipped)) { - return OutputMap::new() - .value("codegen_needed", Value::Skipped) - .value("prep_success", Value::Skipped) - .value("codegen_ran", Value::Skipped) - .value("prep_message", Value::Skipped) - .ok(); + if let Some(result) = propagate_skipped(&inputs, "response", &["codegen_needed", "prep_success", "codegen_ran", "prep_message"]) { + return result; } let response = require_response(&inputs, "response")?; @@ -201,13 +189,8 @@ fn execute_prepare_codegen_command(inputs: HashMap) -> Result) -> Result, ExecError> { - // Handle skipped response (upstream transport was skipped) - if matches!(inputs.get("response"), Some(Value::Skipped)) { - return OutputMap::new() - .value("prep_success", Value::Skipped) - .value("codegen_ran", Value::Skipped) - .value("prep_message", Value::Skipped) - .ok(); + if let Some(result) = propagate_skipped(&inputs, "response", &["prep_success", "codegen_ran", "prep_message"]) { + return result; } // Check if codegen was skipped @@ -265,14 +248,8 @@ fn execute_prepare_build_command(inputs: HashMap) -> Result) -> Result, ExecError> { - // Handle skipped response (upstream transport was skipped) - if matches!(inputs.get("response"), Some(Value::Skipped)) { - return OutputMap::new() - .value("build_success", Value::Skipped) - .value("build_skipped", Value::Skipped) - .value("build_stdout", Value::Skipped) - .value("build_stderr", Value::Skipped) - .ok(); + if let Some(result) = propagate_skipped(&inputs, "response", &["build_success", "build_skipped", "build_stdout", "build_stderr"]) { + return result; } let skip = optional_bool(&inputs, "skip").unwrap_or(false); @@ -324,14 +301,8 @@ fn execute_prepare_test_command(inputs: HashMap) -> Result) -> Result, ExecError> { - // Handle skipped response (upstream transport was skipped) - if matches!(inputs.get("response"), Some(Value::Skipped)) { - return OutputMap::new() - .value("test_success", Value::Skipped) - .value("test_skipped", Value::Skipped) - .value("test_stdout", Value::Skipped) - .value("test_stderr", Value::Skipped) - .ok(); + if let Some(result) = propagate_skipped(&inputs, "response", &["test_success", "test_skipped", "test_stdout", "test_stderr"]) { + return result; } let skip = optional_bool(&inputs, "skip").unwrap_or(false); @@ -615,14 +586,14 @@ mod tests { fn test_parse_deps_exists_true() { let mut inputs = HashMap::new(); inputs.insert("response".to_string(), Value::Response( - TransportResponse::File(FileResponse { + FileResponse { path: "deps.toml".to_string(), operation: FileOp::Exists, success: true, content: None, exists: Some(true), error: None, - }) + }.into() )); let result = execute_parse_deps_exists(inputs).unwrap(); @@ -633,14 +604,14 @@ mod tests { fn test_parse_deps_exists_false() { let mut inputs = HashMap::new(); inputs.insert("response".to_string(), Value::Response( - TransportResponse::File(FileResponse { + FileResponse { path: "deps.toml".to_string(), operation: FileOp::Exists, success: true, content: None, exists: Some(false), error: None, - }) + }.into() )); let result = execute_parse_deps_exists(inputs).unwrap(); @@ -672,11 +643,7 @@ mod tests { let mut inputs = HashMap::new(); inputs.insert("skip".to_string(), Value::Bool(false)); inputs.insert("response".to_string(), Value::Response( - TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: "Build success".to_string(), - stderr: String::new(), - }) + ShellResponse::ok("Build success").into() )); let result = execute_parse_build_result(inputs).unwrap(); diff --git a/gunbc-dag/src/makegen/graph_mock.rs b/gunbc-dag/src/makegen/graph_mock.rs index 4da1a201a60..d386ed4072c 100644 --- a/gunbc-dag/src/makegen/graph_mock.rs +++ b/gunbc-dag/src/makegen/graph_mock.rs @@ -5,7 +5,7 @@ //! - What input constraints upstream must satisfy //! - Resource simulations for file system operations -use gunbc_ir::transport::{ShellResponse, TransportResponse}; +use gunbc_ir::transport::ShellResponse; use gunbc_ir::{CargoInvocation, Value}; use gunbc_test::{InputConstraint, MockSpec, NodeExample, OutputMatcher}; @@ -44,11 +44,7 @@ pub fn makegen_mock_spec() -> MockSpec { .transport_mock( "execute_transport", "response", - Value::Response(TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: String::new(), - stderr: String::new(), - })), + Value::Response(ShellResponse::ok("").into()), ) .transport_mock( "execute_transport", diff --git a/lib/git-ops/src/lib.rs b/lib/git-ops/src/lib.rs index 0a7c9c5c36a..760e271867d 100644 --- a/lib/git-ops/src/lib.rs +++ b/lib/git-ops/src/lib.rs @@ -215,19 +215,11 @@ mod tests { use gunbc_ir::transport::{ShellResponse, TransportRequest, TransportResponse}; fn shell_response(stdout: &str) -> TransportResponse { - TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: stdout.to_string(), - stderr: String::new(), - }) + ShellResponse::ok(stdout).into() } fn failed_shell_response() -> TransportResponse { - TransportResponse::Shell(ShellResponse { - exit_code: 1, - stdout: String::new(), - stderr: "error".to_string(), - }) + ShellResponse::failed(1, "error").into() } // ======================================================================== diff --git a/lib/llm-ops/src/lib.rs b/lib/llm-ops/src/lib.rs index 00339170e8c..808c4fb3e97 100644 --- a/lib/llm-ops/src/lib.rs +++ b/lib/llm-ops/src/lib.rs @@ -25,8 +25,8 @@ pub mod graph; pub mod graph_mock; use gunbc_exec::{ - optional_str, require_response, require_str, ExecError, Executable, OutputMap, - TransportResponseExt, + optional_str, propagate_skipped, require_response, require_str, ExecError, Executable, + OutputMap, TransportResponseExt, }; use gunbc_ir::transport::llm::{self, ChatMessage, ChatRequest, MessageContent, Role}; use gunbc_ir::transport::TransportRequest; @@ -166,15 +166,8 @@ fn execute_prepare_chat_request( fn execute_parse_chat_response( inputs: HashMap, ) -> Result, ExecError> { - // Handle skipped response (upstream transport was skipped) - if matches!(inputs.get("response"), Some(Value::Skipped)) { - return OutputMap::new() - .value("content", Value::Skipped) - .value("model", Value::Skipped) - .value("finish_reason", Value::Skipped) - .value("input_tokens", Value::Skipped) - .value("output_tokens", Value::Skipped) - .ok(); + if let Some(result) = propagate_skipped(&inputs, "response", &["content", "model", "finish_reason", "input_tokens", "output_tokens"]) { + return result; } let provider_id = require_str(&inputs, "provider")?; @@ -238,11 +231,8 @@ fn execute_prepare_simple_request( fn execute_parse_simple_response( inputs: HashMap, ) -> Result, ExecError> { - // Handle skipped response (upstream transport was skipped) - if matches!(inputs.get("response"), Some(Value::Skipped)) { - return OutputMap::new() - .value("answer", Value::Skipped) - .ok(); + if let Some(result) = propagate_skipped(&inputs, "response", &["answer"]) { + return result; } let provider_id = require_str(&inputs, "provider")?; diff --git a/lib/review/src/graph_mock.rs b/lib/review/src/graph_mock.rs index d70d5fe2b33..d71cb1011e9 100644 --- a/lib/review/src/graph_mock.rs +++ b/lib/review/src/graph_mock.rs @@ -4,7 +4,7 @@ use crate::{Criteria, Check, ReviewOutput, Finding, Location}; use gunbc_ir::transport::llm::mock; -use gunbc_ir::transport::{ShellResponse, TransportResponse}; +use gunbc_ir::transport::ShellResponse; use gunbc_ir::Value; use gunbc_test::{InputConstraint, MockSpec}; @@ -102,12 +102,12 @@ pub fn inline_review_mock_spec() -> MockSpec { .transport_mock( "execute_llm", "response", - Value::Response(TransportResponse::Rest(llm_response.clone())), + Value::Response(llm_response.clone().into()), ) .boundary( "execute_llm", "response", - Value::Response(TransportResponse::Rest(llm_response)), + Value::Response(llm_response.into()), ) // Boundary: parse_response outputs .boundary( @@ -188,31 +188,23 @@ diff --git a/src/main.rs b/src/main.rs .transport_mock( "execute_diff", "response", - Value::Response(TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: diff_output.to_string(), - stderr: String::new(), - })), + Value::Response(ShellResponse::ok(diff_output).into()), ) .boundary( "execute_diff", "response", - Value::Response(TransportResponse::Shell(ShellResponse { - exit_code: 0, - stdout: diff_output.to_string(), - stderr: String::new(), - })), + Value::Response(ShellResponse::ok(diff_output).into()), ) // Transport mock: LLM execute .transport_mock( "execute_llm", "response", - Value::Response(TransportResponse::Rest(llm_response.clone())), + Value::Response(llm_response.clone().into()), ) .boundary( "execute_llm", "response", - Value::Response(TransportResponse::Rest(llm_response)), + Value::Response(llm_response.into()), ) // Boundary: parse_response outputs .boundary( From 4028ca13c2ef9d22e342ced90a4b41e322fe661f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Feb 2026 19:13:50 +0000 Subject: [PATCH 3/3] Fix IntGe/IntLe codegen: emit boolean expressions, not string literals The IntGe/IntLe matchers used Expr::Str to build the closure body, which rendered as a string literal ("n >= 2") instead of a boolean expression (n >= 2). Generated tests using these matchers would fail to compile because the closure returned &str instead of bool. Fix: Add Expr::BinOp { left, op, right } and Expr::IntLit(i64) to the test IR. BinOp renders as `left op right` (e.g., `n >= 2`). IntLit renders as a bare integer (not Value::Int(n)), needed inside closures that operate on unwrapped i64 values. Before: x.as_int().is_some_and(|n| "n >= 2") // &str, won't compile After: x.as_int().is_some_and(|n| n >= 2) // bool, correct https://claude.ai/code/session_01EaBXwSmZrbVcpbFoV44Aju --- core/codegen/src/testgen/codegen.rs | 5 ++--- core/codegen/src/testgen/render_rust.rs | 21 +++++++++++++++++++++ core/codegen/src/testgen/test_ir.rs | 23 +++++++++++++++++++++++ 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/core/codegen/src/testgen/codegen.rs b/core/codegen/src/testgen/codegen.rs index b34fd112c7e..020780a2e5c 100644 --- a/core/codegen/src/testgen/codegen.rs +++ b/core/codegen/src/testgen/codegen.rs @@ -1965,14 +1965,13 @@ fn render_output_matcher_check(matcher: &OutputMatcher, var_name: &str) -> Strin RustRenderer.render_assert(&assert, 0) } OutputMatcher::IntGe(threshold) => { - // assert!(var.as_int().unwrap() >= threshold) let assert = Assert::True { expr: Expr::var(&output_var) .method("as_int", vec![]) .method("is_some_and", vec![ Expr::Closure { args: vec!["n".to_string()], - body: Box::new(Expr::Str(format!("n >= {}", threshold))), + body: Box::new(Expr::var("n").bin_op(">=", Expr::int(*threshold))), }, ]), message: format!("expected Int >= {} for {}", threshold, output_var), @@ -1986,7 +1985,7 @@ fn render_output_matcher_check(matcher: &OutputMatcher, var_name: &str) -> Strin .method("is_some_and", vec![ Expr::Closure { args: vec!["n".to_string()], - body: Box::new(Expr::Str(format!("n <= {}", threshold))), + body: Box::new(Expr::var("n").bin_op("<=", Expr::int(*threshold))), }, ]), message: format!("expected Int <= {} for {}", threshold, output_var), diff --git a/core/codegen/src/testgen/render_rust.rs b/core/codegen/src/testgen/render_rust.rs index ce717139d1a..bc203989d1f 100644 --- a/core/codegen/src/testgen/render_rust.rs +++ b/core/codegen/src/testgen/render_rust.rs @@ -128,6 +128,10 @@ impl TestRenderer for RustRenderer { format!("|{}| {}", args.join(", "), body_str) } } + Expr::BinOp { left, op, right } => { + format!("{} {} {}", self.render_expr(left), op, self.render_expr(right)) + } + Expr::IntLit(n) => n.to_string(), } } @@ -499,4 +503,21 @@ mod tests { " assert!(!output.is_empty(), \"expected non-empty value\");\n" ); } + + #[test] + fn render_bin_op_in_closure() { + let r = RustRenderer; + let expr = Expr::var("x") + .method("as_int", vec![]) + .method("is_some_and", vec![ + Expr::Closure { + args: vec!["n".to_string()], + body: Box::new(Expr::var("n").bin_op(">=", Expr::int(2))), + }, + ]); + assert_eq!( + r.render_expr(&expr), + "x.as_int().is_some_and(|n| n >= 2)" + ); + } } diff --git a/core/codegen/src/testgen/test_ir.rs b/core/codegen/src/testgen/test_ir.rs index ce912ffa66b..cf858af0613 100644 --- a/core/codegen/src/testgen/test_ir.rs +++ b/core/codegen/src/testgen/test_ir.rs @@ -122,6 +122,15 @@ pub enum Expr { args: Vec, body: Box, }, + /// Binary operation: `left op right` (e.g., `n >= 2`, `a == b`). + BinOp { + left: Box, + op: String, + right: Box, + }, + /// Bare integer literal (not `Value::Int`). For use in expressions + /// operating on unwrapped values (e.g., closure bodies after `as_int()`). + IntLit(i64), } // =========================================================================== @@ -205,6 +214,20 @@ impl Expr { pub fn ref_of(self) -> Self { Expr::Ref(Box::new(self)) } + + /// Shorthand for `self op right` (e.g., `n.ge(Expr::int(2))`). + pub fn bin_op(self, op: impl Into, right: Expr) -> Self { + Expr::BinOp { + left: Box::new(self), + op: op.into(), + right: Box::new(right), + } + } + + /// Shorthand for a bare integer literal (renders as `n`, not `Value::Int(n)`). + pub fn int(n: i64) -> Self { + Expr::IntLit(n) + } } impl Stmt {