Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
refactor/Delete-builder · L-261004-89a668 (#1331)
Louis Choquel60f54220c779
diff --git a/.drift/acks/cli-docs.toml b/.drift/acks/cli-docs.tomlindex 3d5ce609a..fecc34eaf 100644--- a/.drift/acks/cli-docs.toml+++ b/.drift/acks/cli-docs.toml@@ -1,25 +1,24 @@contract = "cli-docs"-digest = "sha256:0abffb6250cb4295f1533db1951fbf2cce547efd4ed746ae129c37fac680aa6d"+digest = "sha256:9ad68869227011d788deb2ece011967491b852cc3b49789247b21d4e1f242cca"reviewed_by = "Louis Choquel"-reviewed_at = "2026-10-04T11:52:31Z"-rationale = "real-catch: the inputs commands now print exactly success, pipe_ref and inputs, pipe_ref being the resolved qualified ref, with no message key on a pipe that declares no inputs; docs/tools/cli/agent-cli.md named the envelope success/pipe_code/inputs, so it now documents pipe_ref, its resolution and the no-inputs answer in JSON and TOML. pipelex/cli/agent_cli/CLAUDE.md describes the inputs command without its envelope keys and stays accurate."+reviewed_at = "2026-10-04T14:57:21Z"+rationale = "clean-pass: the only trigger change drops, from the emit_inputs_result docstring, its comparison with the deleted concept and pipe raw-TOML commands, with no surface change. Reviewed docs/tools/cli/ and pipelex/cli/agent_cli/CLAUDE.md: the review pass on this branch found what the previous ack missed, the Output Contract's raw-TOML bullet in docs/tools/cli/agent-cli.md and three passages of the agent-CLI guide still naming the deleted concept and pipe commands and the builder's validate ops, and this change removes them."[trigger_files]"pipelex/cli/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc"-"pipelex/cli/_cli.py" = "blob:22b4a3719e54a0c5593bbb98fb2737293df34d8c"+"pipelex/cli/_cli.py" = "blob:06366c8e670f003926eb5bfed75bf4f3db418835""pipelex/cli/agent_cli/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/agent_cli/_agent_cli.py" = "blob:e49ea3d36aa0e964e6d2cc66e901f8362c9ae76b"+"pipelex/cli/agent_cli/_agent_cli.py" = "blob:7dcd54b1fceb428b30757aa19d8e5d214f49f4a8""pipelex/cli/agent_cli/commands/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/agent_cli/commands/accept_gateway_terms_cmd.py" = "blob:cb8338c09a7b5dee6088551c156d69dab613213a""pipelex/cli/agent_cli/commands/agent_cli_factory.py" = "blob:49b8bab889d8673e7d4f1d683efe0928e43914b9"-"pipelex/cli/agent_cli/commands/agent_output.py" = "blob:30ecf4a3b1cb778864ed821a7b9918f62407a7f4"-"pipelex/cli/agent_cli/commands/bundle_path_resolver.py" = "blob:30339c5d91048f4e67312d5691ed9a65d57472e0"-"pipelex/cli/agent_cli/commands/check_model_cmd.py" = "blob:fbf29c499d8856f06736656ba17953457d04ca46"+"pipelex/cli/agent_cli/commands/agent_output.py" = "blob:7a56932e614a50c42cb029817c05e74aed3c6d9a"+"pipelex/cli/agent_cli/commands/bundle_path_resolver.py" = "blob:a1904517c731afb72af7d49adf6d217dc50b2660"+"pipelex/cli/agent_cli/commands/check_model_cmd.py" = "blob:c0ba11631c3904b9c4b4529d48d5954494cc1153""pipelex/cli/agent_cli/commands/codegen/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/agent_cli/commands/codegen/app.py" = "blob:56130b89fe9efec5ad3d014ed6bc16bef1bd1645""pipelex/cli/agent_cli/commands/codegen/check_cmd.py" = "blob:9e8beb084a9f04f39e8acca9e6ae2554d40cb667""pipelex/cli/agent_cli/commands/codegen/types_cmd.py" = "blob:dea775a8a469816f2c84ea4f6a5c9234c4af6705"-"pipelex/cli/agent_cli/commands/concept_cmd.py" = "blob:8e5c1881805cda39a1dae06be247a4fc257ccf69""pipelex/cli/agent_cli/commands/doctor_cmd.py" = "blob:9bfdb8c24a39a859665d2a9ff6b57883da0bd666""pipelex/cli/agent_cli/commands/fix/__init__.py" = "blob:65662c86f17f610ad55ecfc3e27a022b9aa26e8b""pipelex/cli/agent_cli/commands/fix/app.py" = "blob:e6190d9bde6a05755c04bd21806f699461038ac0"@@ -27,59 +26,53 @@ rationale = "real-catch: the inputs commands now print exactly success, pipe_ref"pipelex/cli/agent_cli/commands/fmt_cmd.py" = "blob:97d6fb6c328e0b718b1293bd6b73cba03edcb7dc""pipelex/cli/agent_cli/commands/init_cmd.py" = "blob:f10c15f5f1c220cb5f9509336258eaa2d2a11967""pipelex/cli/agent_cli/commands/inputs/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/agent_cli/commands/inputs/_inputs_core.py" = "blob:57233a09522464bb95f14eda83d7849800785418"+"pipelex/cli/agent_cli/commands/inputs/_inputs_core.py" = "blob:4161029643f3a302de54fa637d2676521e10d873""pipelex/cli/agent_cli/commands/inputs/app.py" = "blob:7e19284687b334c684fb03381a8d9d20af1aa152"-"pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py" = "blob:a3cab23f83f375f7571f86c16b54904cd2045449"+"pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py" = "blob:e42c08315b879df91ba4a22074ba697311830ae2""pipelex/cli/agent_cli/commands/inputs/method_cmd.py" = "blob:56fc7edc47ec9513d4e289010c42405df351544e""pipelex/cli/agent_cli/commands/inputs/pipe_cmd.py" = "blob:bdddcc8f1bf6e5437ab4375b1c601ee66bee994f""pipelex/cli/agent_cli/commands/lint_cmd.py" = "blob:91ad9cb4d618ba4c0b7da366cde2f74f38d350df""pipelex/cli/agent_cli/commands/migrate_cmd.py" = "blob:ce733b78df03e65c3c8a10d46b27b57c05ec054c"-"pipelex/cli/agent_cli/commands/models_cmd.py" = "blob:5678c00ab389b0a433c080be3454c7905e569308"-"pipelex/cli/agent_cli/commands/pipe_cmd.py" = "blob:b040d1f71b1f3e0a1e2d6c03e8fc9929431e01de"+"pipelex/cli/agent_cli/commands/models_cmd.py" = "blob:e1e17e86d1f1b1f1fae167fcaa87a0618ba25681""pipelex/cli/agent_cli/commands/plxt_passthrough.py" = "blob:a1c530d110482485ce462f199b9e79fac29f8896""pipelex/cli/agent_cli/commands/run/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/agent_cli/commands/run/_output_helpers.py" = "blob:40ed1700e0d5e86d7696eadd7f9887baeb8059f6""pipelex/cli/agent_cli/commands/run/_run_core.py" = "blob:32f973c5c754b23016f3e708ab3235856e8bc5f4""pipelex/cli/agent_cli/commands/run/_run_core_api.py" = "blob:ac949cc4c93ca8e0f18b93a68f59584a7cf1a75e""pipelex/cli/agent_cli/commands/run/app.py" = "blob:64b2ecc02007cda11b526d8d3fc139593875dd9d"-"pipelex/cli/agent_cli/commands/run/bundle_cmd.py" = "blob:950fbfb28a1ecd73283f52853da944358662d088"+"pipelex/cli/agent_cli/commands/run/bundle_cmd.py" = "blob:b1c01b3ad4aeffe806c5c44a886a64f5324c8afc""pipelex/cli/agent_cli/commands/run/method_cmd.py" = "blob:75a67ad84ea53e793d2aec415b045e84abd7464c""pipelex/cli/agent_cli/commands/run/pipe_cmd.py" = "blob:0985c360de8fddc3f282b41a530792e3cf1fd254""pipelex/cli/agent_cli/commands/run/stdin_resolver.py" = "blob:c7c7d7495508f1c4e5a46eba336a4ab1694ebcf7""pipelex/cli/agent_cli/commands/validate/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/agent_cli/commands/validate/_validate_core.py" = "blob:96d0f9f178739dd5a2e659cb392760b8a2bbcb32"+"pipelex/cli/agent_cli/commands/validate/_validate_core.py" = "blob:2a04aeff94db4afc56ac0c033a9d4add54d85c88""pipelex/cli/agent_cli/commands/validate/app.py" = "blob:d2d0ed19288c2d1c25be1650dd962189fcdb3b86""pipelex/cli/agent_cli/commands/validate/bundle_cmd.py" = "blob:b3f17f88fc74d02abf8a167af69f4275a8e8c6c8""pipelex/cli/agent_cli/commands/validate/method_cmd.py" = "blob:cf841e73d6af1a7e90d5ddfadaad012928f1a3ba""pipelex/cli/agent_cli/commands/validate/pipe_cmd.py" = "blob:b5aae81bc47ed8de23a13755b2c8c2418b4b8b9a"-"pipelex/cli/bundle_target_resolution.py" = "blob:8dccc50b700b877968ed1b2c1c3652ab1c32e956"+"pipelex/cli/bundle_target_resolution.py" = "blob:460aa997ea0886c6faee0f3a42bd55231c480240""pipelex/cli/cli_factory.py" = "blob:1f859ab3b995e1a67e5fdc812a168d56c338e970""pipelex/cli/commands/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/build/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/build/app.py" = "blob:0a96edab273c838aa9e0fae23646805c3a775e9d"+"pipelex/cli/commands/build/app.py" = "blob:d3205e1dc0268a9d32a517e4f9a9a3b4647e8889""pipelex/cli/commands/build/inputs/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/build/inputs/_inputs_core.py" = "blob:50317e058df75070722d2e29edab4537e6b7b438"+"pipelex/cli/commands/build/inputs/_inputs_core.py" = "blob:6f3f7a5417f72eabef33c39d95157a89c8c22e88""pipelex/cli/commands/build/inputs/app.py" = "blob:2a7770c8294b8c2c1b4420ac00d6ffdfa50609bf"-"pipelex/cli/commands/build/inputs/bundle_cmd.py" = "blob:0cd99e9d307f46b8e8899bf7d5f3813563fcdf10"-"pipelex/cli/commands/build/inputs/method_cmd.py" = "blob:34d3a67c33c6856be965a3a15142f9c53baf0585"+"pipelex/cli/commands/build/inputs/bundle_cmd.py" = "blob:699980753d79480387ef1edc7f94b00325827e63"+"pipelex/cli/commands/build/inputs/method_cmd.py" = "blob:2fcaea4f05df4947d6ec1a49b2fa23b52c23ca3c""pipelex/cli/commands/build/inputs/pipe_cmd.py" = "blob:00625740fd29837e3165d31be692e40e96065fc8""pipelex/cli/commands/build/output/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/build/output/_output_core.py" = "blob:9ba47b88a3c0b6cbf3f8de5f9a4939373f64ceb8""pipelex/cli/commands/build/output/app.py" = "blob:67996650b99551fbd58be30e692688204d16935a"-"pipelex/cli/commands/build/output/bundle_cmd.py" = "blob:54c07aedb123eaaf2049965859e82b6d4800560d"+"pipelex/cli/commands/build/output/bundle_cmd.py" = "blob:7cafc55438704ecc6e86d1182069e4b1f73f9794""pipelex/cli/commands/build/output/method_cmd.py" = "blob:242434d518aff0b9706b910e7f937b53a601fde1""pipelex/cli/commands/build/output/pipe_cmd.py" = "blob:eb0db8279c93fcff9d5fe4546f593d753282acb5"-"pipelex/cli/commands/build/runner/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/build/runner/_runner_core.py" = "blob:e4745231cb46547de93d83d1ac7a6db28ae81494"-"pipelex/cli/commands/build/runner/app.py" = "blob:b5aa321ed93dc2cb9b138e4a26bae9eb75c732b7"-"pipelex/cli/commands/build/runner/bundle_cmd.py" = "blob:5b5ca0628f0595a0c3aae9b539ae4e7e0c92a853"-"pipelex/cli/commands/build/runner/method_cmd.py" = "blob:cea9a0365bc828c9f83cdcb88f4faee13d8fc6de""pipelex/cli/commands/build/structures_cmd.py" = "blob:d13ba3b6fc1433f787e1aa97c6c04a67483ec7ed"-"pipelex/cli/commands/bundle_path_resolver.py" = "blob:60c6a2994c9b7c6e0ec212702467d668eecb6d50"+"pipelex/cli/commands/bundle_path_resolver.py" = "blob:c98794b23efde0f279ac3c113fd5f5175f2db479""pipelex/cli/commands/codegen/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391""pipelex/cli/commands/codegen/app.py" = "blob:9158084a89da23654e122e9df3a0a9c726401642""pipelex/cli/commands/codegen/check_cmd.py" = "blob:329f410bca90eb022fad2abc729e8b5203138c02"-"pipelex/cli/commands/codegen/inputs_cmd.py" = "blob:20738a9e42f0e5ef7ffc489093348af3cb4643a0"+"pipelex/cli/commands/codegen/inputs_cmd.py" = "blob:9957ee119b5d839aaa56f98444a1be3789c68f7c""pipelex/cli/commands/codegen/types_cmd.py" = "blob:b7c9c7a3664c9fbe66f9b4c3c5ebf9ea1322445c""pipelex/cli/commands/crate_loading.py" = "blob:3d7d651931ecf1a15a3e2d72411b3212b55d74ef""pipelex/cli/commands/doctor_cmd.py" = "blob:230c30f13e7bf19b70a6e2a03398725dcc2c422e"@@ -109,12 +102,12 @@ rationale = "real-catch: the inputs commands now print exactly success, pipe_ref"pipelex/cli/commands/plugins_cmd.py" = "blob:9657b713c3650ff4a929e92ae68af453d896393e""pipelex/cli/commands/resolve_cmd.py" = "blob:2928a0e26eab7983367a59a78533f6618817feba""pipelex/cli/commands/run/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"-"pipelex/cli/commands/run/_inputs_file_loader.py" = "blob:dde781f846968b667a0acfb4b3e3cea01cef7049"+"pipelex/cli/commands/run/_inputs_file_loader.py" = "blob:957e6eb00531d168b3b1e179a517717d069cb7fc""pipelex/cli/commands/run/_inputs_path_resolver.py" = "blob:c8ec89d98718e18af7aaaded44c9f545be60adab""pipelex/cli/commands/run/_main_stuff_file.py" = "blob:ca806e55085aa2e5748492751521296ce1f42960""pipelex/cli/commands/run/_run_core.py" = "blob:12958ebb9bc89fec6f0e6faf0b79d031091f02b3""pipelex/cli/commands/run/app.py" = "blob:a7090b0ff6bf2f1d47827fa27d2a138096a2e148"-"pipelex/cli/commands/run/bundle_cmd.py" = "blob:cb420bf4879c863d64c5e20ed535c42732b720a2"+"pipelex/cli/commands/run/bundle_cmd.py" = "blob:13d68d533986c3938b1b2ee808819d8daf6f91db""pipelex/cli/commands/run/exceptions.py" = "blob:e9552226e597922b6ac0757f7b52eb880a2e1472""pipelex/cli/commands/run/method_cmd.py" = "blob:9f5c7b6ad8f7fc7d086a9e6253049c6e2ec3e7d8""pipelex/cli/commands/run/pipe_cmd.py" = "blob:f92fcb94e3ad55cf5aeec366a59fa7a74bcc9667"@@ -128,7 +121,7 @@ rationale = "real-catch: the inputs commands now print exactly success, pipe_ref"pipelex/cli/commands/validate/pipe_cmd.py" = "blob:d67267571559006459628180f2c8b216ba7fee31""pipelex/cli/commands/which_cmd.py" = "blob:68661d4bab22e2c4dab183d59bd9f2c6dd573472""pipelex/cli/deck_notice.py" = "blob:542877125e89e35b02bc969cfee952155b0d7c2c"-"pipelex/cli/error_handlers.py" = "blob:4b97a9c89d9b2532f0a9d1406baad130fc4d56f7"+"pipelex/cli/error_handlers.py" = "blob:978a836fc2327e071533150a4b8e210793615bc3""pipelex/cli/exceptions.py" = "blob:1d51c3a53ddd3f6cf8de566fa2ade3fa75ab7a3a""pipelex/cli/installed_methods.py" = "blob:09197f47baf8d7251d28d148a0544b4a23ee7365""pipelex/cli/method_resolver.py" = "blob:afaf77b2d8b6a3467d6ab1f355b1ee78a71eafa7"diff --git a/.drift/acks/hub-layering-convention.toml b/.drift/acks/hub-layering-convention.tomlindex e059e8372..641cc9590 100644--- a/.drift/acks/hub-layering-convention.toml+++ b/.drift/acks/hub-layering-convention.toml@@ -1,10 +1,10 @@contract = "hub-layering-convention"-digest = "sha256:644cc1387406a8e2c330a76f4139ec25318bd56a7d78caa46f9bb54f2bf7b682"+digest = "sha256:717ab382b52b2fa43c750bd30036428fb9d363cd0a5f8e86faffb4ebc0d86f3f"reviewed_by = "Louis Choquel"-reviewed_at = "2026-10-04T00:24:05Z"-rationale = "clean-pass: runtime_hub.py changed only in a docstring, which adds PipeJudge to the list of inference operators resolving the content generator; no layer placement or hub member moved, so docs/contribute/hub-layering.md is unaffected."+reviewed_at = "2026-10-04T14:31:48Z"+rationale = "real-catch: runtime_hub.py's docstring dropped builder from the interpreter packages it may not name, since pipelex.builder no longer exists. docs/contribute/hub-layering.md named it in the same list and in its verification snippet's INTERPRETER set, which the closure test compares against INTERPRETER_PACKAGES, and listed builder/runner_code among the interpreter callers that supply get_concept_library(); all three now leave it out."[trigger_files]"pipelex/cli/dev_cli/commands/hub_layering_guard.py" = "blob:2dbadcbab7d44364a7b5f1d16268b23b26700a00""pipelex/interpreter_hub.py" = "blob:327e75d0fbb5bdf46f6cbf06024f83840f0106d0"-"pipelex/runtime_hub.py" = "blob:b6dcef79b73d5ce05669c478bff9dc4b367696e5"+"pipelex/runtime_hub.py" = "blob:485fefa16424ad368e80a5008beab7bd5bf86305"diff --git a/.drift/acks/keyword-only-convention.toml b/.drift/acks/keyword-only-convention.tomlindex ed54b4941..c19a3fdb6 100644--- a/.drift/acks/keyword-only-convention.toml+++ b/.drift/acks/keyword-only-convention.toml@@ -1,8 +1,8 @@contract = "keyword-only-convention"-digest = "sha256:85a8ab8c560f91b16ecf54ff13835d3cc4a36e0d6a0ef17783fe5417ebbb2134"+digest = "sha256:adc659a6dcca514c5e253b85b5d24206b767b5d0416618b0ee11e1e7de38b864"reviewed_by = "Louis Choquel"-reviewed_at = "2026-07-28T16:26:27Z"-rationale = "FU-3 adds an unsorted-grant violation kind: subject_grants.toml's sorted-by-key order is now enforced rather than only asserted in the doc's prose (line 37), which is the invariant the modularity track broke three times unnoticed. Reviewed docs/contribute/keyword-only-arguments.md in full and updated five places — the violation-kinds table under Enforcement, the registry-order paragraph under 'Staleness is symmetric' (order is read from the raw text, since TOML declares table order insignificant, and the text scan is cross-checked against the parsed keys so an unreadable entry shape fails loudly instead of narrowing the scan), the PostToolUse hook bullet (registry order is a whole-file property the per-file path cannot see, same as dead grants), the auto-fix paragraph (which listed only grant-param-mismatch as never-rewritten and silently omitted dead-grant — pre-existing gap, closed here), and a pointer line after the top-of-page rule list, because that list is scoped to signatures and registry order is not a signature property. No new Make target: the check rides check-keyword-only into agent-check and CI. Negative-tested both failure modes against the real registry (a swapped adjacent entry, and a multi-line rationale carrying a phantom table header)."+reviewed_at = "2026-10-04T14:15:36Z"+rationale = "clean-pass: the guard's only change is a docstring example of a qualified module path (pipelex.builder.foo becomes pipelex.cogt.foo, since pipelex.builder no longer exists); its behaviour is unchanged. Reviewed docs/contribute/keyword-only-arguments.md: its worked grant example named pipelex/builder/build.py::build_pipe, so it now names a neutral publish_bundle; nothing else names the builder."[trigger_files]-"pipelex/cli/dev_cli/commands/keyword_only_guard.py" = "blob:e0be8c72d545db425efab586f7be5cc7e98f1e13"+"pipelex/cli/dev_cli/commands/keyword_only_guard.py" = "blob:dfa8b2eeec1bb0e7c41fe431c7a6e4514c67628a"diff --git a/.test_durations b/.test_durationsindex f965b1baa..8a89520a9 100644--- a/.test_durations+++ b/.test_durations@@ -186,23 +186,6 @@"tests/helpers/test_ts_toolchain.py::TestTsToolchainResolversReturnAbsolutePaths::test_resolve_node_absolutizes_a_relative_path_entry": 0.2726,"tests/helpers/test_ts_toolchain.py::TestTsToolchainResolversReturnAbsolutePaths::test_resolve_prettier_absolutizes_a_relative_path_entry": 3.3773,"tests/helpers/test_ts_toolchain.py::TestTsToolchainResolversReturnAbsolutePaths::test_resolve_zod_package_absolutizes_a_relative_env_value": 0.0542,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_agent_validate_all_locates_a_wiring_refusal_on_its_file": 0.0424,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_an_inherited_system_prompt_refusal_names_the_domain": 0.0509,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_an_inherited_system_prompt_refusal_quotes_no_token_of_it": 0.0436,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_factory_refusal_is_the_authors_caller_facing_input[PipeComposeFactoryError]": 0.0082,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_factory_refusal_is_the_authors_caller_facing_input[PipeConditionFactoryError]": 0.0015,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_factory_refusal_is_the_authors_caller_facing_input[PipeExtractFactoryError]": 0.0009,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_factory_refusal_is_the_authors_caller_facing_input[PipeLLMFactoryError]": 0.2284,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_factory_refusal_is_the_authors_caller_facing_input[PipeParallelFactoryError]": 0.0011,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_validate_bundle_locates_the_extract_refusal_with_its_next_step": 0.0577,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_validate_ops_validate_all_answers_a_load_refusal_with_the_verdict": 0.0695,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_validate_ops_validate_all_lets_a_teardown_fault_propagate": 0.0764,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_validate_ops_validate_all_locates_a_wiring_refusal_on_its_file": 0.0442,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_validate_ops_validate_pipe_answers_a_load_refusal_with_the_verdict": 0.0556,- "tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_validate_ops_validate_pipe_keeps_an_ambiguous_code_out_of_the_verdict": 0.0453,- "tests/integration/pipelex/builder/operations/test_runner_code_ops_library_lifecycle.py::TestRunnerCodeOpsLibraryLifecycle::test_failure_restores_outer_and_tears_down_temp": 1.9462,- "tests/integration/pipelex/builder/operations/test_validate_pipe_library_lifecycle.py::TestValidatePipeLibraryLifecycle::test_failure_restores_outer_and_tears_down_temp": 1.035,- "tests/integration/pipelex/builder/operations/test_validate_pipe_library_lifecycle.py::TestValidatePipeLibraryLifecycle::test_success_restores_outer_and_tears_down_temp": 1.2246,"tests/integration/pipelex/cli/agent_cli/test_run_cost_report.py::TestAgentRunCostReport::test_cost_report_for_free_model_run": 0.0026,"tests/integration/pipelex/cli/agent_cli/test_run_cost_report.py::TestAgentRunCostReport::test_cost_report_in_with_memory_json": 1.0553,"tests/integration/pipelex/cli/agent_cli/test_run_cost_report.py::TestAgentRunCostReport::test_no_cost_report_for_dry_run": 0.1196,@@ -218,7 +201,6 @@"tests/integration/pipelex/cli/commands/init/test_cache_priming.py::TestCachePriming::test_priming_reads_backends_toml_from_target_dir": 0.1575,"tests/integration/pipelex/cli/commands/init/test_cache_priming.py::TestCachePriming::test_priming_runs_for_a_manifold_only_installation": 0.5568,"tests/integration/pipelex/cli/commands/init/test_cache_priming.py::TestCachePriming::test_priming_skips_when_target_dir_says_gateway_disabled": 1.1641,- "tests/integration/pipelex/cli/commands/test_build_runner_flow.py::TestBuildRunnerFlow::test_runner_and_structures_projection_agree_on_names": 2.3521,"tests/integration/pipelex/cli/test_advisory_warning_channels.py::TestAdvisoryWarningChannels::test_agent_cli_bundle_envelope_carries_all_three_families": 0.6051,"tests/integration/pipelex/cli/test_advisory_warning_channels.py::TestAdvisoryWarningChannels::test_agent_cli_markdown_lists_all_three_families_in_the_same_order": 1.949,"tests/integration/pipelex/cli/test_advisory_warning_channels.py::TestAdvisoryWarningChannels::test_agent_cli_markdown_renders_the_warning_under_its_heading": 1.5342,@@ -693,6 +675,15 @@"tests/integration/pipelex/pipeline/test_execution_seams.py::TestExecutionSeams::test_an_unsafe_scope_is_refused_before_anything_is_written[traversal-leading]": 1.3545,"tests/integration/pipelex/pipeline/test_execution_seams.py::TestExecutionSeams::test_prepare_pipe_job_builds_equivalent_job_against_open_library": 0.0592,"tests/integration/pipelex/pipeline/test_execution_seams.py::TestExecutionSeams::test_prepare_pipe_job_skips_normalize_for_empty_inputs": 0.219,+ "tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_agent_validate_all_locates_a_wiring_refusal_on_its_file": 0.0424,+ "tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_an_inherited_system_prompt_refusal_names_the_domain": 0.0509,+ "tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_an_inherited_system_prompt_refusal_quotes_no_token_of_it": 0.0436,+ "tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_factory_refusal_is_the_authors_caller_facing_input[PipeComposeFactoryError]": 0.0082,+ "tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_factory_refusal_is_the_authors_caller_facing_input[PipeConditionFactoryError]": 0.0015,+ "tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_factory_refusal_is_the_authors_caller_facing_input[PipeExtractFactoryError]": 0.0009,+ "tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_factory_refusal_is_the_authors_caller_facing_input[PipeLLMFactoryError]": 0.2284,+ "tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_factory_refusal_is_the_authors_caller_facing_input[PipeParallelFactoryError]": 0.0011,+ "tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py::TestFactoryRefusalVerdicts::test_validate_bundle_locates_the_extract_refusal_with_its_next_step": 0.0577,"tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_already_valid_bundle_is_a_no_op": 1.7559,"tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_cascade_needs_two_iterations": 1.9638,"tests/integration/pipelex/pipeline/test_fix_convergence_loop.py::TestFixConvergenceLoop::test_concurrent_edit_during_render_is_not_overwritten": 0.1282,@@ -1621,355 +1612,6 @@"tests/integration/pipelex/tools/uri/test_uri_resolver_integration.py::TestUriResolverIntegration::test_make_base64_url_from_uri_async_with_http_url[https://d2cinlfp2qnig1.cloudfront.net/tests/eiffel_tower.jpg]": 0.0475,"tests/integration/pipelex/tools/uri/test_uri_resolver_integration.py::TestUriResolverIntegration::test_make_base64_url_from_uri_async_with_http_url[https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/diagrams/gantt_tree_house.png]": 0.6017,"tests/integration/pipelex/tools/uri/test_uri_resolver_integration.py::TestUriResolverIntegration::test_resolve_and_convert_local_file": 0.0058,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptBlueprintConversion::test_concept_to_core_blueprint[concept_with_concept_ref-concept_spec5-expected_core5]": 0.0551,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptBlueprintConversion::test_concept_to_core_blueprint[concept_with_integer_field-concept_spec3-expected_core3]": 0.0398,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptBlueprintConversion::test_concept_to_core_blueprint[concept_with_multiple_fields-concept_spec4-expected_core4]": 0.0339,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptBlueprintConversion::test_concept_to_core_blueprint[concept_with_refines-concept_spec1-expected_core1]": 0.0659,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptBlueprintConversion::test_concept_to_core_blueprint[concept_with_text_field-concept_spec2-expected_core2]": 0.0695,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptBlueprintConversion::test_concept_to_core_blueprint[simple_concept-concept_spec0-expected_core0]": 1.248,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptCodeValidation::test_concept_code_conversion[mixed_case_with_domain-my_domain.some_complex_concept_name-my_domain.SomeComplexConceptName]": 0.0956,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptCodeValidation::test_concept_code_conversion[multi_segment_domain-legal.contracts.Invoice-legal.contracts.Invoice]": 0.0475,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptCodeValidation::test_concept_code_conversion[multi_segment_domain_snake-legal.contracts.non_compete_clause-legal.contracts.NonCompeteClause]": 0.1926,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptCodeValidation::test_concept_code_conversion[multiple_underscores-my_super_long_concept_name-MySuperLongConceptName]": 0.106,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptCodeValidation::test_concept_code_conversion[pascal_case_no_domain-ConceptName-ConceptName]": 0.0483,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptCodeValidation::test_concept_code_conversion[pascal_case_with_domain-my_domain.ConceptName-my_domain.ConceptName]": 0.0495,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptCodeValidation::test_concept_code_conversion[single_word_snake-concept-Concept]": 0.1013,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptCodeValidation::test_concept_code_conversion[snake_case_no_domain-concept_name-ConceptName]": 0.109,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptCodeValidation::test_concept_code_conversion[snake_case_with_domain-my_domain.concept_name-my_domain.ConceptName]": 0.0844,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptCodeValidation::test_concept_code_conversion[with_numbers_domain_snake-domain_v1.concept_name_v2-domain_v1.ConceptNameV2]": 0.0898,- "tests/unit/pipelex/builder/concept/test_concept_blueprint.py::TestConceptCodeValidation::test_concept_code_conversion[with_numbers_snake-concept_v2_name-ConceptV2Name]": 0.078,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.py::TestConceptStructureSpecChoices::test_choices_without_type_converts_to_blueprint": 0.0599,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.py::TestConceptStructureSpecChoices::test_incompatible_type_with_choices[choices_boolean_type-spec_data0]": 0.0516,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.py::TestConceptStructureSpecChoices::test_incompatible_type_with_choices[choices_concept_type-spec_data2]": 0.0484,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.py::TestConceptStructureSpecChoices::test_incompatible_type_with_choices[choices_date_type-spec_data1]": 0.06,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.py::TestConceptStructureSpecChoices::test_incompatible_type_with_choices[choices_list_type-spec_data3]": 0.1486,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.py::TestConceptStructureSpecChoices::test_no_type_no_choices_fails_validation": 0.0007,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.py::TestConceptStructureSpecChoices::test_valid_choices[choices_integer_type-spec_data2-integer-expected_choices2]": 0.0382,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.py::TestConceptStructureSpecChoices::test_valid_choices[choices_no_type-spec_data0-text-expected_choices0]": 0.8634,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.py::TestConceptStructureSpecChoices::test_valid_choices[choices_number_type-spec_data3-number-expected_choices3]": 0.0387,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.py::TestConceptStructureSpecChoices::test_valid_choices[choices_text_type-spec_data1-text-expected_choices1]": 0.0496,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_validation.py::TestConceptStructureSpecValidation::test_concept_ref_only_allowed_for_concept_type": 0.0007,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_validation.py::TestConceptStructureSpecValidation::test_concept_type_cannot_have_default_value": 0.0008,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_validation.py::TestConceptStructureSpecValidation::test_concept_type_requires_concept_ref": 1.2218,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_validation.py::TestConceptStructureSpecValidation::test_concept_type_with_concept_ref_valid": 0.0004,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_validation.py::TestConceptStructureSpecValidation::test_date_spec_accepts_date_rejects_datetime": 0.0013,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_validation.py::TestConceptStructureSpecValidation::test_datetime_spec_type_and_to_blueprint": 0.0007,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_validation.py::TestConceptStructureSpecValidation::test_required_with_default_is_rejected_at_spec_level": 0.2023,- "tests/unit/pipelex/builder/concept/test_concept_structure_spec_validation.py::TestConceptStructureSpecValidation::test_to_blueprint_concept_type": 0.1401,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_builder_toml_roundtrips_through_blueprint_with_default": 0.196,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_choices_none_by_default": 0.0007,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_choices_passed_to_blueprint": 0.0003,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_concept_field_with_concept_ref": 0.0003,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_description_only_field_uses_string_format": 0.0013,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_field_with_choices": 0.0007,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_field_with_choices_and_default": 0.0006,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_field_with_choices_and_required": 0.0007,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_field_with_default_value": 0.0008,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_integer_field": 0.0007,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_no_refines_omits_refines": 0.0764,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_no_structure_omits_structure_section": 0.002,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_roundtrip_json_to_toml_preserves_choices": 0.0015,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_simple_refines_concept": 0.0013,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_structured_concept_with_multiple_fields": 0.0017,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_text_field_description_only": 0.7786,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_text_field_with_required": 0.001,- "tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py::TestConceptSpecToToml::test_toml_includes_choices": 0.0006,- "tests/unit/pipelex/builder/operations/test_inputs_ops.py::TestBuildInputsForPipe::test_bundle_path_explicit_pipe_code_wins": 0.003,- "tests/unit/pipelex/builder/operations/test_inputs_ops.py::TestBuildInputsForPipe::test_bundle_path_validates_file_and_qualifies_main_pipe": 0.0055,- "tests/unit/pipelex/builder/operations/test_inputs_ops.py::TestBuildInputsForPipe::test_bundle_path_without_main_pipe_raises_with_path": 0.0047,- "tests/unit/pipelex/builder/operations/test_inputs_ops.py::TestBuildInputsForPipe::test_happy_path_return_shape": 0.1,- "tests/unit/pipelex/builder/operations/test_inputs_ops.py::TestBuildInputsForPipe::test_mthds_contents_explicit_pipe_code_skips_scan": 0.004,- "tests/unit/pipelex/builder/operations/test_inputs_ops.py::TestBuildInputsForPipe::test_mthds_contents_first_main_pipe_wins_domain_qualified": 0.7118,- "tests/unit/pipelex/builder/operations/test_inputs_ops.py::TestBuildInputsForPipe::test_mthds_contents_validates_with_allow_signatures": 0.0041,- "tests/unit/pipelex/builder/operations/test_inputs_ops.py::TestBuildInputsForPipe::test_mthds_contents_without_any_main_pipe_raises": 0.0023,- "tests/unit/pipelex/builder/operations/test_inputs_ops.py::TestBuildInputsForPipe::test_no_bundle_and_no_pipe_code_raises": 0.0041,- "tests/unit/pipelex/builder/operations/test_inputs_ops.py::TestBuildInputsForPipe::test_no_bundle_empty_resolved_dirs_skips_loading": 0.0028,- "tests/unit/pipelex/builder/operations/test_inputs_ops.py::TestBuildInputsForPipe::test_no_bundle_loads_libraries_from_resolved_dirs": 0.004,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_canonical_concept_code": 0.7359,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_canonical_ignores_alias": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_concept_code_alias_accepted[code]": 0.001,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_concept_code_alias_accepted[concept_name]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_concept_code_alias_accepted[concept_ref]": 0.001,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_concept_code_alias_accepted[name]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_concept_code_alias_accepted[the_concept_code]": 0.0037,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_concept_with_choices_in_structure": 0.0922,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_dict_field_without_type_defaults_to_text": 0.0009,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_malformed_structure_classifies_as_input_domain": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_missing_concept_code_raises": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_mixed_string_and_dict_fields": 0.001,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_multiple_aliases_all_cleaned_up": 0.001,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_dict_mapping_top_level_is_accepted": 0.0007,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_dict_structure_raises_concept_spec_error[0]": 0.0009,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_dict_structure_raises_concept_spec_error[False]": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_dict_structure_raises_concept_spec_error[]": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_dict_structure_raises_concept_spec_error[bad_structure1]": 0.0011,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_dict_structure_raises_concept_spec_error[not_a_dict]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_mapping_top_level_classifies_as_input_domain": 0.0006,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_mapping_top_level_raises_concept_spec_error[123]": 0.0006,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_mapping_top_level_raises_concept_spec_error[3.14]": 0.001,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_mapping_top_level_raises_concept_spec_error[None]": 0.0024,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_mapping_top_level_raises_concept_spec_error[a string]": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_mapping_top_level_raises_concept_spec_error[bad_spec1]": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_str_non_dict_field_raises_concept_spec_error[3.14]": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_str_non_dict_field_raises_concept_spec_error[42]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_str_non_dict_field_raises_concept_spec_error[True]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_non_str_non_dict_field_raises_concept_spec_error[bad_field_value1]": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_none_structure_is_treated_as_absent": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_original_dict_unchanged": 0.0007,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_simple_concept_with_refines": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_string_field_becomes_text": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_concept_spec.py::TestParseConceptSpec::test_structured_concept": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_canonical_pipe_code": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_canonical_pipe_code_takes_precedence_over_alias": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_canonical_prompt_takes_precedence_over_alias": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_condition_canonical_jinja2_field": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_condition_canonical_takes_precedence": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_condition_expression_alias": 0.0007,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_correct_subclass[PipeBatch-spec_data5-PipeBatchSpec]": 0.0766,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_correct_subclass[PipeExtract-spec_data3-PipeExtractSpec]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_correct_subclass[PipeFunc-spec_data1-PipeFuncSpec]": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_correct_subclass[PipeImgGen-spec_data2-PipeImgGenSpec]": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_correct_subclass[PipeLLM-spec_data0-PipeLLMSpec]": 0.0007,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_correct_subclass[PipeSearch-spec_data4-PipeSearchSpec]": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_error_lists_valid_types": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_explicit_signature_tag_rejected_with_migration_error": 0.0007,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_first_alias_wins_when_no_canonical": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_first_output_alias_wins": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_malformed_steps_classifies_as_input_domain": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_nested_step_dicts_not_mutated": 0.0021,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_list_branches_raises_pipe_spec_error[42]": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_list_branches_raises_pipe_spec_error[bad_branches2]": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_list_branches_raises_pipe_spec_error[notalist]": 0.0006,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_list_steps_raises_pipe_spec_error[42]": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_list_steps_raises_pipe_spec_error[bad_steps2]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_list_steps_raises_pipe_spec_error[notalist]": 0.0006,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_mapping_branch_entry_raises_pipe_spec_error[42]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_mapping_branch_entry_raises_pipe_spec_error[astring]": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_mapping_branch_entry_raises_pipe_spec_error[bad_entry2]": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_mapping_step_entry_raises_pipe_spec_error[42]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_mapping_step_entry_raises_pipe_spec_error[astring]": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_mapping_step_entry_raises_pipe_spec_error[bad_entry2]": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_mapping_top_level_classifies_as_input_domain": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_mapping_top_level_raises_pipe_spec_error[123]": 0.0011,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_mapping_top_level_raises_pipe_spec_error[3.14]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_mapping_top_level_raises_pipe_spec_error[None]": 0.001,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_mapping_top_level_raises_pipe_spec_error[a string]": 0.0006,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_non_mapping_top_level_raises_pipe_spec_error[bad_spec1]": 0.0007,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_original_dict_unchanged": 0.0009,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_output_alias_accepted[output_concept]": 0.0011,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_output_alias_accepted[output_type]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_output_alias_tried_first_when_canonical_present[output_concept]": 0.0006,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_output_alias_tried_first_when_canonical_present[output_type]": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_output_as_string": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_output_dict_with_type_key": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_output_multi_item_dict_raises": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_output_single_item_dict": 0.0017,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_output_type_key_takes_precedence_in_dict": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_parallel_branches_all_aliases[code]": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_parallel_branches_all_aliases[name]": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_parallel_branches_all_aliases[pipe]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_parallel_branches_all_aliases[pipe_name]": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_parallel_branches_all_aliases[pipe_ref]": 0.0016,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_parallel_branches_all_aliases[the_pipe_code]": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_parallel_branches_extraneous_inputs_dropped": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_pipe_code_alias_accepted[code]": 0.0009,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_pipe_code_alias_accepted[name]": 0.001,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_pipe_code_alias_accepted[pipe_name]": 0.0015,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_pipe_code_alias_accepted[pipe_ref]": 0.0007,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_pipe_code_alias_accepted[the_pipe_code]": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_prompt_template_alias_for_img_gen": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_prompt_template_alias_for_llm": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_sequence_steps_all_aliases[code]": 0.0007,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_sequence_steps_all_aliases[name]": 0.0006,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_sequence_steps_all_aliases[pipe]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_sequence_steps_all_aliases[pipe_name]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_sequence_steps_all_aliases[pipe_ref]": 0.0005,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_sequence_steps_all_aliases[the_pipe_code]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_sequence_steps_canonical_pipe_code": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_sequence_steps_extraneous_inputs_dropped": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_typeless_spec_accepts_dict_output": 0.0003,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_typeless_spec_accepts_output_alias[output_concept]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_typeless_spec_accepts_output_alias[output_type]": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_typeless_spec_becomes_signature": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_typeless_spec_preserves_signature_for_hint": 0.0004,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_typeless_spec_stray_impl_field_still_rejected_after_output_normalization": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_typeless_spec_with_stray_field_raises_teaching_error": 0.0008,- "tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py::TestParsePipeSpec::test_unknown_type_raises": 4.6708,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_batch_fields_in_toml": 0.0007,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_compose_construct_with_from_mappings": 0.0024,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_compose_construct_with_static_values": 0.0007,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_compose_no_construct_in_template_mode": 0.0006,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_compose_no_template_in_construct_mode": 0.0997,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_compose_template_mode_fields": 0.0006,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_condition_expression_outcomes_default": 0.0012,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_doc_gen_model_in_toml": 0.0723,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_doc_gen_no_model_omits_field": 0.0651,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_extract_max_page_images_in_toml": 0.0022,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_extract_model_in_toml": 0.0014,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_extract_no_optional_fields_omits_them": 0.0006,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_extract_page_views_in_toml": 0.0007,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_func_function_name_in_toml": 0.0012,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_img_gen_model_and_prompt_in_toml": 0.0011,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_img_gen_no_model_omits_field": 0.0012,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_llm_basic_structure": 0.0009,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_llm_inputs_as_inline_table": 0.0033,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_llm_model_in_toml": 0.0009,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_llm_multiple_inputs": 0.0005,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_llm_no_inputs_omits_inputs": 0.0007,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_llm_no_model_omits_field": 0.0014,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_llm_no_structuring_method_omits_field": 0.0005,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_llm_prompt_in_toml": 0.0013,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_llm_structuring_method_direct_in_toml": 0.001,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_llm_structuring_method_preliminary_text_in_toml": 0.001,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_llm_system_prompt_in_toml": 0.0012,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_parallel_branches_and_add_each_output": 0.0008,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_search_all_fields_in_toml": 0.0039,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_search_minimal": 0.0005,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_sequence_step_with_batch_over": 0.0007,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_sequence_steps_in_toml": 0.0011,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_signature_toml_has_no_type_line": 0.7419,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_signature_toml_preserves_signature_for_hint": 0.0044,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_structure_basic_structure": 0.0011,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_structure_model_in_toml": 0.0011,- "tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py::TestPipeSpecToToml::test_structure_no_model_omits_field": 0.0005,- "tests/unit/pipelex/builder/pipe/pipe_controller/pipe_batch/test_pipe_batch.py::TestPipeBatchBlueprintConversion::test_pipe_batch_spec_to_blueprint[batch_with_names-pipe_spec0-expected_blueprint0]": 0.7735,- "tests/unit/pipelex/builder/pipe/pipe_controller/pipe_batch/test_pipe_batch.py::TestPipeBatchBlueprintConversion::test_rejects_input_item_name_same_as_input_list_name": 0.0005,- "tests/unit/pipelex/builder/pipe/pipe_controller/pipe_batch/test_pipe_batch.py::TestPipeBatchBlueprintConversion::test_rejects_input_item_name_same_as_inputs_key": 0.1285,- "tests/unit/pipelex/builder/pipe/pipe_controller/pipe_condition/test_pipe_condition.py::TestPipeConditionBlueprintConversion::test_pipe_condition_spec_to_blueprint[condition_with_template-pipe_spec0-expected_blueprint0]": 0.8808,- "tests/unit/pipelex/builder/pipe/pipe_controller/pipe_parallel/test_pipe_parallel.py::TestPipeParallelBlueprintConversion::test_pipe_parallel_spec_to_blueprint[parallel_omitting_add_each_output-pipe_spec2-expected_blueprint2]": 0.1725,- "tests/unit/pipelex/builder/pipe/pipe_controller/pipe_parallel/test_pipe_parallel.py::TestPipeParallelBlueprintConversion::test_pipe_parallel_spec_to_blueprint[parallel_with_each_output-pipe_spec0-expected_blueprint0]": 0.8143,- "tests/unit/pipelex/builder/pipe/pipe_controller/pipe_parallel/test_pipe_parallel.py::TestPipeParallelBlueprintConversion::test_pipe_parallel_spec_to_blueprint[parallel_without_each_output-pipe_spec1-expected_blueprint1]": 0.0575,- "tests/unit/pipelex/builder/pipe/pipe_controller/pipe_sequence/test_pipe_sequence.py::TestPipeSequenceBlueprintConversion::test_pipe_sequence_spec_to_blueprint[sequence_with_batch_step-pipe_spec1-expected_blueprint1]": 0.0912,- "tests/unit/pipelex/builder/pipe/pipe_controller/pipe_sequence/test_pipe_sequence.py::TestPipeSequenceBlueprintConversion::test_pipe_sequence_spec_to_blueprint[simple_sequence-pipe_spec0-expected_blueprint0]": 0.7959,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose.py::TestPipeComposeBlueprintConversion::test_pipe_compose_spec_to_blueprint[construct_compose-pipe_spec1-expected_blueprint1]": 0.1089,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose.py::TestPipeComposeBlueprintConversion::test_pipe_compose_spec_to_blueprint[simple_compose-pipe_spec0-expected_blueprint0]": 0.859,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose_to_toml.py::TestPipeComposeToToml::test_construct_mode_has_construct_section": 0.002,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose_to_toml.py::TestPipeComposeToToml::test_construct_with_static_values": 0.0011,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose_to_toml.py::TestPipeComposeToToml::test_pipe_spec_to_toml_does_not_crash[construct_with_from_mappings-spec_data0]": 0.8345,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose_to_toml.py::TestPipeComposeToToml::test_pipe_spec_to_toml_does_not_crash[construct_with_static_values-spec_data1]": 0.0009,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose_to_toml.py::TestPipeComposeToToml::test_pipe_spec_to_toml_does_not_crash[template_mode-spec_data2]": 0.0007,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose_to_toml.py::TestPipeComposeToToml::test_template_mode_has_target_format_and_template": 0.1176,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_extract/test_pipe_extract.py::TestPipeExtractBlueprintConversion::test_pipe_extract_spec_to_blueprint[extract_with_options-pipe_spec1-expected_blueprint1]": 0.1259,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_extract/test_pipe_extract.py::TestPipeExtractBlueprintConversion::test_pipe_extract_spec_to_blueprint[simple_extract-pipe_spec0-expected_blueprint0]": 0.8122,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_func/test_pipe_func.py::TestPipeFuncBlueprintConversion::test_pipe_func_spec_to_blueprint[func_no_inputs-pipe_spec1-expected_blueprint1]": 0.1077,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_func/test_pipe_func.py::TestPipeFuncBlueprintConversion::test_pipe_func_spec_to_blueprint[simple_func-pipe_spec0-expected_blueprint0]": 0.7263,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_img_gen/test_pipe_img_gen.py::TestPipeImgGenBlueprintConversion::test_pipe_img_gen_spec_to_blueprint[img_gen_with_options-pipe_spec1-expected_blueprint1]": 0.102,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_img_gen/test_pipe_img_gen.py::TestPipeImgGenBlueprintConversion::test_pipe_img_gen_spec_to_blueprint[simple_img_gen-pipe_spec0-expected_blueprint0]": 0.6787,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_pipe_llm.py::TestPipeLLMBlueprintConversion::test_pipe_llm_spec_to_blueprint[llm_no_inputs-pipe_spec1-expected_blueprint1]": 0.0444,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_pipe_llm.py::TestPipeLLMBlueprintConversion::test_pipe_llm_spec_to_blueprint[llm_with_fixed_output-pipe_spec7-expected_blueprint7]": 0.2042,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_pipe_llm.py::TestPipeLLMBlueprintConversion::test_pipe_llm_spec_to_blueprint[llm_with_multiple_output-pipe_spec6-expected_blueprint6]": 0.0955,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_pipe_llm.py::TestPipeLLMBlueprintConversion::test_pipe_llm_spec_to_blueprint[llm_with_preset-pipe_spec3-expected_blueprint3]": 0.0548,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_pipe_llm.py::TestPipeLLMBlueprintConversion::test_pipe_llm_spec_to_blueprint[llm_with_settings-pipe_spec4-expected_blueprint4]": 0.0575,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_pipe_llm.py::TestPipeLLMBlueprintConversion::test_pipe_llm_spec_to_blueprint[llm_with_system_prompt-pipe_spec5-expected_blueprint5]": 0.0536,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_pipe_llm.py::TestPipeLLMBlueprintConversion::test_pipe_llm_spec_to_blueprint[llm_with_vision_input-pipe_spec2-expected_blueprint2]": 0.0565,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_pipe_llm.py::TestPipeLLMBlueprintConversion::test_pipe_llm_spec_to_blueprint[simple_llm-pipe_spec0-expected_blueprint0]": 0.7886,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_structure/test_pipe_structure_spec.py::TestPipeStructureSpec::test_spec_rejects_empty_model": 0.0966,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_structure/test_pipe_structure_spec.py::TestPipeStructureSpec::test_spec_to_blueprint_minimal": 1.1154,- "tests/unit/pipelex/builder/pipe/pipe_operator/pipe_structure/test_pipe_structure_spec.py::TestPipeStructureSpec::test_spec_to_blueprint_with_model": 0.0018,- "tests/unit/pipelex/builder/pipe/test_inputs_blueprint.py::TestInputRequirementBlueprintConversion::test_input_requirement_spec_to_string[custom_concept_input-CustomConcept-CustomConcept]": 0.0012,- "tests/unit/pipelex/builder/pipe/test_inputs_blueprint.py::TestInputRequirementBlueprintConversion::test_input_requirement_spec_to_string[domain_concept_input-domain.ConceptName-domain.ConceptName]": 0.1154,- "tests/unit/pipelex/builder/pipe/test_inputs_blueprint.py::TestInputRequirementBlueprintConversion::test_input_requirement_spec_to_string[image_input-Image-Image]": 0.0007,- "tests/unit/pipelex/builder/pipe/test_inputs_blueprint.py::TestInputRequirementBlueprintConversion::test_input_requirement_spec_to_string[simple_text_input-Text-Text]": 1.5593,- "tests/unit/pipelex/builder/pipe/test_pipe_blueprint.py::TestPipeBlueprintConversion::test_pipe_blueprint_to_core[pipe_no_inputs-pipe_spec2-expected_blueprint2]": 0.2417,- "tests/unit/pipelex/builder/pipe/test_pipe_blueprint.py::TestPipeBlueprintConversion::test_pipe_blueprint_to_core[pipe_with_requirements-pipe_spec1-expected_blueprint1]": 0.0005,- "tests/unit/pipelex/builder/pipe/test_pipe_blueprint.py::TestPipeBlueprintConversion::test_pipe_blueprint_to_core[simple_pipe-pipe_spec0-expected_blueprint0]": 1.1046,- "tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py::TestPipeSignatureSpec::test_inputs_accept_multiplicity": 0.0008,- "tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py::TestPipeSignatureSpec::test_inputs_reject_invalid_concept_syntax": 0.0009,- "tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py::TestPipeSignatureSpec::test_no_result_field": 0.0007,- "tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py::TestPipeSignatureSpec::test_rendered_pretty_preserves_bracketed_values_multi_input": 0.0974,- "tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py::TestPipeSignatureSpec::test_rendered_pretty_preserves_bracketed_values_single_input": 0.0014,- "tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py::TestPipeSignatureSpec::test_signature_for_optional": 0.0005,- "tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py::TestPipeSignatureSpec::test_signature_for_rejects_pipe_signature": 0.0005,- "tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py::TestPipeSignatureSpec::test_to_blueprint_preserves_input_multiplicity": 0.0004,- "tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py::TestPipeSignatureSpec::test_to_blueprint_returns_signature_blueprint": 0.0008,- "tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py::TestPipeSignatureSpec::test_type_literal_is_pipe_signature": 0.9351,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_code_validation.py::TestPipeSpecCodeValidation::test_validate_pipe_code_syntax_raises_for_invalid_after_strip": 0.1493,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_code_validation.py::TestPipeSpecCodeValidation::test_validate_pipe_code_syntax_strips_namespace[multi_dot]": 0.0484,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_code_validation.py::TestPipeSpecCodeValidation::test_validate_pipe_code_syntax_strips_namespace[passthrough]": 0.0004,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_code_validation.py::TestPipeSpecCodeValidation::test_validate_pipe_code_syntax_strips_namespace[single_dot]": 0.7526,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_code_validation.py::TestPipeSpecCodeValidation::test_validate_pipe_code_syntax_strips_namespace[unicode_with_dot]": 0.0532,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_force_marker_on_output_rejected[Text!]": 0.0013,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_force_marker_on_output_rejected[domain.Concept!]": 0.0008,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_malformed_marker_input_syntax_rejected[Text??]": 0.0012,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_malformed_marker_input_syntax_rejected[Text?[]]": 0.1307,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_marker_on_count_of_one_input_accepted[Text[1]!]": 0.3287,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_marker_on_count_of_one_input_accepted[Text[1]?]": 0.1962,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_marker_on_count_of_one_input_accepted[domain.Concept[1]?]": 1.5633,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_marker_on_plural_input_rejected[Text[3]?]": 0.0012,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_marker_on_plural_input_rejected[Text[]!]": 0.0009,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_marker_on_plural_input_rejected[Text[]?]": 0.0007,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_optional_marker_on_plural_output_rejected[Text[3]?]": 0.0007,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_optional_marker_on_plural_output_rejected[Text[]?]": 0.0005,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_optional_output_accepted[Text?]": 0.0014,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_optional_output_accepted[domain.Concept?]": 0.0006,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_singular_input_markers_accepted[Text!]": 0.0009,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_singular_input_markers_accepted[Text?]": 0.8036,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_singular_input_markers_accepted[domain.Concept!]": 0.0005,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_singular_input_markers_accepted[domain.Concept?]": 0.0023,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_to_blueprint_passes_markers_through": 0.0003,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_zero_count_input_rejected[Text[0]!]": 1.409,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_zero_count_input_rejected[Text[0]?]": 0.293,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_zero_count_input_rejected[Text[0]]": 0.0187,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py::TestPipeSpecPresenceMarkers::test_zero_count_input_rejected[domain.Concept[0]]": 0.0192,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_union_signature.py::TestPipeSpecUnionDispatch::test_union_dispatches_pipe_llm_unchanged": 0.081,- "tests/unit/pipelex/builder/pipe/test_pipe_spec_union_signature.py::TestPipeSpecUnionDispatch::test_union_dispatches_pipe_signature": 0.9045,- "tests/unit/pipelex/builder/pipe/test_sub_pipe_blueprint.py::TestSubPipeBlueprintConversion::test_sub_pipe_to_core[simple_sub_pipe-sub_pipe_spec0-expected_blueprint0]": 0.8465,- "tests/unit/pipelex/builder/pipe/test_sub_pipe_blueprint.py::TestSubPipeBlueprintConversion::test_sub_pipe_to_core[sub_pipe_with_batch-sub_pipe_spec1-expected_blueprint1]": 0.1064,- "tests/unit/pipelex/builder/test_bundle_spec_rendered_pretty.py::TestPipelexBundleSpecRenderedPretty::test_concepts_table_renders_spec_and_string_rows": 0.0046,- "tests/unit/pipelex/builder/test_bundle_spec_rendered_pretty.py::TestPipelexBundleSpecRenderedPretty::test_full_render_with_title": 0.9767,- "tests/unit/pipelex/builder/test_bundle_spec_rendered_pretty.py::TestPipelexBundleSpecRenderedPretty::test_minimal_render_omits_optional_sections": 0.1058,- "tests/unit/pipelex/builder/test_bundle_spec_rendered_pretty.py::TestPipelexBundleSpecRenderedPretty::test_pipes_table_lists_each_pipe": 0.003,- "tests/unit/pipelex/builder/test_bundle_spec_to_blueprint.py::TestPipelexBundleSpecToBlueprint::test_bundle_blueprint_construction_failure_wrapped": 0.1197,- "tests/unit/pipelex/builder/test_bundle_spec_to_blueprint.py::TestPipelexBundleSpecToBlueprint::test_concept_spec_value_converted_to_concept_blueprint": 0.7865,- "tests/unit/pipelex/builder/test_bundle_spec_to_blueprint.py::TestPipelexBundleSpecToBlueprint::test_no_concepts_yields_none_concept_on_blueprint[None]": 0.0007,- "tests/unit/pipelex/builder/test_bundle_spec_to_blueprint.py::TestPipelexBundleSpecToBlueprint::test_no_concepts_yields_none_concept_on_blueprint[empty_concepts1]": 0.0031,- "tests/unit/pipelex/builder/test_bundle_spec_to_blueprint.py::TestPipelexBundleSpecToBlueprint::test_pipe_spec_validation_error_wrapped_with_pipe_code": 0.004,- "tests/unit/pipelex/builder/test_bundle_spec_to_blueprint.py::TestPipelexBundleSpecToBlueprint::test_pipes_sorted_controller_first_then_step_order": 0.0009,- "tests/unit/pipelex/builder/test_bundle_spec_to_blueprint.py::TestPipelexBundleSpecToBlueprint::test_string_concept_value_passes_through_as_description": 0.0005,- "tests/unit/pipelex/builder/test_bundle_spec_to_blueprint.py::TestPipelexBundleSpecToBlueprint::test_string_concept_value_survives_normal_validation": 0.0004,- "tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py::TestPipelexBundleSpecTypelessSignature::test_already_built_spec_instance_passes_through": 0.0771,- "tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py::TestPipelexBundleSpecTypelessSignature::test_explicit_signature_tag_rejected": 0.0004,- "tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py::TestPipelexBundleSpecTypelessSignature::test_invalid_pipe_dict_key_rejected_at_spec_level": 0.001,- "tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py::TestPipelexBundleSpecTypelessSignature::test_signature_spec_survives_model_dump_revalidate_round_trip": 0.0008,- "tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py::TestPipelexBundleSpecTypelessSignature::test_stray_key_message_advertises_signature_for": 0.0006,- "tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py::TestPipelexBundleSpecTypelessSignature::test_typed_section_left_untouched": 0.0005,- "tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py::TestPipelexBundleSpecTypelessSignature::test_typeless_contract_section_becomes_signature_spec": 0.841,- "tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py::TestPipelexBundleSpecTypelessSignature::test_typeless_with_blueprint_only_source_field_raises_teaching_error": 0.0007,- "tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py::TestPipelexBundleSpecTypelessSignature::test_typeless_with_signature_for_hint_becomes_signature": 0.0016,- "tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py::TestPipelexBundleSpecTypelessSignature::test_typeless_with_stray_field_raises_teaching_error": 0.0007,- "tests/unit/pipelex/builder/test_bundle_spec_validation.py::TestPipelexBundleSpecValidation::test_invalid_domain_code_rejected[1starts_with_digit]": 0.0011,- "tests/unit/pipelex/builder/test_bundle_spec_validation.py::TestPipelexBundleSpecValidation::test_invalid_domain_code_rejected[Bad Domain]": 0.7739,- "tests/unit/pipelex/builder/test_bundle_spec_validation.py::TestPipelexBundleSpecValidation::test_invalid_domain_code_rejected[UpperCase]": 0.0013,- "tests/unit/pipelex/builder/test_bundle_spec_validation.py::TestPipelexBundleSpecValidation::test_invalid_domain_code_rejected[has-dashes]": 0.0015,- "tests/unit/pipelex/builder/test_bundle_spec_validation.py::TestPipelexBundleSpecValidation::test_main_pipe_absent_from_pipe_dict_rejected": 0.0013,- "tests/unit/pipelex/builder/test_bundle_spec_validation.py::TestPipelexBundleSpecValidation::test_main_pipe_with_no_pipes_rejected[None]": 0.0005,- "tests/unit/pipelex/builder/test_bundle_spec_validation.py::TestPipelexBundleSpecValidation::test_main_pipe_with_no_pipes_rejected[empty_pipes0]": 0.0018,- "tests/unit/pipelex/builder/test_bundle_spec_validation.py::TestPipelexBundleSpecValidation::test_valid_spec_constructs": 0.0987,- "tests/unit/pipelex/builder/test_runner_generator.py::TestConceptGenerateInputRepresentationJson::test_native_document_json_with_multiplicity": 0.0004,- "tests/unit/pipelex/builder/test_runner_generator.py::TestConceptGenerateInputRepresentationJson::test_native_image_json": 0.0004,- "tests/unit/pipelex/builder/test_runner_generator.py::TestConceptGenerateInputRepresentationJson::test_native_number_json": 0.0004,- "tests/unit/pipelex/builder/test_runner_generator.py::TestConceptGenerateInputRepresentationJson::test_native_text_json": 0.7569,- "tests/unit/pipelex/builder/test_runner_generator.py::TestConceptGenerateInputRepresentationPython::test_native_document_python_with_multiplicity": 0.0008,- "tests/unit/pipelex/builder/test_runner_generator.py::TestConceptGenerateInputRepresentationPython::test_native_image_python": 0.0008,- "tests/unit/pipelex/builder/test_runner_generator.py::TestConceptGenerateInputRepresentationPython::test_native_text_python": 0.0012,- "tests/unit/pipelex/builder/test_runner_generator.py::TestConceptGenerateInputRepresentationPython::test_refined_text_python": 0.0004,- "tests/unit/pipelex/builder/test_runner_generator.py::TestGenerateRunnerCode::test_runner_code_anything_output_uses_any_return_type": 0.1065,- "tests/unit/pipelex/builder/test_runner_generator.py::TestGenerateRunnerCode::test_runner_code_class_name_overrides_spell_emitted_names": 0.0008,- "tests/unit/pipelex/builder/test_runner_generator.py::TestGenerateRunnerCode::test_runner_code_custom_class_import_format": 0.0016,- "tests/unit/pipelex/builder/test_runner_generator.py::TestGenerateRunnerCode::test_runner_code_includes_imports": 0.0027,- "tests/unit/pipelex/builder/test_runner_generator.py::TestGenerateRunnerCode::test_runner_code_includes_inputs": 0.0014,- "tests/unit/pipelex/builder/test_runner_generator.py::TestGenerateRunnerCode::test_runner_code_includes_main_block": 0.002,- "tests/unit/pipelex/builder/test_runner_generator.py::TestGenerateRunnerCode::test_runner_code_includes_structure_imports": 0.0008,- "tests/unit/pipelex/builder/test_runner_generator.py::TestGenerateRunnerCode::test_runner_code_list_output_return_type": 0.0017,- "tests/unit/pipelex/builder/test_runner_generator.py::TestGenerateRunnerCode::test_runner_code_multiplicity_input": 0.0021,- "tests/unit/pipelex/builder/test_runner_generator.py::TestGenerateRunnerCode::test_runner_code_single_output_return_type": 0.0024,- "tests/unit/pipelex/builder/test_runner_generator.py::TestInputStuffSpecsRenderInputsRepresentation::test_empty_inputs": 0.0003,- "tests/unit/pipelex/builder/test_runner_generator.py::TestInputStuffSpecsRenderInputsRepresentation::test_multiple_inputs": 0.0009,- "tests/unit/pipelex/builder/test_runner_generator.py::TestInputStuffSpecsRenderInputsRepresentation::test_single_input": 0.0003,- "tests/unit/pipelex/builder/test_runner_generator.py::TestInputStuffSpecsRenderWithMultiplicity::test_mixed_multiplicity": 0.0007,- "tests/unit/pipelex/builder/test_runner_generator.py::TestInputStuffSpecsRenderWithMultiplicity::test_multiple_items_int_multiplicity": 0.0014,- "tests/unit/pipelex/builder/test_runner_generator.py::TestInputStuffSpecsRenderWithMultiplicity::test_multiple_items_true_multiplicity": 0.0022,- "tests/unit/pipelex/builder/test_runner_generator.py::TestInputStuffSpecsRenderWithMultiplicity::test_single_item_no_multiplicity": 0.0008,"tests/unit/pipelex/cli/agent_cli/commands/test_bundle_path_resolver.py::TestResolveBundleTarget::test_ambiguous_directory_error_names_candidates_in_sorted_order": 0.0022,"tests/unit/pipelex/cli/agent_cli/commands/test_bundle_path_resolver.py::TestResolveBundleTarget::test_directory_mode_expands_tilde_and_injects_expanded_dir": 0.0012,"tests/unit/pipelex/cli/agent_cli/commands/test_bundle_path_resolver.py::TestResolveBundleTarget::test_directory_refuses_auto_detected_symlink": 0.0939,@@ -2077,15 +1719,6 @@"tests/unit/pipelex/cli/commands/build/test_output_core.py::TestGenerateOutputCore::test_render_value_error_exits_zero": 0.0034,"tests/unit/pipelex/cli/commands/build/test_output_core.py::TestGenerateOutputCore::test_schema_format_defaults_to_results_dir_without_bundle": 0.007,"tests/unit/pipelex/cli/commands/build/test_output_core.py::TestGenerateOutputCore::test_validate_bundle_error_exits": 0.0075,- "tests/unit/pipelex/cli/commands/build/test_runner_core.py::TestPrepareRunnerCore::test_bundle_main_pipe_writes_runner_next_to_bundle": 0.7713,- "tests/unit/pipelex/cli/commands/build/test_runner_core.py::TestPrepareRunnerCore::test_bundle_without_main_pipe_exits": 0.0046,- "tests/unit/pipelex/cli/commands/build/test_runner_core.py::TestPrepareRunnerCore::test_explicit_output_path_wins": 0.004,- "tests/unit/pipelex/cli/commands/build/test_runner_core.py::TestPrepareRunnerCore::test_no_bundle_exits": 0.0077,- "tests/unit/pipelex/cli/commands/build/test_runner_core.py::TestPrepareRunnerCore::test_no_crate_skips_structures_projection": 0.0055,- "tests/unit/pipelex/cli/commands/build/test_runner_core.py::TestPrepareRunnerCore::test_output_multiplicity_detected_from_pipe_blueprint": 0.0063,- "tests/unit/pipelex/cli/commands/build/test_runner_core.py::TestPrepareRunnerCore::test_runner_codegen_failure_exits": 0.106,- "tests/unit/pipelex/cli/commands/build/test_runner_core.py::TestPrepareRunnerCore::test_structures_projection_emitted_into_structures_dir": 0.0053,- "tests/unit/pipelex/cli/commands/build/test_runner_core.py::TestPrepareRunnerCore::test_validate_bundle_error_exits": 0.0058,"tests/unit/pipelex/cli/commands/build/test_structures_alias.py::TestBuildStructuresAlias::test_directory_target_delegates_with_default_output": 0.9231,"tests/unit/pipelex/cli/commands/build/test_structures_alias.py::TestBuildStructuresAlias::test_explicit_output_dir_and_library_dirs_pass_through": 0.0015,"tests/unit/pipelex/cli/commands/build/test_structures_alias.py::TestBuildStructuresAlias::test_file_target_resolves_to_parent_directory": 0.0023,@@ -2751,9 +2384,6 @@"tests/unit/pipelex/cli/test_agent_output_drift.py::TestAgentOutputDrift::test_every_dict_key_is_a_known_error_type": 0.9663,"tests/unit/pipelex/cli/test_agent_validate_cmd.py::TestValidateBundleCmd::test_graph_generation_failure_emits_single_json_error": 1.0948,"tests/unit/pipelex/cli/test_agent_validate_cmd.py::TestValidateBundleCmd::test_view_generation_uses_pipe_override": 0.2215,- "tests/unit/pipelex/cli/test_build_runner_method_materialization.py::TestBuildRunnerMethodMaterialization::test_fetched_materialization_excludes_git_metadata": 1.2136,- "tests/unit/pipelex/cli/test_build_runner_method_materialization.py::TestBuildRunnerMethodMaterialization::test_fetched_method_is_materialized_beside_the_script": 1.2591,- "tests/unit/pipelex/cli/test_build_runner_method_materialization.py::TestBuildRunnerMethodMaterialization::test_installed_method_is_not_copied": 1.2286,"tests/unit/pipelex/cli/test_check_model_cmd.py::TestCheckModelCmd::test_completely_unknown_name": 0.0029,"tests/unit/pipelex/cli/test_check_model_cmd.py::TestCheckModelCmd::test_invalid_handle_cross_collection_suggestions": 0.0017,"tests/unit/pipelex/cli/test_check_model_cmd.py::TestCheckModelCmd::test_invalid_handle_fuzzy_suggestions": 0.002,@@ -3161,23 +2791,6 @@"tests/unit/pipelex/cli/test_output_helpers.py::TestBuildRunOutput::test_full_with_memory": 0.0009,"tests/unit/pipelex/cli/test_output_helpers.py::TestBuildRunOutput::test_full_with_memory_includes_extra_metadata": 0.0015,"tests/unit/pipelex/cli/test_output_helpers.py::TestBuildRunOutput::test_with_memory_ignores_compact_result": 0.0005,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_doc_gen_model_in_toml": 0.0622,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_explicit_null_type_rejected": 0.0007,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_extract_model_in_toml": 0.0014,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_img_gen_model_in_toml": 0.0013,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_llm_different_model_in_toml": 0.0014,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_llm_model_appears_in_toml": 0.0014,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_llm_no_model_omits_model_in_toml": 0.0013,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_model_with_dict_output_both_tolerated": 0.0009,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_non_string_type_rejected_with_actionable_error": 0.001,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_search_fields_appear_in_toml": 0.0019,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_search_optional_filters_omitted_in_toml": 0.0014,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_sequence_toml_has_steps": 0.0017,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_toml_contains_pipe_section": 0.0013,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_toml_contains_prompt": 0.0013,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_toml_output_has_correct_model": 0.1018,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_type_extracted_from_spec": 0.8228,- "tests/unit/pipelex/cli/test_pipe_cmd.py::TestCliPipeCmd::test_typeless_spec_renders_signature_without_type_line": 0.0015,"tests/unit/pipelex/cli/test_print_traceback_if_requested.py::TestPrintTracebackIfRequested::test_does_not_print_when_flag_not_set": 0.8294,"tests/unit/pipelex/cli/test_print_traceback_if_requested.py::TestPrintTracebackIfRequested::test_prints_traceback_when_flag_set": 0.1755,"tests/unit/pipelex/cli/test_readiness.py::TestReadiness::test_check_readiness_passes_for_dev_install_in_venv": 0.0007,@@ -8735,17 +8348,6 @@"tests/unit/pipelex/mthds_parsing/test_parser_preliminary_text.py::TestInterpreterPreliminaryText::test_mthds_without_preliminary_text_is_unchanged": 0.0986,"tests/unit/pipelex/mthds_parsing/test_parser_rejected_structure_fields.py::TestRejectedStructureFieldParsing::test_required_with_default_fails_the_parse_naming_the_pair": 0.2417,"tests/unit/pipelex/mthds_parsing/test_parser_rejected_structure_fields.py::TestRejectedStructureFieldParsing::test_unknown_structure_field_key_fails_the_parse_naming_the_key": 0.207,- "tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py::TestSortPipesByDependencies::test_circular_dependency_error_carries_domain_code": 0.1126,- "tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py::TestSortPipesByDependencies::test_sort_pipes_by_dependencies[circular_dependency-pipes6-None-PipeValidationError]": 0.0012,- "tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py::TestSortPipesByDependencies::test_sort_pipes_by_dependencies[complex_nested-pipes9-expected_order9-None]": 0.0008,- "tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py::TestSortPipesByDependencies::test_sort_pipes_by_dependencies[diamond_pattern-pipes2-None-None]": 0.001,- "tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py::TestSortPipesByDependencies::test_sort_pipes_by_dependencies[image_inversion-pipes8-expected_order8-None]": 0.0007,- "tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py::TestSortPipesByDependencies::test_sort_pipes_by_dependencies[missing_dependency-pipes7-expected_order7-None]": 0.0004,- "tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py::TestSortPipesByDependencies::test_sort_pipes_by_dependencies[multiple_chains-pipes3-expected_order3-None]": 0.0009,- "tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py::TestSortPipesByDependencies::test_sort_pipes_by_dependencies[no_dependencies-pipes0-expected_order0-None]": 0.7554,- "tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py::TestSortPipesByDependencies::test_sort_pipes_by_dependencies[pipe_batch-pipes4-expected_order4-None]": 0.0008,- "tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py::TestSortPipesByDependencies::test_sort_pipes_by_dependencies[pipe_condition-pipes5-expected_order5-None]": 0.0011,- "tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py::TestSortPipesByDependencies::test_sort_pipes_by_dependencies[simple_chain-pipes1-expected_order1-None]": 0.0022,"tests/unit/pipelex/mthds_parsing/test_pipelex_bundle_blueprint_concept_construction.py::TestPipelexBundleBlueprintConceptConstruction::test_valid_concept_ref_in_structure": 0.0009,"tests/unit/pipelex/mthds_parsing/test_pipelex_bundle_blueprint_concept_construction.py::TestPipelexBundleBlueprintConceptConstruction::test_valid_concept_with_multiplicity": 0.0014,"tests/unit/pipelex/mthds_parsing/test_pipelex_bundle_blueprint_concept_construction.py::TestPipelexBundleBlueprintConceptConstruction::test_valid_declared_concept_in_refines": 0.0009,@@ -9925,6 +9527,17 @@"tests/unit/pipelex/pipeline/test_input_normalizer_read_scope.py::TestInputNormalizerReadScope::test_a_scoped_run_refuses_to_sign_a_foreign_storage_reference": 0.0012,"tests/unit/pipelex/pipeline/test_input_normalizer_read_scope.py::TestInputNormalizerReadScope::test_a_scoped_run_signs_an_in_scope_reference": 0.0012,"tests/unit/pipelex/pipeline/test_input_normalizer_read_scope.py::TestInputNormalizerReadScope::test_an_unscoped_run_uploads_a_local_path_as_before": 0.0033,+ "tests/unit/pipelex/pipeline/test_inputs_template.py::TestBuildInputsForPipe::test_bundle_path_explicit_pipe_code_wins": 0.003,+ "tests/unit/pipelex/pipeline/test_inputs_template.py::TestBuildInputsForPipe::test_bundle_path_validates_file_and_qualifies_main_pipe": 0.0055,+ "tests/unit/pipelex/pipeline/test_inputs_template.py::TestBuildInputsForPipe::test_bundle_path_without_main_pipe_raises_with_path": 0.0047,+ "tests/unit/pipelex/pipeline/test_inputs_template.py::TestBuildInputsForPipe::test_happy_path_return_shape": 0.1,+ "tests/unit/pipelex/pipeline/test_inputs_template.py::TestBuildInputsForPipe::test_mthds_contents_explicit_pipe_code_skips_scan": 0.004,+ "tests/unit/pipelex/pipeline/test_inputs_template.py::TestBuildInputsForPipe::test_mthds_contents_first_main_pipe_wins_domain_qualified": 0.7118,+ "tests/unit/pipelex/pipeline/test_inputs_template.py::TestBuildInputsForPipe::test_mthds_contents_validates_with_allow_signatures": 0.0041,+ "tests/unit/pipelex/pipeline/test_inputs_template.py::TestBuildInputsForPipe::test_mthds_contents_without_any_main_pipe_raises": 0.0023,+ "tests/unit/pipelex/pipeline/test_inputs_template.py::TestBuildInputsForPipe::test_no_bundle_and_no_pipe_code_raises": 0.0041,+ "tests/unit/pipelex/pipeline/test_inputs_template.py::TestBuildInputsForPipe::test_no_bundle_empty_resolved_dirs_skips_loading": 0.0028,+ "tests/unit/pipelex/pipeline/test_inputs_template.py::TestBuildInputsForPipe::test_no_bundle_loads_libraries_from_resolved_dirs": 0.004,"tests/unit/pipelex/pipeline/test_load_libraries_and_activate.py::TestLoadLibrariesAndActivate::test_rejects_bare_string": 0.8943,"tests/unit/pipelex/pipeline/test_markdown_input_form_and_hints.py::TestMarkdownInputFormAndHints::test_markdown_chains_are_text_valued_sites[docs.Minutes-prose]": 0.0014,"tests/unit/pipelex/pipeline/test_markdown_input_form_and_hints.py::TestMarkdownInputFormAndHints::test_markdown_chains_are_text_valued_sites[docs.Report-text]": 0.0015,@@ -9948,7 +9561,7 @@"tests/unit/pipelex/pipeline/test_runner_execute_error_paths.py::TestRunnerExecuteErrorPaths::test_validation_error_wraps_into_pipe_execution_error": 0.101,"tests/unit/pipelex/pipeline/test_runner_models.py::TestRunnerModels::test_deck_keeps_category_keyed_aliases_on_cross_category_collision": 0.9182,"tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py::TestRunnerProtocolSurfaces::test_execute_rejects_extra_args_listing_keys_sorted": 0.7517,- "tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py::TestRunnerProtocolSurfaces::test_models_category_filter_translates_to_builder_enum": 0.0015,+ "tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py::TestRunnerProtocolSurfaces::test_models_category_filter_translates_to_listing_enum": 0.0015,"tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py::TestRunnerProtocolSurfaces::test_models_shapes_deck_and_keeps_aliases_and_waterfalls_keyed_by_category": 0.0016,"tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py::TestRunnerProtocolSurfaces::test_start_raises_not_implemented_pointing_at_execute": 0.001,"tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py::TestRunnerProtocolSurfaces::test_validate_rejects_blank_graph_pipe_code_extra": 0.001,@@ -12154,21 +11767,13 @@"tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_exclude_using_absolute_path_structures_directory": 0.0019,"tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_empty_directory": 0.0005,"tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_empty_excluded_list": 0.0015,- "tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_empty_force_include_list": 0.0011,- "tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_force_include_not_in_excluded_dir": 0.0015,"tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_no_excluded_dirs": 0.0027,- "tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_no_force_include_dirs": 0.001,"tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_no_matches": 0.0009,"tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_non_recursive": 0.7607,"tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_pattern_matching": 0.0016,"tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_recursive": 0.0012,- "tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_with_deeply_nested_force_include": 0.0021,"tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_with_excluded_dirs_multiple": 0.0021,"tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_with_excluded_dirs_single": 0.0018,- "tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_with_force_include_dirs_directory_name": 0.0036,- "tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_with_force_include_dirs_full_path": 0.0032,- "tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_with_force_include_dirs_mixed_types": 0.0026,- "tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_find_files_with_multiple_force_include_dirs_full_paths": 0.0042,"tests/unit/pipelex/tools/misc/test_find_files_in_dir.py::TestFindFilesInDir::test_mixed_name_and_absolute_path_exclusions": 0.0813,"tests/unit/pipelex/tools/misc/test_hash_md5.py::TestHashMd5ToInt::test_hash_md5_to_int[-281949768489412648962353822266799178366]": 0.0004,"tests/unit/pipelex/tools/misc/test_hash_md5.py::TestHashMd5ToInt::test_hash_md5_to_int[hello-123957004363873451094272536567338222994]": 0.9072,@@ -14023,15 +13628,6 @@"tests/unit/pipelex/tools/typing/test_find_classes_in_module.py::TestFindClassesInModule::test_find_classes_with_builtin_types": 0.0003,"tests/unit/pipelex/tools/typing/test_find_classes_in_module.py::TestFindClassesInModule::test_find_classes_with_functions_and_variables": 0.0002,"tests/unit/pipelex/tools/typing/test_find_classes_in_module.py::TestFindClassesInModule::test_find_classes_with_nested_classes": 0.0003,- "tests/unit/pipelex/tools/typing/test_format_agent_pydantic_validation_error.py::TestFormatPydanticValidationErrorForAgent::test_context_with_non_serializable_values_is_json_safe": 0.0017,- "tests/unit/pipelex/tools/typing/test_format_agent_pydantic_validation_error.py::TestFormatPydanticValidationErrorForAgent::test_large_input_value_not_truncated": 0.0013,- "tests/unit/pipelex/tools/typing/test_format_agent_pydantic_validation_error.py::TestFormatPydanticValidationErrorForAgent::test_literal_error_with_context": 0.0007,- "tests/unit/pipelex/tools/typing/test_format_agent_pydantic_validation_error.py::TestFormatPydanticValidationErrorForAgent::test_multiple_errors_all_reported": 0.0833,- "tests/unit/pipelex/tools/typing/test_format_agent_pydantic_validation_error.py::TestFormatPydanticValidationErrorForAgent::test_non_serializable_input_falls_back_to_repr": 0.0013,- "tests/unit/pipelex/tools/typing/test_format_agent_pydantic_validation_error.py::TestFormatPydanticValidationErrorForAgent::test_structured_details[extra_field]": 0.0009,- "tests/unit/pipelex/tools/typing/test_format_agent_pydantic_validation_error.py::TestFormatPydanticValidationErrorForAgent::test_structured_details[large_input]": 0.0013,- "tests/unit/pipelex/tools/typing/test_format_agent_pydantic_validation_error.py::TestFormatPydanticValidationErrorForAgent::test_structured_details[missing_field]": 0.7431,- "tests/unit/pipelex/tools/typing/test_format_agent_pydantic_validation_error.py::TestFormatPydanticValidationErrorForAgent::test_structured_details[multiple_errors]": 0.001,"tests/unit/pipelex/tools/typing/test_format_pydantic_validation_error.py::TestFormatPydanticValidationError::test_combination_of_multiple_missing_and_extra_fields": 0.0009,"tests/unit/pipelex/tools/typing/test_format_pydantic_validation_error.py::TestFormatPydanticValidationError::test_every_error_is_rendered_beside_the_listed_kinds": 0.085,"tests/unit/pipelex/tools/typing/test_format_pydantic_validation_error.py::TestFormatPydanticValidationError::test_literal_error_multiple_fields": 0.0988,diff --git a/AGENTS.md b/AGENTS.mdindex ce312b7ca..89d9a7213 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -348,12 +348,9 @@ Use one casing per acronym (`LLMError` vs `LlmError` collide when kebab-cased in## Standards related to developing the Pipelex codebase-### Spec vs Blueprint Architecture+### Blueprints-- **Blueprints** (`pipelex/pipe_operators/`, `pipelex/pipe_controllers/`, `pipelex/pipe_machinery/`, `pipelex/mthds_parsing/`, `pipelex/core/`) are the MTHDS language reference — what `.mthds` files parse into. The base `PipeBlueprint` lives in `pipe_machinery/`, the bundle blueprint the parser produces in `mthds_parsing/`, and the concept/domain blueprints in `core/`.-- **Specs** (`pipelex/builder/pipe/`) are a convenience authoring format for AI agents. Each spec has `to_blueprint()` that transforms it into the corresponding blueprint. Spec-level fields may differ from blueprint-level fields.--When adding validation or fields, decide which layer they belong to. Language rules go on blueprints; authoring convenience goes on specs. See `pipelex/builder/CLAUDE.md` for details.+**Blueprints** (`pipelex/pipe_operators/`, `pipelex/pipe_controllers/`, `pipelex/pipe_machinery/`, `pipelex/mthds_parsing/`, `pipelex/core/`) are the MTHDS language reference — what `.mthds` files parse into. The base `PipeBlueprint` lives in `pipe_machinery/`, the bundle blueprint the parser produces in `mthds_parsing/`, and the concept/domain blueprints in `core/`. A language rule or field goes on the blueprint, since a method is written as MTHDS directly.### Main configdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2304bba2e..817e8327c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,11 @@# Changelog+## [Unreleased]++### Removed++- **The builder: `pipelex-agent concept`, `pipelex-agent pipe`, `pipelex build runner` and `pipelex.builder` (Breaking)**: the two agent commands that converted a JSON concept or pipe spec into MTHDS TOML, and `pipelex build runner bundle` and `pipelex build runner method`, which wrote a Python script running a pipe, are gone with the spec layer behind them, `ConceptSpec`, `PipeSpec`, `PipelexBundleSpec` and the `ConceptSpecError`, `PipeSpecError` and `PipelexBundleSpecBlueprintError` classes; write a method in MTHDS directly and check it with `pipelex validate`, and take a runner's typed structures from `pipelex build structures` or `pipelex codegen types --target python-structures`. The `pipelex.builder` package no longer exists: the modules the runtime still uses moved, `pipelex.builder.conventions` to `pipelex.pipeline.default_file_names`, `pipelex.builder.operations.models_ops` to `pipelex.cogt.models.model_listing` and `pipelex.builder.operations.inputs_ops` to `pipelex.pipeline.inputs_template`, and the others are deleted with the helpers only they used, `force_include_dirs` on `pipelex.tools.misc.file_utils.find_files_in_dir` among them, which only forced the builder package into library loading. The `circular_dependency_error` validation error type, which only the spec layer's pipe sorter raised, leaves the `error_type` registry and the API server's OpenAPI schema.+## [v0.72.0] - 2026-10-04### Highlightsdiff --git a/CLAUDE.md b/CLAUDE.mdindex fb5be6159..78ae86133 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -16,12 +16,9 @@## Standards related to developing the Pipelex codebase-### Spec vs Blueprint Architecture+### Blueprints-- **Blueprints** (`pipelex/pipe_operators/`, `pipelex/pipe_controllers/`, `pipelex/pipe_machinery/`, `pipelex/mthds_parsing/`, `pipelex/core/`) are the MTHDS language reference — what `.mthds` files parse into. The base `PipeBlueprint` lives in `pipe_machinery/`, the bundle blueprint the parser produces in `mthds_parsing/`, and the concept/domain blueprints in `core/`.-- **Specs** (`pipelex/builder/pipe/`) are a convenience authoring format for AI agents. Each spec has `to_blueprint()` that transforms it into the corresponding blueprint. Spec-level fields may differ from blueprint-level fields.--When adding validation or fields, decide which layer they belong to. Language rules go on blueprints; authoring convenience goes on specs. See `pipelex/builder/CLAUDE.md` for details.+**Blueprints** (`pipelex/pipe_operators/`, `pipelex/pipe_controllers/`, `pipelex/pipe_machinery/`, `pipelex/mthds_parsing/`, `pipelex/core/`) are the MTHDS language reference — what `.mthds` files parse into. The base `PipeBlueprint` lives in `pipe_machinery/`, the bundle blueprint the parser produces in `mthds_parsing/`, and the concept/domain blueprints in `core/`. A language rule or field goes on the blueprint, since a method is written as MTHDS directly.### Main configdiff --git a/api/tests/unit/test_validate_and_models_routes.py b/api/tests/unit/test_validate_and_models_routes.pyindex ce195f997..8879519b3 100644--- a/api/tests/unit/test_validate_and_models_routes.py+++ b/api/tests/unit/test_validate_and_models_routes.py@@ -4,7 +4,7 @@ import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClientfrom mthds.protocol.models import ModelCategory as MthdsModelCategory-from pipelex.builder.operations.models_ops import ModelCategory+from pipelex.cogt.models.model_listing import ModelCategoryfrom pipelex.interpreter_hub import get_library_managerfrom pytest_mock import MockerFixturediff --git a/docs/CLAUDE.md b/docs/CLAUDE.mdindex 98f015dd9..a97e6802d 100644--- a/docs/CLAUDE.md+++ b/docs/CLAUDE.md@@ -88,11 +88,6 @@ Mike (`mike deploy X.Y.Z latest`) creates two directories on gh-pages: `X.Y.Z/`- Do NOT source the root sitemap from `$(DOCS_VERSION)/` — use `latest/` so pre-release deploys don't overwrite it with pages not served at `/latest/`- Do NOT flip `ROOT_ROBOTS_TXT` to a deny-by-default `Disallow: /` policy — a `Sitemap:` directive does NOT override `Disallow`, so every root-level asset (`/sitemap.xml`, `/llms.txt`, ...) would silently drop from crawl unless individually `Allow`ed. The shipped policy is allow-by-default with targeted disallows for versioned and non-content paths-## Spec vs Blueprint in Documentation+## Blueprints in Documentation-The `docs/building-methods/` section documents the MTHDS language — what users write in `.mthds` files. This corresponds to the **blueprint** layer, NOT the spec layer.--- **Blueprints** define the MTHDS language — what `.mthds` files parse into via `MthdsParser`.-- **Specs** (in `pipelex/builder/pipe/`) are a simplified authoring format for AI agents with convenience fields that get transformed into blueprint fields via `to_blueprint()`. Specs are NOT the language definition.--Documentation under `docs/building-methods/` must describe blueprint-level fields, not spec-level convenience fields. For example, `PipeComposeSpec.target_format` is a spec convenience — the MTHDS language uses `category` + `templating_style` on the `TemplateBlueprint` instead.+The `docs/building-methods/` section documents the MTHDS language — what users write in `.mthds` files and what those files parse into via `MthdsParser`, the **blueprint** layer. Documentation under `docs/building-methods/` describes blueprint-level fields only.diff --git a/docs/api-server/openapi/pipelex-api.openapi.yaml b/docs/api-server/openapi/pipelex-api.openapi.yamlindex 6d4ef0caf..140447519 100644--- a/docs/api-server/openapi/pipelex-api.openapi.yaml+++ b/docs/api-server/openapi/pipelex-api.openapi.yaml@@ -5509,7 +5509,6 @@ components:- input_stuff_spec_mismatch- inadequate_output_concept- inadequate_output_multiplicity- - circular_dependency_error- llm_output_cannot_be_image- invalid_pipe_code_syntax- unknown_pipe_typediff --git a/docs/api-server/pipe-builder.md b/docs/api-server/pipe-builder.mdindex 50f44e414..c2243600a 100644--- a/docs/api-server/pipe-builder.md+++ b/docs/api-server/pipe-builder.md@@ -1,10 +1,10 @@# Pipe Builder (`/v1/build/*`) — REMOVED-**The five build routes are gone from this server**: `POST /v1/build/inputs`, `POST /v1/build/output`, `POST /v1/build/runner`, `POST /v1/build/concept` and `POST /v1/build/pipe-spec` now answer `404`. Nothing in the runtime changed; only the HTTP routes were removed.+**The five build routes are gone from this server**: `POST /v1/build/inputs`, `POST /v1/build/output`, `POST /v1/build/runner`, `POST /v1/build/concept` and `POST /v1/build/pipe-spec` now answer `404`. The runtime code that only these routes and their local twins used went after them: the concept and pipe specs, `pipelex-agent concept`, `pipelex-agent pipe` and `pipelex build runner`.## What replaces each one- **An inputs template (`/v1/build/inputs`)** is projected by the client from the input form that [`POST /v1/pipe-io`](pipe-io.md) returns, with the `mthds` packages' projection: `renderInputsTemplate` from `mthds/protocol`, which `@pipelex/sdk` re-exports, or `mthds.protocol.inputs_template` in Python. `mthds-agent inputs` does exactly that. `pipelex build inputs` still writes the engine's own rendering locally, the template the removed route returned, which differs from the client projection where the [projection fixture corpus](../contribute/generate-projection-corpus.md) records.- **A pipe's declared output (`/v1/build/output`)** is described by the `output_form` and the pipe I/O contract that [`POST /v1/pipe-io`](pipe-io.md) returns. The rendered output example has no HTTP replacement; `pipelex build output` renders it locally.-- **The typed structures a runner script imported (`/v1/build/runner`)** are the `python-structures` target of [`POST /v1/codegen`](codegen.md). The runner script itself has no HTTP replacement.+- **The typed structures a runner script imported (`/v1/build/runner`)** are the `python-structures` target of [`POST /v1/codegen`](codegen.md). The runner script itself has no replacement: [Build Runner](../tools/cli/build/runner.md) says how to write one.- **The concept and pipe spec conversions (`/v1/build/concept`, `/v1/build/pipe-spec`)** have no replacement: a method is written as MTHDS directly and checked with [`POST /v1/validate`](pipe-validate.md).diff --git a/docs/building-methods/pipes/understanding-optionality.md b/docs/building-methods/pipes/understanding-optionality.mdindex 312b4eedd..f8ac1b1b6 100644--- a/docs/building-methods/pipes/understanding-optionality.md+++ b/docs/building-methods/pipes/understanding-optionality.md@@ -104,7 +104,7 @@ You never discover an unhandled absence at run time. Validation walks every contTwo more facts surface on the **valid** report (`pipelex validate`, the agent CLI, and the API) — the first about optionality, the second a mixed bag of advisories that the same report carries:- **`liftable_pipes`** — every pipe that may be silently skipped at run time, with the slots whose absence triggers the skip and where that absence can come from. Implicit lifting is acceptable *because* it is visible at build time.-- **`warnings`** — advisory lints that never flip the verdict, spanning optionality and the intent-hint vocabulary alike. Every whole-bundle validate channel carries the same set — the protocol report, the agent CLI, the builder's per-bundle operations, and the bare CLI's `validate bundle` and `validate --all`. (`pipelex validate <PIPE_CODE>` makes no bundle-wide claim and prints none of them; neither does the builder's `validate_all`, which carries no `warnings` key at all.)+- **`warnings`** — advisory lints that never flip the verdict, spanning optionality and the intent-hint vocabulary alike. Every whole-bundle validate channel carries the same set — the protocol report, the agent CLI, and the bare CLI's `validate bundle` and `validate --all`. (`pipelex validate <PIPE_CODE>` makes no bundle-wide claim and prints none of them.)- `optional_force_redundant` — a `!` whose slot is guaranteed present in every analyzed flow, so the assertion can never fire and the marker is dead weight.- `input_presence_vacuous` — a **method input** (an input of the bundle's declared `main_pipe`) that must be supplied, but whose concept declares no required field. The empty object satisfies it, so the declaration enforces nothing and a caller cannot tell what to fill in. Either mark the input `?`, or give the concept a required field. See [Inline Structures](../concepts/inline-structures.md#all-optional-structures-and-the-input_presence_vacuous-lint).diff --git a/docs/contribute/hub-layering.md b/docs/contribute/hub-layering.mdindex 77b6f3cec..1f492a978 100644--- a/docs/contribute/hub-layering.md+++ b/docs/contribute/hub-layering.md@@ -82,7 +82,7 @@ Not everything a hub module exports is an accessor. `resolve_run_mode_for_boot`## Why the boundary exists-`runtime_hub` must not name anything from `libraries`, `pipe_operators`, `pipe_controllers`, `codegen`, `builder`, `interpreter_plugins`, `pipe_machinery`, `pipe_signature`, `mthds_parsing`, `pipeline` or `pipe_run` at module level. That list is now stated in whole top-level packages, which is the point of the modularity moves: it used to have to trail "…or the Pipe-touching modules of `core.pipes`", because some of what it forbids lived under a runtime-named package. Those module-level imports exist only to type the getters, but they are what made a single hub drag the entire method interpreter into every consumer that just wanted `get_console()`.+`runtime_hub` must not name anything from `libraries`, `pipe_operators`, `pipe_controllers`, `codegen`, `interpreter_plugins`, `pipe_machinery`, `pipe_signature`, `mthds_parsing`, `pipeline` or `pipe_run` at module level. That list is now stated in whole top-level packages, which is the point of the modularity moves: it used to have to trail "…or the Pipe-touching modules of `core.pipes`", because some of what it forbids lived under a runtime-named package. Those module-level imports exist only to type the getters, but they are what made a single hub drag the entire method interpreter into every consumer that just wanted `get_console()`.The property that matters is measurable: **importing the Pipelex kernel layer loads zero modules from any of the packages named above.** That is both the assertion the closure test pins and the outward-facing claim — the inference engine does not know the MTHDS language exists, so you can embed it without loading a line of the parser, the pipe machinery, or a single pipe kind. Verify it from the repo root on a synced venv:@@ -93,7 +93,7 @@ from pathlib import Pathimport pipelex.cogt.content_generation.content_generator # noqa: F401-INTERPRETER = {"libraries", "pipe_operators", "pipe_controllers", "codegen", "builder", "interpreter_plugins", "pipe_machinery", "pipe_signature", "mthds_parsing", "pipeline", "pipe_run"}+INTERPRETER = {"libraries", "pipe_operators", "pipe_controllers", "codegen", "interpreter_plugins", "pipe_machinery", "pipe_signature", "mthds_parsing", "pipeline", "pipe_run"}loaded = {name: mod for name, mod in sys.modules.items() if name.startswith("pipelex.")}interpreter = sorted(n for n in loaded if n.split(".")[1] in INTERPRETER)sloc = 0@@ -136,7 +136,7 @@ Be precise about what that buys, because it is easy to overstate. The read is stTwo shapes fall out of that, and they are the ones to copy:- **Compatibility is two tiers, composed by the thing that owns resolution.** `Concept.are_compatible_by_declaration` is pure over the model's fields (plus an injected `concept_resolver`): dynamic short-circuits, ref equality, declared-class-name equality, `refines` chains. `ConceptLibrary.is_compatible` asks that first and only resolves classes when it is inconclusive. A name that should have resolved and didn't now raises `ConceptStructureClassNotFoundError` instead of answering `False` — "unknown" and "incompatible" are different answers, and conflating them was a latent wrong-verdict bug. The class tier's equivalence test (`are_classes_equivalent`) compares JSON schemas, which is the expensive part of loading a library, so it first settles the answers that need no schema: a class is equivalent to itself, and two *plain* models with different field names are not equivalent. A plain model is built only from an allow-list — scalar, `Any`, `Literal`, union and builtin-container annotations, inert constraints such as `gt` or `strict`, defaults made of plain values (a time-zone-aware `datetime` or `time` only in the standard library's `datetime.timezone`), no alias, no schema hook or schema-shaping setting, and nested models that are plain in turn — and for such a model the properties pydantic publishes provably equal its field names. Any other pair, including two plain models with the same field names, goes to the full comparison, so the shortcut only ever answers where the schemas would say `False`, and a schema that cannot be generated still raises. It is an allow-list rather than a list of the ways pydantic can drop a property because those ways keep multiplying (a type alias to `SkipJsonSchema`, a nested model's title generator or typed extras, a default whose own type has a schema hook, a default whose custom time zone raises when asked for its offset), and a deny-list that misses one answers `False` for two classes whose schemas are identical. In practice the structure classes generated from a concept's `structure` table and the native content classes are plain, so library validation's question of whether a pipe's output is an image needs no schema for them; `CompositeContent`, which allows extra fields, is the notable exception.-- **Rendering takes the resolved class, not the name.** `Concept.render_concept_representation` receives a `structure_class`; `StuffSpec.render_stuff_spec` takes the `concept_provider`, resolves once, and passes the class down. Interpreter-layer callers (`output_renderer`, `input_renderer`, `pipe_io_contracts`, `builder/runner_code`) supply `get_concept_library()`.+- **Rendering takes the resolved class, not the name.** `Concept.render_concept_representation` receives a `structure_class`; `StuffSpec.render_stuff_spec` takes the `concept_provider`, resolves once, and passes the class down. Interpreter-layer callers (`output_renderer`, `input_renderer`, `pipe_io_contracts`) supply `get_concept_library()`.The **write side** stays ambient on purpose: `concept_factory` and `structure_generation/generator.py` generate structure classes and register them at library-load time, which is genuinely the registry's business. That those two are the only modules under `pipelex/core/concepts/` touching the registry is pinned as a golden set by `tests/unit/pipelex/core/concepts/test_concept_registry_boundary.py` — nothing else can see it, since both the accessor and its users are kernel-layer.diff --git a/docs/contribute/inference-family-surface.md b/docs/contribute/inference-family-surface.mdindex 30f1b1a25..b8d99935e 100644--- a/docs/contribute/inference-family-surface.md+++ b/docs/contribute/inference-family-surface.md@@ -12,7 +12,7 @@ Most of the list is enforced by the type checker: the matches over the family en1. **The family's package**, `pipelex/cogt/<family>/`, mirroring `pipelex/cogt/search/`: the question/request and answer models, the setting and its model-choice union, the job, the job factory, the usage report, the worker contract (`<Family>WorkerAbstract` with one template method and one abstract hook) and the worker factory, which resolves its worker through the inference-backend registry and holds no `match` over SDK strings.-2. **The family enums, together.** `InferenceFamily` in `pipelex/plugins/inference_backend_registry.py`, `ModelType` in `pipelex/cogt/model_backends/model_type.py`, `InferenceErrorFamily` in `pipelex/cogt/inference/error_render.py` with an entry in both its failure-class and not-found-class tables, and `ModelCategory` in `pipelex/builder/operations/models_ops.py`, which is what `pipelex-agent models` and `check-model` list from.+2. **The family enums, together.** `InferenceFamily` in `pipelex/plugins/inference_backend_registry.py`, `ModelType` in `pipelex/cogt/model_backends/model_type.py`, `InferenceErrorFamily` in `pipelex/cogt/inference/error_render.py` with an entry in both its failure-class and not-found-class tables, and `ModelCategory` in `pipelex/cogt/models/model_listing.py`, which is what `pipelex-agent models` and `check-model` list from.3. **The error classes** in `pipelex/cogt/exceptions.py`: a job failure, a model-not-found (subclassing `ModelNotFoundError`) and a handle-not-found. Then regenerate the error pages and the identity snapshot (`make gep`, `make gei`); the snapshot test fails until you do.@@ -30,7 +30,7 @@ Most of the list is enforced by the type checker: the matches over the family en10. **Silent: fakes that stand in for the deck.** Any test double that impersonates `ModelDeck` by attribute — the fake deck in `tests/unit/pipelex/cli/test_agent_models_cmd.py` is one — needs the new family's presets, aliases and waterfalls, or every case using it fails with an `AttributeError` far from the cause.-11. **The MTHDS protocol's model categories.** `PipelexMTHDSProtocol.models()` in `pipelex/pipeline/runner.py` types each preset by the protocol's own `ModelCategory`, which carries every family this runtime serves, `judgment` included, through two exhaustive matches beside it: `_protocol_category_of` for the deck's entries and `_builder_category_of` for the `?type=` filter. A new member of the builder's `ModelCategory` (step 2) stops the type checker at the first of them, because a new family needs a protocol category too, which the standard adds in a protocol minor for each settings family it adds. Until the protocol defines one, the family's presets go under an extension property `PipelexModelDeck` adds for them, never under a category the protocol does not define, since a runner must not put such a value in a deck entry's `type`.+11. **The MTHDS protocol's model categories.** `PipelexMTHDSProtocol.models()` in `pipelex/pipeline/runner.py` types each preset by the protocol's own `ModelCategory`, which carries every family this runtime serves, `judgment` included, through two exhaustive matches beside it: `_protocol_category_of` for the deck's entries and `_listing_category_of` for the `?type=` filter. A new member of the model listing's `ModelCategory` (step 2) stops the type checker at the first of them, because a new family needs a protocol category too, which the standard adds in a protocol minor for each settings family it adds. Until the protocol defines one, the family's presets go under an extension property `PipelexModelDeck` adds for them, never under a category the protocol does not define, since a runner must not put such a value in a deck entry's `type`.12. **Files, when the family reads them.** The job and the assignment carry them keyed by input name, as `JudgmentJob` and `JudgmentAssignment` carry `images` and `documents`, and the assignment's `referenced_uris()` returns each one, or a scoped run's read authorization never sees them. The worker's template method checks that the model reads them before its hook runs, raising the family's capability error (`JudgmentWorkerAbstract._check_can_read_files`), and runs the per-file format checks in `pipelex/cogt/inference/prompt_file_checks.py`, which the LLM family shares. What a model reads is the `inputs` of its spec in the backend's model file, so the capability is configuration, and an operator that knows its model at load time refuses a file input there too, as `PipeJudge` does.diff --git a/docs/contribute/keyword-only-arguments.md b/docs/contribute/keyword-only-arguments.mdindex 45dd1e7ff..1a48db82e 100644--- a/docs/contribute/keyword-only-arguments.md+++ b/docs/contribute/keyword-only-arguments.md@@ -49,7 +49,7 @@ The command validates the def (it must exist, be inspected by the guard, and havA subject grant is warranted when EITHER:-- **Verb–object test:** the function name is a verb (phrase) and the param is its direct object — the call reads as a sentence (`render(node)`, `validate_bundle(bundle)`, `parse_concept_spec(spec_data)`) — AND it is the **single candidate** (if you hesitate between two params, neither is the subject) — AND typical call sites pass a **self-labelling expression**, never a bare literal (literal-typed subjects are banned outright anyway);+- **Verb–object test:** the function name is a verb (phrase) and the param is its direct object — the call reads as a sentence (`render(node)`, `validate_bundle(bundle)`) — AND it is the **single candidate** (if you hesitate between two params, neither is the subject) — AND typical call sites pass a **self-labelling expression**, never a bare literal (literal-typed subjects are banned outright anyway);- OR the def must satisfy a **positional `Callable` protocol** (it is passed as a value to something that calls it positionally) and a grant keeps it compliant without reaching for the heavier `# kw-only: ignore`.When in doubt → keyword-only. The grant is the exception tier; all-keyword is always compliant and often more readable. Rationales must be def-specific but may be terse for obvious keeps ("verb–object; single operand") — the value is that someone actually looked; copy-paste boilerplate across dozens of entries defeats the point.@@ -139,8 +139,8 @@ A `# kw-only: ignore` comment on the `def` line (or the `async def` line) suppreA subject plus options — the canonical shape, legal only with a grant:```python-# subject_grants.toml carries: ["pipelex/builder/build.py::build_pipe"] param = "spec" rationale = "…"-def build_pipe(spec, *, dry_run, retries, validate): ... # build_pipe(my_spec, dry_run=True, retries=3, validate=False)+# subject_grants.toml carries: ["pipelex/pipeline/publish.py::publish_bundle"] param = "bundle" rationale = "…"+def publish_bundle(bundle, *, dry_run, retries, validate): ... # publish_bundle(my_bundle, dry_run=True, retries=3, validate=False)```A single subject and nothing else — needs a grant too (strict-all scope; lone-subject defs are not implicitly exempt):diff --git a/docs/contribute/mthds-test-corpus.md b/docs/contribute/mthds-test-corpus.mdindex a5116f88c..bf1ce7356 100644--- a/docs/contribute/mthds-test-corpus.md+++ b/docs/contribute/mthds-test-corpus.md@@ -90,9 +90,9 @@ An **exclusion** marks a registry code that no standalone focused entry could meNo native concept is excluded — every one of them turned out to support a real entry. `PipeFunc` is excluded: it names a Python function that the runtime resolves against its function registry *at validation time*, so an entry declaring one fails with `Function '<name>' not found in registry` in every consumer that has not registered that exact function — and a cross-language consumer cannot register a Python function at all. Exercise `PipeFunc` in a consumer's own fixtures, where the function exists.-`error.*` carries the rest of the exclusions, and the distinction they turn on is worth stating: **membership in the registry means a value is reachable on the wire, never that a focused entry can produce it.** A corpus entry is a `.mthds` bundle validated through `validate bundle`, so a fault the validate path cannot reach is excluded here rather than pruned from the runtime's own truth. Two are unreachable by construction — `circular_dependency_error` is raised only by the pipe sorter, which runs on the builder's spec-to-blueprint conversion and never on a parsed `.mthds` file, and `unknown_concept` fires in the pipe factory under exactly the condition the earlier concept-reference resolution has already rejected as `unresolved_concept`. Several have no shape an entry could take: the advisory-only codes — `optional_force_redundant`, `input_presence_vacuous`, and the three `hint_*` lints — ride the validation report's `warnings` array and never make a verdict invalid, so the bundle they fire on is valid and has no `expected_error` to carry, and the manifest models no warnings axis. The two `unknown_*` fallbacks are excluded because an entry pinning one would be pinning the absence of a diagnosis, and would have to be rewritten the moment the fault got a code of its own.+`error.*` carries the rest of the exclusions, and the distinction they turn on is worth stating: **membership in the registry means a value is reachable on the wire, never that a focused entry can produce it.** A corpus entry is a `.mthds` bundle validated through `validate bundle`, so a fault the validate path cannot reach is excluded here rather than pruned from the runtime's own truth. One is unreachable by construction: `unknown_concept` fires in the pipe factory under exactly the condition the earlier concept-reference resolution has already rejected as `unresolved_concept`. Several have no shape an entry could take: the advisory-only codes — `optional_force_redundant`, `input_presence_vacuous`, and the three `hint_*` lints — ride the validation report's `warnings` array and never make a verdict invalid, so the bundle they fire on is valid and has no `expected_error` to carry, and the manifest models no warnings axis. The two `unknown_*` fallbacks are excluded because an entry pinning one would be pinning the absence of a diagnosis, and would have to be rewritten the moment the fault got a code of its own.-**Measure an exclusion, do not reason your way to one.** Every `error.*` exclusion reason above was established by writing the bundle that ought to trigger it and reading what the runtime actually said — which is how the first two turned out to be shadowed rather than merely awkward, and how the two the registry made look unreachable (`missing_pipe_type`, `native_concept_redeclaration`) turned out to have entries after all.+**Measure an exclusion, do not reason your way to one.** Every `error.*` exclusion reason above was established by writing the bundle that ought to trigger it and reading what the runtime actually said — which is how `unknown_concept` turned out to be shadowed rather than merely awkward, and how the two the registry made look unreachable (`missing_pipe_type`, `native_concept_redeclaration`) turned out to have entries after all.### `fails_at` — which layer catches a fault firstdiff --git a/docs/contribute/registration-surface.md b/docs/contribute/registration-surface.mdindex ac48fd4ab..069b39933 100644--- a/docs/contribute/registration-surface.md+++ b/docs/contribute/registration-surface.md@@ -16,7 +16,7 @@ Each kind lives in its own package under `pipelex/pipe_operators/<kind>/` or `pi| `pipe_foo.py` | `PipeFoo` | the runnable pipe || `pipe_foo_factory.py` | `PipeFooFactory` | blueprint → pipe |-`PipeSignature` follows the same shape from `pipelex/pipe_signature/`, with the caveat noted below.+`PipeSignature` follows the same shape from `pipelex/pipe_signature/`, except that a signature is not an executable kind: it has no `PipeType` member and no `PipeCategory`, and its `type` tag is the internal `PIPE_SIGNATURE_TYPE_TAG` of `pipelex/pipe_machinery/pipe_blueprint.py`.## The checklist@@ -28,8 +28,6 @@ Each kind lives in its own package under `pipelex/pipe_operators/<kind>/` or `pi4. **The registration manifest** — add `PipeFoo` and `PipeFooFactory` to `PipeRegistryModels` in `pipelex/pipe_machinery/registry_models.py`, in `PIPE_OPERATORS` / `PIPE_OPERATORS_FACTORY` or `PIPE_CONTROLLERS` / `PIPE_CONTROLLERS_FACTORY`. This is the one whose omission is **silent**: boot succeeds either way, and the failure surfaces later as a kajson deserialization error on a pipe. `tests/unit/pipelex/test_registry_models_split.py` pins the manifests against the class registry for exactly that reason.-5. **The spec layer** — add `PipeFooSpec` under `pipelex/builder/pipe/`, then register it in **both** `pipe_spec_map.py` (`pipe_type_to_spec_class`, the authoring lookup) and `pipe_spec_union.py` (`PipeSpecUnion`, the discriminated union). The two are separate on purpose: the union carries `PipeSignatureSpec`, the map does not, because a signature is not a user-selectable type.-## Why `core/` no longer holds the manifest`PipeRegistryModels` used to live in `pipelex/core/registry_models.py` alongside core's value model. Importing it loads every pipe operator, every pipe controller and their factories — so a module filed under `core/` pulled in the whole interpreter, and `core` read as a dependant of the pipe packages it is supposed to sit below. The manifest now lives in `pipelex/pipe_machinery/`; `core.registry_models` keeps `CoreRegistryModels` (the stuff-content classes) and imports nothing from `pipe_operators` / `pipe_controllers` / `pipe_signature`.@@ -37,12 +35,3 @@ Each kind lives in its own package under `pipelex/pipe_operators/<kind>/` or `piThe two manifests land in one registry from the two halves of the boot: `CoreRegistryModels` is registered by `RuntimeBoot.setup` in `pipelex/runtime_boot.py`, `PipeRegistryModels` by `Pipelex.setup` in `pipelex/pipelex.py` — see [Where the boot splits](hub-layering.md#where-the-boot-splits). They must stay **disjoint** — a class in both is a sign one half was edited without the other — and because registration is name-keyed dict insertion, which side registers first carries no meaning.See [Hub Layering](hub-layering.md) for the layer boundary this split serves.--## The spec/blueprint parallel is deliberate--Steps 3 and 5 look like the same list written twice. They are not, and collapsing them would be a mistake:--- **Blueprints are the MTHDS language.** `PipeFooBlueprint` defines what an author may write in a `.mthds` file. It is the reference for the standard.-- **Specs are an authoring convenience for AI agents.** `PipeFooSpec` is a simplified shape with convenience fields that `to_blueprint()` transforms into blueprint fields. Spec-level fields deliberately differ from blueprint-level ones — `PipeComposeSpec.target_format` is a spec convenience with no blueprint counterpart, for instance.--The two layers evolve for different reasons and answer to different consumers, so they carry their own unions. When adding validation or a field, decide which layer owns it first: language rules go on blueprints, authoring convenience goes on specs. `pipelex/builder/CLAUDE.md` is the canonical statement of that split.diff --git a/docs/contribute/rich-imports.md b/docs/contribute/rich-imports.mdindex da8cdaf40..dd205e451 100644--- a/docs/contribute/rich-imports.md+++ b/docs/contribute/rich-imports.md@@ -57,7 +57,7 @@ class TextContent(StuffContent):return Markdown(self.text)```-- **`require_rich_for_rendering()`** (`pipelex.tools.misc.pretty`) is the check for a rendering: the `rendered_pretty` methods of the content types and the builder specs, and the `rich` pretty-print mode. Its message points at the Rich-free pretty-print modes as well as at the extra.+- **`require_rich_for_rendering()`** (`pipelex.tools.misc.pretty`) is the check for a rendering: the `rendered_pretty` methods of the content types, and the `rich` pretty-print mode. Its message points at the Rich-free pretty-print modes as well as at the extra.- **`require_rich(message=...)`** (`pipelex.tools.misc.rich_extra`) is the check for anything else, with a message saying what needed Rich: the `console` log sink uses it, and so does `get_console()`.- **`is_rich_installed()`**, in the same module, answers without raising, for a caller that has a Rich-free fallback. The stuff viewer page uses it, and shows the JSON rendering in its Pretty tab when Rich is absent.- **A type-only import goes under `if TYPE_CHECKING:`.** In a module with `from __future__ import annotations`, the annotation can stay unquoted; in a pydantic model module without it, quote the annotation, as `"PrettyPrintable"` is quoted above, since pydantic resolves annotations at class creation.diff --git a/docs/errors/authoring-and-language.md b/docs/errors/authoring-and-language.mdindex 5acc692d3..374ea7117 100644--- a/docs/errors/authoring-and-language.md+++ b/docs/errors/authoring-and-language.md@@ -106,12 +106,6 @@ own page. Classes are grouped by subsystem.- [`PipeSignatureNotExecutableError`](pipe-signature-not-executable-error.md) — Pipe signature not executable-## Builder--- [`ConceptSpecError`](concept-spec-error.md) — Concept spec-- [`PipeSpecError`](pipe-spec-error.md) — Pipe spec-- [`PipelexBundleSpecBlueprintError`](pipelex-bundle-spec-blueprint-error.md) — Pipelex bundle spec blueprint-## Libraries- [`ConceptLibraryError`](concept-library-error.md) — Concept librarydiff --git a/docs/errors/concept-spec-error.md b/docs/errors/concept-spec-error.mdindex 90ffe6e8a..604a554d7 100644--- a/docs/errors/concept-spec-error.md+++ b/docs/errors/concept-spec-error.md@@ -1,21 +1,14 @@----title: "Concept spec"-description: "Reference for the `ConceptSpecError` Pipelex error class."+title: "Concept spec (removed)"+description: "The `ConceptSpecError` Pipelex error class no longer exists."----<!-- pipelex:generated -->+<!-- pipelex:authored -->-# Concept spec+# Concept spec (removed)-Raised when a concept spec is malformed against its authoring contract.+**`ConceptSpecError` is no longer raised.** It reported a malformed concept spec, the JSON authoring format that `pipelex-agent concept` and the `POST /v1/build/concept` route converted into MTHDS TOML. The command, the route and the concept spec are all gone: a concept is written in MTHDS directly, in a `[concept.<Code>]` section, and checked with `pipelex validate bundle` or [`POST /v1/validate`](../api-server/pipe-validate.md).-| Field | Value |-|---|---|-| `error_type` | `ConceptSpecError` |-| `title` | Concept spec |-| `type_uri` | `https://docs.pipelex.com/latest/errors/concept-spec-error/` |-| `error_domain` | `input` |-| Defined in | `pipelex.builder.concept.exceptions` |-| Parent class | [`PipelexError`](pipelex-error.md) |+This page stays at the URL the error's `type_uri` published, so a link recorded from an earlier response still resolves.[Back to Error Reference](index.md)diff --git a/docs/errors/index.md b/docs/errors/index.mdindex c374a7807..4e88f6eb0 100644--- a/docs/errors/index.md+++ b/docs/errors/index.md@@ -15,7 +15,7 @@ Every Pipelex error class has a stable RFC 7807 `type` URI on the formThe classes are grouped into a few macro areas — pick the one that matches wherethe error came from:-- [Authoring & language](authoring-and-language.md) — MTHDS parsing, Core language, Pipe operators, Pipe controllers, Pipe signatures, Builder, Libraries.+- [Authoring & language](authoring-and-language.md) — MTHDS parsing, Core language, Pipe operators, Pipe controllers, Pipe signatures, Libraries.- [Execution & runtime](execution-and-runtime.md) — Pipe execution, Pipeline execution, Runtime bridge, Graph, Tracing.- [Inference & providers](inference-and-providers.md) — Inference (Cogt), Provider adapters, Plugin system.- [Platform & tooling](platform-and-tooling.md) — Base & root errors, Tools, Kit, System & configuration, CLI, Codegen, Methods, Migration.diff --git a/docs/errors/pipe-spec-error.md b/docs/errors/pipe-spec-error.mdindex 5a10fa739..5d3039009 100644--- a/docs/errors/pipe-spec-error.md+++ b/docs/errors/pipe-spec-error.md@@ -1,21 +1,14 @@----title: "Pipe spec"-description: "Reference for the `PipeSpecError` Pipelex error class."+title: "Pipe spec (removed)"+description: "The `PipeSpecError` Pipelex error class no longer exists."----<!-- pipelex:generated -->+<!-- pipelex:authored -->-# Pipe spec+# Pipe spec (removed)-Raised when a pipe spec is malformed against its authoring contract.+**`PipeSpecError` is no longer raised.** It reported a malformed pipe spec, the JSON authoring format that `pipelex-agent pipe` and the `POST /v1/build/pipe-spec` route converted into MTHDS TOML. The command, the route and the pipe spec are all gone: a pipe is written in MTHDS directly, in a `[pipe.<code>]` section, and checked with `pipelex validate bundle` or [`POST /v1/validate`](../api-server/pipe-validate.md).-| Field | Value |-|---|---|-| `error_type` | `PipeSpecError` |-| `title` | Pipe spec |-| `type_uri` | `https://docs.pipelex.com/latest/errors/pipe-spec-error/` |-| `error_domain` | `input` |-| Defined in | `pipelex.builder.pipe.exceptions` |-| Parent class | [`PipelexError`](pipelex-error.md) |+This page stays at the URL the error's `type_uri` published, so a link recorded from an earlier response still resolves.[Back to Error Reference](index.md)diff --git a/docs/errors/pipelex-bundle-spec-blueprint-error.md b/docs/errors/pipelex-bundle-spec-blueprint-error.mddeleted file mode 100644index c91352638..000000000--- a/docs/errors/pipelex-bundle-spec-blueprint-error.md+++ /dev/null@@ -1,19 +0,0 @@-----title: "Pipelex bundle spec blueprint"-description: "Reference for the `PipelexBundleSpecBlueprintError` Pipelex error class."------<!-- pipelex:generated -->--# Pipelex bundle spec blueprint--| Field | Value |-|---|---|-| `error_type` | `PipelexBundleSpecBlueprintError` |-| `title` | Pipelex bundle spec blueprint |-| `type_uri` | `https://docs.pipelex.com/latest/errors/pipelex-bundle-spec-blueprint-error/` |-| `error_domain` | _(inherited from parent)_ |-| Defined in | `pipelex.builder.exceptions` |-| Parent class | [`PipelexError`](pipelex-error.md) |--[Back to Error Reference](index.md)diff --git a/docs/features/cli.md b/docs/features/cli.mdindex 9b6840137..6275e32ae 100644--- a/docs/features/cli.md+++ b/docs/features/cli.md@@ -19,7 +19,7 @@ The `pipelex` CLI is the primary tool for working with Pipelex methods. It cover| **`pipelex init`** | Initialize configuration, backends, credentials, routing, and telemetry || **`pipelex update`** | Refresh the model deck and `backends/internal.toml` to match the installed pipelex version || **`pipelex doctor`** | Check configuration health and suggest fixes |-| **`pipelex build`** | AI-powered method generation from natural language requirements |+| **`pipelex build`** | Generate the structures of your concepts and example inputs and outputs for a pipe || **`pipelex validate`** | Check pipeline syntax, structure, and run dry-run validation || **`pipelex fix`** | Apply deterministic safe fixes to a bundle and re-validate (with `--diff` preview) || **`pipelex run`** | Execute pipelines from bundle files or libraries |@@ -54,8 +54,6 @@ The `pipelex-agent` CLI is a machine-first interface designed for automated envi| `fmt` | Format `.mthds`, `.toml`, or `.plx` files in-place || `lint` | Lint files for errors || `inputs` | Generate example input JSON for a pipe |-| `concept` | Convert a JSON concept spec into raw TOML (stdout) |-| `pipe` | Convert a JSON pipe spec into raw TOML (stdout) || `models` | List available model presets, aliases, and waterfalls (`--format markdown\|json` success, default: markdown; `--error-format` for errors, defaults to `--format`'s value) || `doctor` | Check configuration health (`--format markdown\|json` success, default: markdown; `--error-format` for errors, defaults to `--format`'s value) |diff --git a/docs/tools/cli/agent-cli.md b/docs/tools/cli/agent-cli.mdindex fc805d8de..3c5796d79 100644--- a/docs/tools/cli/agent-cli.md+++ b/docs/tools/cli/agent-cli.md@@ -85,7 +85,7 @@ For `bundle`, additional options are available:A refusal of your input raised while the bundle is loaded or validated is answered with the invalid-verdict envelope — `is_valid: false` and a `validation_errors` array — and exit code `1`, never the no-verdict envelope and exit code `2`, which is kept for failures of the tool or its environment. A pipe whose dry run fails gives one `dry_run` item per failing pipe, with `error_type: DryRunError`, the `pipe_code`, `domain_code` and `source` of the innermost pipe that failed and is not allowed to fail (its `source` whenever the pipe is in your files; a validator of submitted content beside a host's library directories names only that content's files), and a message that keeps the failure's own text only when it is caller-facing, on `validate bundle`, `validate pipe <code>` and `validate pipe --all` alike; a controller that failed because a pipe it runs failed is reported once, at that pipe. Every error found while parsing is its own item, so a misspelled field is reported beside the categorized errors as an item without an `error_type`, carrying its `pipe_code`, `source` and `field_path`. A TOML syntax error's item carries its 1-based `line` and `column`, and an `unresolved_concept` item lists the concepts the validated bundle declares in its domain in `declared_concepts`. A pipe naming a model the model deck does not define gives one `pipe_validation` item with `error_type: unknown_model`, carrying `pipe_code`, `domain_code`, `source`, `field_path` (`pipe.<code>.model`), `model_reference` (the reference as written), `model_type` and `suggestions` (the deck's close matches), plus a `rename-model` `suggested_fix` when there is exactly one suggestion. That fix's `safety` is `unsafe`, because a close name can still be a different model: `fix bundle` never applies it, and the Markdown labels it `💡 Suggested fix (unsafe, confirm before applying):` where a safe fix reads `💡 Suggested fix:`. Any other refusal of your input with no code of its own gives one item without an `error_type`, located on its pipe when it was raised while that pipe was built. A pipe factory's refusal, such as a `PipeExtract` whose input is neither an image nor a document, is one of these items, located on its pipe. See [Error Model](../../under-the-hood/error-model.md#validation_errors-structured-bundle-validation-diagnostics).!!! note "Advisory warnings on validate"- Whole-bundle and whole-library validate surfaces (`validate bundle`, `validate method`, `validate pipe --all`) also carry a `warnings` array — advisory optionality lints on a VALID bundle that never flip the verdict or the exit code. Each entry has the **same shape as a validation error item** (`category`, `error_type`, `pipe_code`, `domain_code`, `variable_names`, `message`) — this is a different shape from the `init`/`doctor` setup `warnings` (`{type, message}`) documented under Output Contract below. Three families ride the array, always in this order: the useless-`!` lint (`optional_force_redundant`), a `!` (force) input whose slot is guaranteed present in every analyzed flow, so the assertion can never fire; the vacuous-presence lint (`input_presence_vacuous`), an entry-pipe input that must be supplied but whose concept declares no required field, so the empty object satisfies it and a caller cannot tell what to fill in (see [Understanding Optionality](../../building-methods/pipes/understanding-optionality.md)); and the [intent-hint](../../building-methods/concepts/intent-hints.md) lints (`hint_unknown_key`, `hint_unknown_intent`, `hint_inapplicable_intent`). Every whole-bundle validate channel — this CLI, the bare CLI, the builder ops and the protocol validation report — assembles them from one composition point, so which advisories you see does not depend on which command you typed. Hint findings are bounded per site: a site naming many undefined keys reports the first few and then how many more there were, and a long authored key or value is elided in the message. In markdown, warnings render as a "Warnings" section. The array is empty when there is nothing to report; `validate pipe` omits it (no flow context to lint in). `validate bundle`/`validate method` with `--pipe` keep it, and it stays bundle-wide there — the slice narrows the dry run, not the validation.+ Whole-bundle and whole-library validate surfaces (`validate bundle`, `validate method`, `validate pipe --all`) also carry a `warnings` array — advisory optionality lints on a VALID bundle that never flip the verdict or the exit code. Each entry has the **same shape as a validation error item** (`category`, `error_type`, `pipe_code`, `domain_code`, `variable_names`, `message`) — this is a different shape from the `init`/`doctor` setup `warnings` (`{type, message}`) documented under Output Contract below. Three families ride the array, always in this order: the useless-`!` lint (`optional_force_redundant`), a `!` (force) input whose slot is guaranteed present in every analyzed flow, so the assertion can never fire; the vacuous-presence lint (`input_presence_vacuous`), an entry-pipe input that must be supplied but whose concept declares no required field, so the empty object satisfies it and a caller cannot tell what to fill in (see [Understanding Optionality](../../building-methods/pipes/understanding-optionality.md)); and the [intent-hint](../../building-methods/concepts/intent-hints.md) lints (`hint_unknown_key`, `hint_unknown_intent`, `hint_inapplicable_intent`). Every whole-bundle validate channel — this CLI, the bare CLI and the protocol validation report — assembles them from one composition point, so which advisories you see does not depend on which command you typed. Hint findings are bounded per site: a site naming many undefined keys reports the first few and then how many more there were, and a long authored key or value is elided in the message. In markdown, warnings render as a "Warnings" section. The array is empty when there is nothing to report; `validate pipe` omits it (no flow context to lint in). `validate bundle`/`validate method` with `--pipe` keep it, and it stays bundle-wide there — the slice narrows the dry run, not the validation.### Fix@@ -138,7 +138,7 @@ The JSON success envelope names the pipe the template was generated for as `pipeA pipe that declares no inputs is not an error: the envelope carries `"inputs": {}` and the command exits `0`; under `--format toml` it prints the comment `# Pipe 'my_domain.main_pipe' declares no inputs.`!!! note "`inputs --format` is `json|toml`, not `markdown|json`"- Unlike `run`/`validate`, the `inputs` command's `--format` selects the **template serialization**, not a presentation style. `json` (the default) emits the structured JSON success envelope; `toml` prints the raw TOML template straight to stdout (a pipe with no inputs prints a TOML comment line, which loads back as an empty dict). This mirrors the raw-TOML output of the `concept` and `pipe` commands. `inputs` has no `--error-format` — its errors stay JSON.+ Unlike `run`/`validate`, the `inputs` command's `--format` selects the **template serialization**, not a presentation style. `json` (the default) emits the structured JSON success envelope; `toml` prints the raw TOML template straight to stdout (a pipe with no inputs prints a TOML comment line, which loads back as an empty dict). `inputs` has no `--error-format` — its errors stay JSON.!!! note "`--explicit` and concept hints"The light `--format toml` template carries the declared concept for each key as a `# concept: ...` comment; the light `--format json` template (the default) cannot (JSON has no comments), so pass `--explicit` when you want the concept written out inline. The JSON success envelope shape (`success` / `pipe_ref` / `inputs`) is unchanged — only the `inputs` payload flips between the light values and the envelope form.@@ -151,8 +151,6 @@ These commands do not have subcommands:|---------|-------------|| `fmt` | Format a `.mthds`/`.toml`/`.plx` file in-place (delegates to `plxt`) || `lint` | Lint a `.mthds`/`.toml`/`.plx` file for errors (delegates to `plxt`) |-| `concept` | Convert a JSON concept spec into raw TOML (stdout) |-| `pipe` | Convert a JSON pipe spec into raw TOML (stdout) || `models` | List available model presets, aliases, and waterfalls (`--format markdown\|json` success, default: markdown; `--error-format` for errors, defaults to `--format`'s value) || `doctor` | Check config, credentials, and model health (`--format markdown\|json` success, default: markdown; `--error-format` for errors, defaults to `--format`'s value) |@@ -162,7 +160,6 @@ Commands use different stdout formats depending on their purpose:- **Markdown or JSON**: `run`, `validate`, `fix`, `init`, `models`, `check-model`, `doctor`, `migrate`, `codegen types`, `codegen check` — markdown by default, JSON with `--format json`. Error format follows `--error-format` (defaults to `--format`'s value, so `--format json` flips both).- **JSON or raw TOML**: `inputs` — structured JSON via `agent_success()` by default (`--format json`), or the raw TOML template printed directly to stdout with `--format toml`-- **Raw TOML**: `concept`, `pipe` — TOML text printed directly to stdout- **Passthrough**: `fmt`, `lint` — raw `plxt` output**JSON success** — written to stdout:diff --git a/docs/tools/cli/build/index.md b/docs/tools/cli/build/index.mdindex 9e470fad9..a2fff6743 100644--- a/docs/tools/cli/build/index.md+++ b/docs/tools/cli/build/index.md@@ -1,16 +1,15 @@----description: "Generate runner code, Pydantic structures, and JSON templates from your pipeline definitions using the Pipelex build commands."+description: "Generate Pydantic structures and example input and output templates from your method definitions using the Pipelex build commands."---# Build Commands-Generate pipelines, runner code, Python structures, and JSON templates from natural language descriptions.+Generate the Python structures of your concepts and example input and output templates for a pipe, from your `.mthds` definitions.## Available Commands| Command | Description ||---------|-------------|-| [**build runner**](runner.md) | Generate Python code to run a pipe || [**build structures**](structures.md) | Generate the structures (Pydantic models) of your concepts || [**build inputs**](inputs.md) | Generate example input JSON for a pipe || [**build output**](output.md) | Generate example output representation for a pipe (JSON, Python, or JSON Schema) |diff --git a/docs/tools/cli/build/inputs.md b/docs/tools/cli/build/inputs.mdindex c0770accb..ded1485cc 100644--- a/docs/tools/cli/build/inputs.md+++ b/docs/tools/cli/build/inputs.md@@ -206,5 +206,4 @@ When an input is declared multiple (`Tag[]`), the light form wraps the example v## Related Documentation- [Build Output](output.md) - Generate example output JSON for a pipe-- [Build Runner](runner.md) - Generate Python code to run a pipe- [Provide Inputs](../../../building-methods/pipes/provide-inputs.md) - Learn about input formatsdiff --git a/docs/tools/cli/build/output.md b/docs/tools/cli/build/output.mdindex 732ec7ead..cb232fe85 100644--- a/docs/tools/cli/build/output.md+++ b/docs/tools/cli/build/output.md@@ -255,5 +255,4 @@ This helps you understand all possible output structures that the pipe could ret## Related Documentation- [Build Inputs](inputs.md) - Generate example input JSON for a pipe-- [Build Runner](runner.md) - Generate Python code to run a pipe- [Pipe Output](../../../building-methods/pipes/pipe-output.md) - Learn about pipe outputsdiff --git a/docs/tools/cli/build/runner.md b/docs/tools/cli/build/runner.mdindex 423be944a..c03a3f675 100644--- a/docs/tools/cli/build/runner.md+++ b/docs/tools/cli/build/runner.md@@ -1,108 +1,13 @@----description: "Generate ready-to-use Python code for running a pipe, complete with imports and example inputs from your .mthds bundles."+description: "The pipelex build runner command has been removed; write the runner yourself from the executing-pipelines guide and the codegen structures."----# Build Runner+# Build Runner — REMOVED-Generate Python code to run a pipe with all necessary imports and example inputs.+**`pipelex build runner` is gone**: `pipelex build runner bundle` and `pipelex build runner method` are no longer commands, and `pipelex build` answers `runner` as an unknown command. The `POST /v1/build/runner` route that served the same script went before it.-## Usage+## What replaces it-### From a bundle--```bash-pipelex build runner bundle <PATH> [OPTIONS]-```--**Arguments:**--- `PATH` - Path to a `.mthds` bundle file or a pipeline directory--**Options:**--- `--pipe` - Pipe code to use (optional if the `.mthds` declares a `main_pipe`)-- `--output`, `-o` - Path to save the generated Python file (defaults to target's directory)-- `--library-dirs`, `-L` - Directories to search for pipe definitions. Can be specified multiple times.--### From an installed method--```bash-pipelex build runner method <NAME> [OPTIONS]-```--**Arguments:**--- `NAME` - Name of the installed method, a method address (`github.com/owner/repo[/name][@tag]`), or a GitHub URL — see [Run a Method by Address](../run-by-address.md)--**Options:**--- `--pipe` - Pipe code (overrides method's `main_pipe`)-- `--output`, `-o` - Path to save the generated Python file-- `--library-dirs`, `-L` - Directories to search for pipe definitions. Can be specified multiple times.--For a method fetched by address, the package is copied beside the generated script (into a directory named after the method) and the script references that copy — the fetched clone itself is temporary and deleted at process exit, so the generated runner stays self-contained and usable afterwards. See [Run a Method by Address](../run-by-address.md).--## Examples--**Generate runner from a bundle (uses main_pipe):**--```bash-pipelex build runner bundle my_bundle.mthds-```--**Generate runner from a pipeline directory:**--```bash-pipelex build runner bundle pipeline_01/-```--**Specify which pipe to use from a bundle:**--```bash-pipelex build runner bundle my_bundle.mthds --pipe my_pipe-```--**With additional library directories:**--```bash-pipelex build runner bundle my_bundle.mthds -L ./shared_pipes/ -L ./common/-```--**Custom output path:**--```bash-pipelex build runner bundle my_bundle.mthds --output custom_runner.py-```--## What Gets Generated--The generated Python file includes:--1. **All necessary imports** - Imports for Pipelex execution, content types, and any custom structures (`from structures.structures import …`)-2. **Generated Pydantic structures** - A stamped `structures/structures.py` module (plus its `codegen.lock`) emitted by the codegen engine, same as `pipelex build structures`-3. **Input memory setup** - Example input values based on the pipe's input types-4. **Pipeline execution** - Async function that executes the pipeline-5. **Output handling** - Code to extract and display the results-6. **Main execution block** - Pipelex initialization and asyncio setup--## Input Type Handling--- **Native concepts** (Text, Image, Document, etc.) - Automatically generates appropriate content objects-- **Custom concepts** - Recursively generates the structure with example values-- **Structured content** - Creates example data matching the concept's fields--## Using the Generated Runner--After generating the runner file:--1. Open the generated Python file-2. Review and customize the example input values-3. Run the script: `python results/run_{pipe_code}.py`-4. Iterate and adjust as needed--## Related Documentation--- [Build Structures](structures.md) - Generate Pydantic models separately-- [Build Inputs](inputs.md) - Generate example input JSON for a pipe-- [Build Output](output.md) - Generate example output JSON for a pipe-- [Run Command](../run.md) - Run pipes directly from CLI+- **The typed structures the script imported** are the `python-structures` target of the codegen engine: [`pipelex build structures`](structures.md), or `pipelex codegen types --target python-structures`, writes them under `structures/` with their `codegen.lock`.+- **The example inputs the script carried** come from [`pipelex build inputs`](inputs.md).+- **The script itself** is a few lines you write once: open Pipelex with `Pipelex.make()`, then execute the pipe with `PipelexMTHDSProtocol().execute(pipe_code=..., inputs=...)` and read its typed output, as [Executing Pipelines](../../../building-methods/pipes/executing-pipelines.md) shows. To run a method without writing any code, use [`pipelex run`](../run.md).diff --git a/docs/tools/cli/build/structures.md b/docs/tools/cli/build/structures.mdindex 382ff302f..3054a27e9 100644--- a/docs/tools/cli/build/structures.md+++ b/docs/tools/cli/build/structures.md@@ -92,7 +92,6 @@ class CandidateProfile(StructuredContent):## Related Documentation- [Codegen projections](../../../under-the-hood/codegen-projections.md) - The engine behind this command (`codegen types`, stamps, lock, offline check)-- [Build Runner](runner.md) - Generate Python runner scripts- [Build Inputs](inputs.md) - Generate example input JSON for a pipe- [Build Output](output.md) - Generate example output JSON for a pipe- [Concepts](../../../building-methods/concepts/define_your_concepts.md) - Understanding concept definitionsdiff --git a/docs/tools/cli/index.md b/docs/tools/cli/index.mdindex 992b501b9..01b7aae45 100644--- a/docs/tools/cli/index.md+++ b/docs/tools/cli/index.md@@ -31,7 +31,7 @@ The Pipelex CLI is organized into several command groups:| [**show**](show.md) | Inspect configuration, pipes, and AI models || [**run**](run.md) | Execute pipelines || [**run method by address**](run-by-address.md) | Fetch and run a method straight from a public GitHub repository |-| [**build**](build/index.md) | Generate pipelines, runners, and structures |+| [**build**](build/index.md) | Generate concept structures and example inputs and outputs for a pipe |## Global flagsdiff --git a/docs/tools/cli/run-by-address.md b/docs/tools/cli/run-by-address.mdindex 45e8ab44b..fb6a33c32 100644--- a/docs/tools/cli/run-by-address.md+++ b/docs/tools/cli/run-by-address.md@@ -48,8 +48,6 @@ The pipe to run defaults to the manifest's `main_pipe`; `--pipe <code>` overrideThe fetched clone is temporary: it lives in a system temp directory and is deleted when the CLI process exits. Default outputs therefore anchor in **your current working directory** — `pipelex run method <ref>` writes into `./results/`, and the `pipelex build` method commands write their generated files there too, so nothing you produced disappears with the clone. An explicit `--output-dir` / `--output` is honored verbatim. For an installed method or a local path, defaults stay inside the method's own directory, as before.-`pipelex build runner method <ref>` goes one step further: the generated script embeds the library directory it loads at run time, so the fetched package is copied beside the script (into a directory named after the method) and the script references that copy — a self-contained artifact that still works after the clone is gone.-## Python in fetched methods: the hosted ruleWhat decides whether Python in a method is acceptable is **where it would execute**:diff --git a/docs/under-the-hood/codegen-projections.md b/docs/under-the-hood/codegen-projections.mdindex 69fe68caa..8ecc2f3e1 100644--- a/docs/under-the-hood/codegen-projections.md+++ b/docs/under-the-hood/codegen-projections.md@@ -57,7 +57,7 @@ Two command families drive the engine:Both codegen commands load and normalize the crate through the same shared helper the resolver uses (`pipelex/cli/commands/crate_loading.py`), so they share the resolve/validate exit-code contract.-The **agent CLI mirrors** the family for machine consumers: `pipelex-agent codegen types --target <flavor>` runs the same engine and emission layer but presents through the agent CLI's two-stream envelopes (`--format markdown|json` on stdout for success, `--error-format` on stderr for errors — markdown default), and `pipelex-agent codegen check` is the same offline drift check with the verdict as a structured envelope: up-to-date is a success envelope, drift is a `CodegenDriftError` error envelope enumerating `drifts[]` by category (exit `1`), and a missing/unreadable lock is a no-verdict error (exit `2`). There is no `pipelex-agent codegen inputs` — the existing `pipelex-agent inputs` group already surfaces that projection. The legacy `build` family rides the same engine: `pipelex build inputs` renders through the same `input_renderer` engine as `codegen inputs` (they cannot diverge), and `pipelex build structures` is a thin alias of `codegen types --target python-structures` (the old always-qualified per-file generator is gone — the alias emits the single stamped `structures.py` + `codegen.lock`, bare-when-unique names). `pipelex build runner` emits its `structures/` scaffold through the same projection and spells the script's imports and example inputs with the emitted class names (`from structures.structures import …`), so the script and the module always agree.+The **agent CLI mirrors** the family for machine consumers: `pipelex-agent codegen types --target <flavor>` runs the same engine and emission layer but presents through the agent CLI's two-stream envelopes (`--format markdown|json` on stdout for success, `--error-format` on stderr for errors — markdown default), and `pipelex-agent codegen check` is the same offline drift check with the verdict as a structured envelope: up-to-date is a success envelope, drift is a `CodegenDriftError` error envelope enumerating `drifts[]` by category (exit `1`), and a missing/unreadable lock is a no-verdict error (exit `2`). There is no `pipelex-agent codegen inputs` — the existing `pipelex-agent inputs` group already surfaces that projection. The legacy `build` family rides the same engine: `pipelex build inputs` renders through the same `input_renderer` engine as `codegen inputs` (they cannot diverge), and `pipelex build structures` is a thin alias of `codegen types --target python-structures` (the old always-qualified per-file generator is gone — the alias emits the single stamped `structures.py` + `codegen.lock`, bare-when-unique names).## The trust chain: stamps, lock, and the offline checkdiff --git a/docs/under-the-hood/dry-run-mock-generation.md b/docs/under-the-hood/dry-run-mock-generation.mdindex d640010ea..88ade28ec 100644--- a/docs/under-the-hood/dry-run-mock-generation.md+++ b/docs/under-the-hood/dry-run-mock-generation.md@@ -11,16 +11,12 @@ Dry runs validate pipeline structure without executing inference. This requires## Why Mock Generation Matters-Pydantic models in Pipelex often enforce format constraints via `field_validator` or `model_validator`:+The structures a method declares can enforce format constraints via `field_validator` or `model_validator`:```python-class BundleHeaderSpec(StructuredContent):- domain_code: str # Must be snake_case- main_pipe: str # Must be snake_case, must exist in pipe dict---class ConceptSpec(StructuredContent):- concept_code: str # Must be PascalCase+class ComponentRecord(StructuredContent):+ component_code: str # A validator requires snake_case+ concept_code: str # A validator requires PascalCase```Standard mock generators (like Polyfactory) produce random strings like `"uygNjiAuDMOtZEyibgHw"` which fail validation. The dry run system addresses this at two levels:@@ -116,8 +112,8 @@ class DryRunFactory:| `PASCAL_CASE` | `generate_pascal_case_code()` | `MockAbcd` | `concept_code` || `CONCEPT_REF` | `generate_concept_ref()` | `mock_abcd.MockCdef` | `concept_ref` field (domain.ConceptCode format) || `IGNORE` | Sets field to `Ignore()` | None/default | `default_value`, `structure` fields |-| `DICT_SNAKE_KEY_PASCAL_VALUE` | `generate_dict_snake_key_pascal_value()` | `{mock_abcd: MockCdef}` | `inputs` dict in PipeSpec |-| `DICT_SINGLE_EXTRACT_INPUT` | `generate_dict_single_extract_input()` | `{mock_abcd: "Image"}` | `inputs` dict in PipeExtract |+| `DICT_SNAKE_KEY_PASCAL_VALUE` | `generate_dict_snake_key_pascal_value()` | `{mock_abcd: MockCdef}` | a dict of input names to concept codes |+| `DICT_SINGLE_EXTRACT_INPUT` | `generate_dict_single_extract_input()` | `{mock_abcd: "Image"}` | a single-entry dict of an input name to an image or document concept || Image URL | `generate_mock_image_url()` | one of `inference.dry_run.image_urls` | `url` of an `ImageContent`, at any depth || Document URL | `generate_mock_document_url()` | `data:application/pdf;base64,…` (a blank one-page PDF) | `url` of a `DocumentContent`, at any depth || Random string | Polyfactory default | `uygNjiAuDMOtZEyibgHw` | All other string fields |@@ -135,7 +131,7 @@ from pydantic import Fieldfrom pipelex.cogt.content_generation.dry_run_factory import MockFormat-class ConceptStructureSpec(StructuredContent):+class FieldDefinition(StructuredContent):# Snake case fieldthe_field_name: str = Field(description="Field name. Must be snake_case.", json_schema_extra={"mock_format": MockFormat.SNAKE_CASE})@@ -157,20 +153,18 @@ class ConceptStructureSpec(StructuredContent):For fields that should pick from a set of valid values (like enum members or known strings), use the `examples` parameter. The factory's `__use_examples__: True` configuration makes Polyfactory randomly select from provided examples:```python-class ConceptSpec(StructuredContent):+class Ticket(StructuredContent):# Refines should be one of the native conceptsrefines: str | None = Field(default=None,examples=["Text", "Image", "Document", "TextAndImages", "Number", "Page"],)--class PipeComposeSpec(PipeSpec):- # Target format should be a valid TargetFormat value- target_format: TargetFormat | str | None = Field(+ # Status should be a valid TicketStatus value+ status: TicketStatus | str | None = Field(default=None,- description="Target format for the output (template mode)",- examples=list(TargetFormat), # Polyfactory picks randomly from these+ description="Where the ticket stands",+ examples=list(TicketStatus), # Polyfactory picks randomly from these)```@@ -296,7 +290,7 @@ There is one fallback: when composition fails with a `StructuredContentComposerV### Using the New Format on Fields```python-class MySpec(StructuredContent):+class MyStructure(StructuredContent):my_kebab_field: str = Field(description="A kebab-case identifier", json_schema_extra={"mock_format": MockFormat.KEBAB_CASE})```@@ -310,7 +304,7 @@ class MySpec(StructuredContent):| File | Purpose ||------|---------|| `pipelex/cogt/content_generation/dry_run_factory.py` | `DryRunFactory` class with `MockFormat` enum and generators |-| `pipelex/cogt/content_generation/dry_mock.py` | Leaf-level dry/mock helpers (`dry_llm_gen_*`, `build_mock_object`, `stamp_mock_main_coordination`) |+| `pipelex/cogt/content_generation/dry_mock.py` | Leaf-level dry/mock helpers (`dry_llm_gen_*`, `build_mock_object`) || `pipelex/core/memory/working_memory_factory.py` | `WorkingMemoryFactory.make_mock_content()` with field constraints || `pipelex/pipe_operators/compose/structured_content_composer.py` | Composes `StructuredContent` from working memory (no mocks) || `pipelex/pipeline/dry_run_pipeline.py` | `dry_run_pipeline()` orchestration |diff --git a/docs/under-the-hood/error-model.md b/docs/under-the-hood/error-model.mdindex ff36bf5cb..4a0a8c67d 100644--- a/docs/under-the-hood/error-model.md+++ b/docs/under-the-hood/error-model.md@@ -482,7 +482,7 @@ The agent CLI (`pipelex-agent`) emits a structured error to **stderr**, markdown| Command | Error output ||---------|--------------|| `run`, `validate`, `init`, `models`, `check-model`, `doctor` | Markdown (default) or JSON via `--error-format` (or via `--format`, which `--error-format` inherits) |-| `inputs`, `concept`, `pipe`, `accept-gateway-terms` | JSON only |+| `inputs`, `accept-gateway-terms` | JSON only || `fmt`, `lint` | Native `plxt` output (subprocess passthrough); falls back to JSON only when the `plxt` binary itself is missing |The human CLI (`pipelex`) renders a Rich error panel — red banner, structured fields, the `user_action` tip, doc/Discord links — through the shared `display_error_panel()` helper in `pipelex/cli/error_handlers.py`.diff --git a/mkdocs.yml b/mkdocs.ymlindex aef523f06..2872f72cb 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -302,7 +302,6 @@ plugins:- tools/cli/show.md: "CLI Show"- tools/cli/pkg.md: "CLI Pkg"- tools/cli/build/index.md: "CLI Build Overview"- - tools/cli/build/runner.md: "CLI Build Runner"- tools/cli/build/structures.md: "CLI Build Structures"- tools/cli/build/inputs.md: "CLI Build Inputs"- tools/cli/build/output.md: "CLI Build Output"@@ -544,10 +543,10 @@ nav:- Pkg: tools/cli/pkg.md- Build:- Overview: tools/cli/build/index.md- - Runner: tools/cli/build/runner.md- Structures: tools/cli/build/structures.md- Inputs: tools/cli/build/inputs.md- Output: tools/cli/build/output.md+ - Runner (Removed): tools/cli/build/runner.md- Agent CLI: tools/cli/agent-cli.md- Tools:- plxt (Formatter & Linter): tools/plxt.mddiff --git a/pipelex/builder/CLAUDE.md b/pipelex/builder/CLAUDE.mddeleted file mode 100644index 235d2e08b..000000000--- a/pipelex/builder/CLAUDE.md+++ /dev/null@@ -1,80 +0,0 @@-# Builder--Provides the spec layer for authoring Pipelex pipeline bundles (`.mthds` files). Specs are a convenience authoring format for AI agents — they compile down to blueprints via `to_blueprint()`.--## Core Flow--```-PipelexBundleSpec → to_blueprint() → PipelexBundleBlueprint → MTHDS file-```--## Code Layout--```-exceptions.py # Exception types-conventions.py # File naming defaults (bundle.mthds, inputs.json)-bundle_spec.py # PipelexBundleSpec — top-level spec model-bundle_header_spec.py # Bundle header info-runner_code.py # Code generation utilities-concept/- concept_spec.py # ConceptSpec, ConceptStructureSpec, field types-pipe/- pipe_spec.py # PipeSpec base class (pipe_code, type, inputs, output)- pipe_spec_union.py # PipeSpecUnion — discriminated union of all pipe types- pipe_signature_spec.py # Pipe signature information- sub_pipe_spec.py # SubPipeSpec — references to pipes inside controllers- pipe_spec_map.py # Pipe spec mapping- pipe_llm_spec.py # PipeLLM — LLM operator- pipe_func_spec.py # PipeFunc — Python function operator- pipe_img_gen_spec.py # PipeImgGen — image generation operator- pipe_extract_spec.py # PipeExtract — OCR/text extraction operator- pipe_search_spec.py # PipeSearch — web search operator- pipe_judge_spec.py # PipeJudge — closed-question judgment operator- pipe_structure_spec.py # PipeStructure — text-to-structure operator- pipe_doc_gen_spec.py # PipeDocGen — document generation operator- pipe_compose_spec.py # PipeCompose — template/construct operator- pipe_sequence_spec.py # PipeSequence — sequential controller- pipe_parallel_spec.py # PipeParallel — concurrent controller- pipe_condition_spec.py # PipeCondition — branching controller- pipe_batch_spec.py # PipeBatch — map-over-list controller-operations/- concept_ops.py # Parse/serialize concepts to TOML- inputs_ops.py # Generate example input JSON- models_ops.py # Model preset listing and markdown formatting- output_ops.py # Generate output JSON representations- pipe_ops.py # Parse/serialize pipes to TOML- runner_code_ops.py # Code generation utilities- validate_ops.py # Validation operations-```--## Spec Architecture--All specs are Pydantic models (`StructuredContent` base). Two categories of pipes:--**Operators** (data transformation): `PipeLLM`, `PipeFunc`, `PipeImgGen`, `PipeExtract`, `PipeSearch`, `PipeJudge`, `PipeStructure`, `PipeDocGen`, `PipeCompose`--**Controllers** (execution flow): `PipeSequence`, `PipeParallel`, `PipeCondition`, `PipeBatch`--Each spec has `to_blueprint()` which converts it to the core framework's blueprint type. This separation keeps user-facing specs independent from internal execution types.--## Critical: PipeSpecs and ConceptSpecs Are NOT the MTHDS Language--PipeSpec and ConceptSpec subclasses in this directory are a **convenience authoring format** for AI agents and builders. They are NOT the ground truth of the MTHDS standard.--The ground truth is the **blueprint** layer:--- **Blueprints** (`pipelex/pipe_operators/`, `pipelex/pipe_controllers/`, `pipelex/pipe_machinery/`, `pipelex/mthds_parsing/`, `pipelex/core/`) define the actual MTHDS language. They are what `.mthds` files parse into via `MthdsParser.make_pipelex_bundle_blueprint()`. The base `PipeBlueprint` is in `pipe_machinery/pipe_blueprint.py`, the `PipelexBundleBlueprint` the parser produces is in `mthds_parsing/pipelex_bundle_blueprint.py`, and the concept/domain blueprints are in `core/`.-- **Specs** are transformed into blueprints via `to_blueprint()` and then discarded. Spec-level fields (e.g., `PipeComposeSpec.target_format`) may not exist on the corresponding blueprint (e.g., `PipeComposeBlueprint` uses `TemplateBlueprint` with `category` + `templating_style` instead).--When reviewing or modifying code: do not assume that a validation rule on a PipeSpec subclass reflects a rule of the MTHDS language. Check the corresponding blueprint class.--`PipeSpecUnion` is a `Field(discriminator="type")` union of all pipe spec types.--## Multiplicity Notation--Pipe inputs and outputs use multiplicity suffixes on concept names:--- `Text` — single item-- `Text[]` — variable-length list-- `Text[N]` — exactly N items-diff --git a/pipelex/builder/__init__.py b/pipelex/builder/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/pipelex/builder/bundle_header_spec.py b/pipelex/builder/bundle_header_spec.pydeleted file mode 100644index 320f3f107..000000000--- a/pipelex/builder/bundle_header_spec.py+++ /dev/null@@ -1,38 +0,0 @@-from typing import TYPE_CHECKING--from pydantic import Field-from typing_extensions import override--from pipelex.cogt.content_generation.dry_mock import MOCK_MAIN_PIPE_CODE-from pipelex.cogt.content_generation.dry_run_factory import MockFormat-from pipelex.core.stuffs.structured_content import StructuredContent-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class BundleHeaderSpec(StructuredContent):- domain_code: str = Field(description="Name of the domain of the knowledge work.", json_schema_extra={"mock_format": MockFormat.SNAKE_CASE})- description: str = Field(description="Definition of the domain of the knowledge work.")- system_prompt: str | None = Field(description="System prompt for the domain.")- # The example IS the dry-run coordination: mocked headers name MOCK_MAIN_PIPE_CODE as the- # bundle's main pipe, and stamp_mock_main_coordination makes mocked pipe-spec lists answer to it.- main_pipe: str = Field(description="The main pipe of the domain.", examples=[MOCK_MAIN_PIPE_CODE])-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.text import Text-- bundle_group = Group()- if title:- bundle_group.renderables.append(Text(title, style="bold"))- bundle_group.renderables.append(Text.from_markup(f"Domain: [yellow]{self.domain_code}[/yellow]\n", style="bold"))- bundle_group.renderables.append(Text.from_markup(f"Description: [yellow italic]{self.description}[/yellow italic]\n"))- bundle_group.renderables.append(Text.from_markup(f"Main Pipe: [red]{self.main_pipe}[/red]\n"))- if self.system_prompt:- bundle_group.renderables.append(Text(f"System Prompt: {self.system_prompt}", style="dim"))-- return bundle_groupdiff --git a/pipelex/builder/bundle_spec.py b/pipelex/builder/bundle_spec.pydeleted file mode 100644index 722200a41..000000000--- a/pipelex/builder/bundle_spec.py+++ /dev/null@@ -1,212 +0,0 @@-from typing import TYPE_CHECKING, Any, cast--from pydantic import ConfigDict, Field, ValidationError, field_validator, model_validator-from typing_extensions import override--from pipelex.builder.concept.concept_spec import ConceptSpec-from pipelex.builder.exceptions import PipelexBundleSpecBlueprintError-from pipelex.builder.pipe.pipe_spec_union import PipeSpecUnion-from pipelex.core.domains.exceptions import DomainCodeError-from pipelex.core.domains.validation import validate_domain_code-from pipelex.core.stuffs.structured_content import StructuredContent-from pipelex.mthds_parsing.pipe_sorter import sort_pipes_by_dependencies-from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipeBlueprintUnion, PipelexBundleBlueprint-from pipelex.pipe_machinery.pipe_blueprint import SIGNATURE_ONLY_KEYS, normalize_typeless_signature_section-from pipelex.pipe_machinery.validation import is_pipe_code_valid-from pipelex.tools.misc.pretty import require_rich_for_rendering-from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable--if TYPE_CHECKING:- from pipelex.core.concepts.concept_blueprint import ConceptBlueprint--# The spec layer's typeless-signature allowlist is the shared blueprint contract set adapted to the-# spec's actual field surface: drop `source` (a blueprint-only field — `PipeSpec` has no `source` and-# forbids extras, so a typeless section carrying it must hit the teaching error, not be injected and-# then rejected with a raw pydantic message) and add the structural `pipe_code` field (the blueprint-# uses the dict key; the spec section carries it explicitly). Any other key on a typeless section-# still triggers the teaching error.-SIGNATURE_ONLY_SPEC_KEYS: frozenset[str] = (SIGNATURE_ONLY_KEYS - {"source"}) | {"pipe_code"}---class PipelexBundleSpec(StructuredContent):- """Complete spec of a Pipelex bundle TOML definition.-- Represents the top-level structure of a Pipelex bundle, which defines a domain- with its concepts, pipes, and configuration. Bundles are the primary unit of- organization for Pipelex methods, loaded from TOML files.-- Attributes:- domain: The domain identifier for this bundle in snake_case format.- Serves as the namespace for all concepts and pipes within.- description: Natural language description of the pipeline's purpose and functionality.- system_prompt: Default system prompt applied to all LLM pipes in the bundle- unless overridden at the pipe level.- main_pipe: The main pipe of the bundle.- concept: Dictionary of concept definitions used in this domain. Keys are concept- codes in PascalCase format, values are ConceptSpec instances or plain- strings used as the concept's description.- pipe: Dictionary of pipe definitions for data transformation. Keys are pipe- codes in snake_case format, values are specific pipe spec types- (PipeLLM, PipeImgGen, PipeSequence, etc.).-- Validation Rules:- 1. Domain must be in valid snake_case format.- 2. Concept keys must be in PascalCase format.- 3. Pipe keys must be in snake_case format.- 4. Extra fields are forbidden (strict mode).- 5. Pipe types must match their blueprint discriminator.-- """-- model_config = ConfigDict(extra="forbid")-- domain: str- description: str | None = None- system_prompt: str | None = None- main_pipe: str-- concept: dict[str, ConceptSpec | str] | None = Field(default_factory=dict)-- pipe: dict[str, PipeSpecUnion] | None = Field(default_factory=dict)-- @field_validator("domain", mode="before")- @classmethod- def validate_domain_syntax(cls, domain_code: str) -> str:- try:- validate_domain_code(code=domain_code)- except DomainCodeError as exc:- msg = f"Error when trying to validate pipelex bundle spec: domain '{domain_code}' is not a valid domain code: {exc}"- raise ValueError(msg) from exc- return domain_code-- @field_validator("pipe", mode="before")- @classmethod- def validate_pipe_keys(cls, pipe: Any) -> Any:- """Validate pipe codes and normalize typeless sections before the discriminated union runs.-- Full mirror of `PipelexBundleBlueprint.validate_pipe_keys`: each dict key (the pipe code) is- rejected up front if not snake_case, then each section is normalized. A spec `[pipe.x]`- section with no `type` whose keys are exactly the signature contract- (`SIGNATURE_ONLY_SPEC_KEYS`) has the internal `PipeSignature` discriminator injected, so the- union routes it to `PipeSignatureSpec` — the author never writes the tag. A typeless section- that declares anything more is describing an implementation without naming its type, which is- a hard error. A section that already names a `type` (or is an already-built spec instance- rather than a raw dict) passes through untouched.- """- if pipe is None:- return None- if not isinstance(pipe, dict):- # Let the field type raise its own "should be a dict" error.- return pipe- typed_pipe = cast("dict[Any, Any]", pipe)- normalized: dict[Any, Any] = {}- for pipe_code, pipe_section in typed_pipe.items():- if isinstance(pipe_code, str) and not is_pipe_code_valid(pipe_code=pipe_code):- msg = f"Pipe code '{pipe_code}' is not a valid pipe code. Must be in snake_case."- raise ValueError(msg)- normalized[pipe_code] = normalize_typeless_signature_section(- pipe_code=pipe_code, pipe_section=pipe_section, allowed_keys=SIGNATURE_ONLY_SPEC_KEYS- )- return normalized-- @model_validator(mode="after")- def validate_main_pipe(self) -> "PipelexBundleSpec":- if not self.pipe or (self.main_pipe not in self.pipe):- msg = f"Main pipe '{self.main_pipe}' could not be found in bundle spec"- raise ValueError(msg)- return self-- def to_blueprint(self) -> PipelexBundleBlueprint:- concept: dict[str, ConceptBlueprint | str] | None = None-- if self.concept:- concept = {}- for concept_code, concept_spec_or_name in self.concept.items():- if isinstance(concept_spec_or_name, ConceptSpec):- concept[concept_code] = concept_spec_or_name.to_blueprint()- else:- # A bare string is a concept description — the blueprint layer accepts it as-is- concept[concept_code] = concept_spec_or_name-- pipe: dict[str, PipeBlueprintUnion] | None = None- if self.pipe:- # First, convert all specs to blueprints- pipe_blueprints: dict[str, PipeBlueprintUnion] = {}- for pipe_code, pipe_spec in self.pipe.items():- try:- pipe_blueprints[pipe_code] = pipe_spec.to_blueprint()- except ValidationError as exc:- msg = f"Failed to create pipe blueprint from spec for pipe code {pipe_code}: {format_pydantic_validation_error(exc)}"- raise PipelexBundleSpecBlueprintError(msg) from exc-- # Then, sort blueprints by dependencies- sorted_pipe_items = sort_pipes_by_dependencies(pipe_blueprints, domain_code=self.domain)- # Finally, create the ordered dict- pipe = dict[str, PipeBlueprintUnion](sorted_pipe_items)-- try:- return PipelexBundleBlueprint(- domain=self.domain,- description=self.description,- system_prompt=self.system_prompt,- main_pipe=self.main_pipe,- pipe=pipe,- concept=concept,- )- except ValidationError as exc:- msg = f"Failed to create pipelex bundle blueprint: {format_pydantic_validation_error(exc)}"- raise PipelexBundleSpecBlueprintError(msg) from exc-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.table import Table- from rich.text import Text-- bundle_group = Group()-- # Bundle header info- if title:- bundle_group.renderables.append(Text(title, style="bold"))- bundle_group.renderables.append(Text.from_markup(f"Domain: [yellow]{self.domain}[/yellow]\n", style="bold"))- if self.description:- bundle_group.renderables.append(Text.from_markup(f"Description: [yellow italic]{self.description}[/yellow italic]\n"))- bundle_group.renderables.append(Text.from_markup(f"Main Pipe: [red]{self.main_pipe}[/red]\n"))- if self.system_prompt:- bundle_group.renderables.append(Text(f"System Prompt: {self.system_prompt}\n", style="dim"))-- # Concepts table- if self.concept:- bundle_group.renderables.append(Text("\n"))- concepts_table = Table(- title="Concepts", title_style="bold green", show_header=False, show_edge=True, show_lines=True, border_style="green"- )- concepts_table.add_column("Concept", style="white")-- for concept_code, concept_spec_or_name in self.concept.items():- if isinstance(concept_spec_or_name, ConceptSpec):- concept_rendered = concept_spec_or_name.rendered_pretty()- concepts_table.add_row(concept_rendered)- else:- # Plain string concept value: the string is the concept's description- concepts_table.add_row(Text.from_markup(f"[green]{concept_code}[/green]: {concept_spec_or_name}"))-- bundle_group.renderables.append(concepts_table)-- # Pipes table- if self.pipe:- bundle_group.renderables.append(Text("\n"))- pipes_table = Table(title="Pipes", title_style="bold red", show_header=False, show_edge=True, show_lines=True, border_style="red")- pipes_table.add_column("Pipe", style="white")-- for pipe_spec in self.pipe.values():- pipe_rendered = pipe_spec.rendered_pretty()- pipes_table.add_row(pipe_rendered)-- bundle_group.renderables.append(pipes_table)-- return bundle_groupdiff --git a/pipelex/builder/concept/__init__.py b/pipelex/builder/concept/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/pipelex/builder/concept/concept_spec.py b/pipelex/builder/concept/concept_spec.pydeleted file mode 100644index b8901859d..000000000--- a/pipelex/builder/concept/concept_spec.py+++ /dev/null@@ -1,419 +0,0 @@-from datetime import date, datetime-from enum import StrEnum-from typing import TYPE_CHECKING, Any, Self, cast--from pydantic import ConfigDict, Field, field_validator, model_validator-from typing_extensions import override--from pipelex import log-from pipelex.builder.concept.exceptions import ConceptSpecError-from pipelex.cogt.content_generation.dry_run_factory import MockFormat-from pipelex.core.concepts.concept_blueprint import ConceptBlueprint, ConceptStructureBlueprint-from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprintFieldType-from pipelex.core.concepts.native.concept_native import NativeConceptCode-from pipelex.core.concepts.validation import is_concept_ref_or_code_valid-from pipelex.core.stuffs.structured_content import StructuredContent-from pipelex.tools.misc.pretty import require_rich_for_rendering-from pipelex.tools.misc.string_utils import is_pascal_case, normalize_to_ascii, snake_to_pascal_case--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class ConceptStructureSpecFieldType(StrEnum):- TEXT = "text"- INTEGER = "integer"- BOOLEAN = "boolean"- NUMBER = "number"- DATE = "date"- DATETIME = "datetime"- CONCEPT = "concept"- LIST = "list"-- @property- def is_text(self) -> bool:- match self:- case ConceptStructureSpecFieldType.TEXT:- return True- case (- ConceptStructureSpecFieldType.INTEGER- | ConceptStructureSpecFieldType.BOOLEAN- | ConceptStructureSpecFieldType.NUMBER- | ConceptStructureSpecFieldType.DATE- | ConceptStructureSpecFieldType.DATETIME- | ConceptStructureSpecFieldType.CONCEPT- | ConceptStructureSpecFieldType.LIST- ):- return False---class ConceptStructureSpec(StructuredContent):- """ConceptStructureSpec represents the schema for a single field in a concept's structure. It supports- various field types including text, integer, boolean, number, date, and concept.-- Attributes:- the_field_name: Field name. Must be snake_case.- description: Natural language description of the field's purpose and usage.- type: The field's data type.- required: Whether the field is mandatory. Defaults to False unless explicitly set to True.- default_value: Default value for the field. Must match the specified type.- concept_ref: For type="concept", the reference to the concept (e.g., "myapp.Customer").-- Validation Rules:- 1. CONCEPT type: concept_ref must be set; default_value cannot be set.- 3. Default values: When default_value is provided, it must match the specified type.-- """-- the_field_name: str = Field(description="Field name. Must be snake_case.", json_schema_extra={"mock_format": MockFormat.SNAKE_CASE})- description: str- # TODO: Change examples to list(ConceptStructureSpecFieldType) for randomness in mocks- type: ConceptStructureSpecFieldType = Field(description="The type of the field.", examples=["concept"])- required: bool = Field(default=False, description="Whether the field is mandatory. Defaults to False unless explicitly set to True.")- default_value: Any | None = Field(default=None, json_schema_extra={"mock_format": MockFormat.IGNORE})- concept_ref: str | None = Field(- default=None,- description="For type='concept', the concept reference (e.g., 'myapp.Customer').",- json_schema_extra={"mock_format": MockFormat.CONCEPT_REF},- )- choices: list[str] | None = Field(- default=None, description="List of allowed values for the field. When set, the field value must be one of these choices."- )- item_type: str | None = Field(- default=None,- description="For type='list', the type of items in the list (e.g., 'text', 'concept').",- )- item_concept_ref: str | None = Field(- default=None,- description="For type='list' with item_type='concept', the concept reference for list items.",- json_schema_extra={"mock_format": MockFormat.CONCEPT_REF},- )-- @model_validator(mode="before")- @classmethod- def default_type_for_choices(cls, values: dict[str, Any]) -> dict[str, Any]:- """Default type to TEXT when choices is present but type is omitted."""- if values.get("choices") and not values.get("type"):- values["type"] = "text"- return values-- @field_validator("type", mode="before")- @classmethod- def validate_type(cls, type_value: str) -> ConceptStructureSpecFieldType:- return ConceptStructureSpecFieldType(type_value)-- @model_validator(mode="after")- def validate_structure_blueprint(self) -> Self:- """Validate the structure blueprint according to type rules."""- if self.required and self.default_value is not None:- msg = (- f"A field cannot declare both required = true and a default_value: a default is applied when "- f"the caller omits the field, which contradicts requiring it. Got default_value: {self.default_value!r}. "- f"Drop `required` to keep the default, or drop `default_value` to keep the field required."- )- raise ValueError(msg)- match self.type:- case ConceptStructureSpecFieldType.CONCEPT:- if not self.concept_ref:- msg = "When type is 'concept', concept_ref must be set."- raise ValueError(msg)- if self.default_value is not None:- msg = "default_value cannot be set for concept type (complex objects cannot have defaults)."- raise ValueError(msg)-- case ConceptStructureSpecFieldType.LIST:- if not self.item_type:- msg = "When type is 'list', item_type must be set."- raise ValueError(msg)- if self.item_type == "concept" and not self.item_concept_ref:- msg = "When item_type is 'concept', item_concept_ref must be set."- raise ValueError(msg)- if self.item_concept_ref and self.item_type != "concept":- msg = f"item_concept_ref can only be set when item_type is 'concept'. Actual item_type: {self.item_type}"- raise ValueError(msg)- if self.default_value is not None:- msg = "default_value cannot be set for list type."- raise ValueError(msg)-- case (- ConceptStructureSpecFieldType.TEXT- | ConceptStructureSpecFieldType.INTEGER- | ConceptStructureSpecFieldType.BOOLEAN- | ConceptStructureSpecFieldType.NUMBER- | ConceptStructureSpecFieldType.DATE- | ConceptStructureSpecFieldType.DATETIME- ):- pass-- # Validate concept_ref can only be set when type is 'concept'- if self.concept_ref and self.type != ConceptStructureSpecFieldType.CONCEPT:- msg = f"'concept_ref' can only be set when type is 'concept'. Actual type: {self.type}"- raise ValueError(msg)-- # Validate item_type and item_concept_ref can only be set when type is 'list'- if self.item_type and self.type != ConceptStructureSpecFieldType.LIST:- msg = f"'item_type' can only be set when type is 'list'. Actual type: {self.type}"- raise ValueError(msg)- if self.item_concept_ref and self.type != ConceptStructureSpecFieldType.LIST:- msg = f"'item_concept_ref' can only be set when type is 'list'. Actual type: {self.type}"- raise ValueError(msg)-- # Validate choices is only compatible with text, integer, and number types- if self.choices:- match self.type:- case ConceptStructureSpecFieldType.TEXT | ConceptStructureSpecFieldType.INTEGER | ConceptStructureSpecFieldType.NUMBER:- pass- case (- ConceptStructureSpecFieldType.BOOLEAN- | ConceptStructureSpecFieldType.DATE- | ConceptStructureSpecFieldType.DATETIME- | ConceptStructureSpecFieldType.CONCEPT- | ConceptStructureSpecFieldType.LIST- ):- msg = f"'choices' cannot be used with type '{self.type}'. Only text, integer, and number types support choices."- raise ValueError(msg)-- # Check default_value type is the same as type- if self.default_value is not None:- self._validate_default_value_type()-- return self-- def _validate_default_value_type(self) -> None:- """Validate that default_value matches the specified type."""- if self.default_value is None:- return-- match self.type:- case ConceptStructureSpecFieldType.TEXT:- if not isinstance(self.default_value, str):- self._raise_type_mismatch_error(expected_type_name="str", actual_type_name=type(self.default_value).__name__)- case ConceptStructureSpecFieldType.INTEGER:- if not isinstance(self.default_value, int):- self._raise_type_mismatch_error(expected_type_name="int", actual_type_name=type(self.default_value).__name__)- case ConceptStructureSpecFieldType.BOOLEAN:- if not isinstance(self.default_value, bool):- self._raise_type_mismatch_error(expected_type_name="bool", actual_type_name=type(self.default_value).__name__)- case ConceptStructureSpecFieldType.NUMBER:- if not isinstance(self.default_value, (int, float)):- self._raise_type_mismatch_error(expected_type_name="number (int or float)", actual_type_name=type(self.default_value).__name__)- case ConceptStructureSpecFieldType.DATE:- # A calendar date, not a datetime: datetime is a subclass of date, so reject it explicitly- # (a datetime default would carry a time the `date` field silently drops).- if not isinstance(self.default_value, date) or isinstance(self.default_value, datetime):- self._raise_type_mismatch_error(expected_type_name="date", actual_type_name=type(self.default_value).__name__)- case ConceptStructureSpecFieldType.DATETIME:- if not isinstance(self.default_value, datetime):- self._raise_type_mismatch_error(expected_type_name="datetime", actual_type_name=type(self.default_value).__name__)- case ConceptStructureSpecFieldType.CONCEPT:- # CONCEPT type cannot have default values, this is already validated in validate_structure_blueprint- pass- case ConceptStructureSpecFieldType.LIST:- # LIST type cannot have default values, this is already validated in validate_structure_blueprint- pass-- def _raise_type_mismatch_error(self, *, expected_type_name: str, actual_type_name: str) -> None:- msg = f"default_value type mismatch: expected {expected_type_name} for type '{self.type}', but got {actual_type_name}"- raise ValueError(msg)-- def to_blueprint(self) -> ConceptStructureBlueprint:- # Convert the type enum value - self.type is already a ConceptStructureBlueprintFieldType enum- # We need to get the corresponding value in the core enum- # Get the string value and use it to get the core enum value- core_type = ConceptStructureBlueprintFieldType(self.type)-- return ConceptStructureBlueprint(- description=self.description,- type=core_type,- required=self.required,- default_value=self.default_value,- concept_ref=self.concept_ref,- choices=self.choices,- item_type=self.item_type,- item_concept_ref=self.item_concept_ref,- )---class ConceptSpec(StructuredContent):- """Spec structuring a concept: a conceptual data type that can either define its own structure or refine an existing native concept.-- Validation Rules:- 1. Mutual exclusivity: A concept must have either 'structure' or 'refines', but not both.- 2. Field names: When structure is a dict, all keys must be valid snake_case identifiers.- 3. Concept codes: Must be in PascalCase format (letters and numbers only, starting- with uppercase, no dots).- 4. Concept strings: Format is "domain.ConceptCode" where domain is lowercase and- ConceptCode is PascalCase.- 5. Native concepts: When refining, must be one of the valid native concepts.- 6. Structure values: In structure attribute, values must be either valid concept strings- or ConceptStructureBlueprint instances.- """-- model_config = ConfigDict(extra="forbid")-- concept_code: str = Field(description="Name of the concept. Must be PascalCase.", json_schema_extra={"mock_format": MockFormat.PASCAL_CASE})- description: str = Field(description="Description of the concept, in natural language.")- structure: dict[str, ConceptStructureSpec] | None = Field(- default=None,- description=(- "Definition of the concept's structure. Each attribute (snake_case) specifies: definition, type, and required or default_value if needed"- ),- json_schema_extra={"mock_format": MockFormat.IGNORE},- )- refines: str | None = Field(- default=None,- description=(- "If applicable: the native concept this concept extends "- f"({', '.join(NativeConceptCode)}) "- "in PascalCase format. Cannot be used together with 'structure'."- ),- examples=["Text", "Markdown", "Html", "Image", "Document", "Number", "Page", "TextAndImages", "JSON"],- )-- @field_validator("concept_code", mode="before")- @classmethod- def validate_concept_code(cls, value: str) -> str:- # Split first to handle domain.ConceptCode format- if "." in value:- domain, concept_code = value.rsplit(".", 1)- # Only normalize the concept code part (not the domain)- normalized_concept_code = normalize_to_ascii(concept_code)-- if normalized_concept_code != concept_code:- log.warning(- f"Concept code '{value}' contained non-ASCII characters in concept part, normalized to '{domain}.{normalized_concept_code}'"- )-- if not is_pascal_case(normalized_concept_code):- log.warning(f"Concept code '{domain}.{normalized_concept_code}' is not PascalCase, converting to PascalCase")- pascal_cased_value = snake_to_pascal_case(normalized_concept_code)- return f"{domain}.{pascal_cased_value}"- else:- return f"{domain}.{normalized_concept_code}"- else:- # No dot, normalize the whole thing- normalized_value = normalize_to_ascii(value)-- if normalized_value != value:- log.warning(f"Concept code '{value}' contained non-ASCII characters, normalized to '{normalized_value}'")-- if not is_pascal_case(normalized_value):- log.warning(f"Concept code '{normalized_value}' is not PascalCase, converting to PascalCase")- return snake_to_pascal_case(normalized_value)- else:- return normalized_value-- @field_validator("refines", mode="before")- @classmethod- def validate_refines(cls, refines: str | None = None) -> str | None:- """Validate the refines field.-- Refines can be either:- - A native concept ref (e.g., "native.Text", "Text")- - A non-native concept ref (e.g., "myapp.BaseEntity") for concept-to-concept inheritance-- Non-native concept refs are allowed since dependencies are loaded in topological order,- ensuring the refined concept exists before the refining concept is constructed.- """- if refines is None:- return None-- # Check if it's a valid concept ref or code (domain.ConceptCode or ConceptCode in PascalCase)- if is_concept_ref_or_code_valid(concept_ref_or_code=refines):- return refines-- # Invalid refines value- msg = f"Refines '{refines}' must be a valid concept ref (domain.ConceptCode) or concept code (PascalCase)"- raise ValueError(msg)-- @model_validator(mode="before")- @classmethod- def model_validate_spec(cls, values: Any) -> Any:- # mode="before" receives raw, unvalidated input — a non-dict (e.g. a plain string in a- # `ConceptSpec | str` union) must fall through untouched rather than crash on dict access- if not isinstance(values, dict):- return values- fields = cast("dict[str, Any]", values)- if fields.get("refines") and fields.get("structure"):- msg = (- f"Forbidden to have refines and structure at the same time: `{fields.get('refines')}` "- f"and `{fields.get('structure')}` for concept that has the description `{fields.get('description')}`"- )- raise ConceptSpecError(msg)- return fields-- def to_blueprint(self) -> ConceptBlueprint:- """Convert this ConceptBlueprint to the original core ConceptBlueprint."""- # TODO: Clarify concept structure blueprint- converted_structure: str | dict[str, str | ConceptStructureBlueprint] | None = None- if self.structure:- converted_structure = {}- for field_name, field_spec in self.structure.items():- converted_structure[field_name] = field_spec.to_blueprint()-- return ConceptBlueprint(description=self.description, structure=converted_structure, refines=self.refines)-- def _format_type_display(self, field_spec: ConceptStructureSpec) -> str:- """Format the type display string for a field, including extra info for complex types."""- match field_spec.type:- case ConceptStructureSpecFieldType.CONCEPT:- return f"concept[{field_spec.concept_ref}]"- case ConceptStructureSpecFieldType.LIST:- if field_spec.item_type == "concept":- return f"list[concept[{field_spec.item_concept_ref}]]"- return f"list[{field_spec.item_type}]"- case (- ConceptStructureSpecFieldType.TEXT- | ConceptStructureSpecFieldType.INTEGER- | ConceptStructureSpecFieldType.BOOLEAN- | ConceptStructureSpecFieldType.NUMBER- | ConceptStructureSpecFieldType.DATE- | ConceptStructureSpecFieldType.DATETIME- ):- return field_spec.type-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.table import Table- from rich.text import Text-- concept_group = Group()- if title:- concept_group.renderables.append(Text(title, style="bold"))- concept_group.renderables.append(Text.from_markup(f"Concept: [green]{self.concept_code}[/green]", style="bold"))- if self.refines:- concept_group.renderables.append(Text.from_markup(f"Refines: [green]{self.refines}[/green]"))- concept_group.renderables.append(Text.from_markup(f"\nDescription: [yellow italic]{self.description}[/yellow italic]\n"))- if self.structure:- # Check if any field has a default value- has_default_values = any(field_spec.default_value is not None for field_spec in self.structure.values())-- structure_table = Table(- title="Structure:",- title_style="not italic",- title_justify="left",- show_header=True,- header_style="dim",- show_edge=True,- show_lines=True,- border_style="dim",- )- structure_table.add_column("Field", style="blue")- structure_table.add_column("Description", style="white italic")- structure_table.add_column("Type", style="white")- structure_table.add_column("Required", style="white")- if has_default_values:- structure_table.add_column("Default Value", style="white")-- for field_name, field_spec in self.structure.items():- required_text = "Yes" if field_spec.required else "No"- type_display = self._format_type_display(field_spec)- row_data = [field_name, field_spec.description, type_display, required_text]- if has_default_values:- row_data.append(str(field_spec.default_value) if field_spec.default_value is not None else "")- structure_table.add_row(*row_data)- concept_group.renderables.append(structure_table)-- return concept_groupdiff --git a/pipelex/builder/concept/exceptions.py b/pipelex/builder/concept/exceptions.pydeleted file mode 100644index c0205fb40..000000000--- a/pipelex/builder/concept/exceptions.py+++ /dev/null@@ -1,16 +0,0 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError---class ConceptSpecError(PipelexError):- """Raised when a concept spec is malformed against its authoring contract.-- Covers both the raw-shape rejections in ``parse_concept_spec`` (a non-mapping- ``structure``, a field value that is neither a description string nor a- field-spec mapping) and the spec-level rule failures raised inside- ``ConceptSpec`` validators. Always describes a fault in the caller's own- input, so it classifies as ``INPUT`` and keeps its message under STRICT- disclosure.- """-- error_domain = ErrorDomain.INPUT- _authors_caller_facing_message = Truediff --git a/pipelex/builder/conventions.py b/pipelex/builder/conventions.pydeleted file mode 100644index 2a6dd78d6..000000000--- a/pipelex/builder/conventions.py+++ /dev/null@@ -1,11 +0,0 @@-"""Conventions for builder output file names.--These constants define the standard file names produced by the builder-and expected by the runner when auto-detecting from a directory.-"""--from pipelex.mthds_parsing.helpers import MTHDS_EXTENSION--DEFAULT_BUNDLE_FILE_NAME = f"bundle{MTHDS_EXTENSION}"-DEFAULT_INPUTS_FILE_NAME = "inputs.json"-DEFAULT_INPUTS_TOML_FILE_NAME = "inputs.toml"diff --git a/pipelex/builder/exceptions.py b/pipelex/builder/exceptions.pydeleted file mode 100644index a6a416f78..000000000--- a/pipelex/builder/exceptions.py+++ /dev/null@@ -1,5 +0,0 @@-from pipelex.base_exceptions import PipelexError---class PipelexBundleSpecBlueprintError(PipelexError):- passdiff --git a/pipelex/builder/operations/__init__.py b/pipelex/builder/operations/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/pipelex/builder/operations/concept_ops.py b/pipelex/builder/operations/concept_ops.pydeleted file mode 100644index e679a856e..000000000--- a/pipelex/builder/operations/concept_ops.py+++ /dev/null@@ -1,167 +0,0 @@-"""Core operations for concept spec parsing and TOML generation."""--# pyright: reportUnknownMemberType=false--from collections.abc import Mapping-from typing import Any, cast--import tomlkit--from pipelex.builder.concept.concept_spec import ConceptSpec, ConceptStructureSpec-from pipelex.builder.concept.exceptions import ConceptSpecError---def parse_concept_spec(spec_data: Any) -> ConceptSpec:- """Parse and validate a ConceptSpec from JSON-like data.-- Accepts common aliases for "concept_code" and converts structure fields.-- Args:- spec_data: Raw data for the concept spec (untrusted JSON-like input).-- Returns:- Validated ConceptSpec instance.-- Raises:- ConceptSpecError: If the top-level value is not a mapping, ``structure``- is not a mapping, a structure field value is neither a description- string nor a field-spec mapping, or a ConceptSpec-level rule fails- (e.g. ``refines`` and ``structure`` both set). Carries the INPUT- error domain.- ValidationError: If Pydantic validation of the assembled spec fails.- """- # Validate the top-level shape before iterating so a non-mapping caller input- # (scalar / list / None) surfaces as a typed, INPUT-domain ConceptSpecError- # instead of a bare TypeError / ValueError from ``dict(...)`` below. Accept any- # ``Mapping`` (not just ``dict``): the message promises "a mapping", so a- # non-``dict`` mapping (e.g. ``MappingProxyType``) must be parsed, not rejected.- if not isinstance(spec_data, Mapping):- msg = f"Concept spec must be a mapping, got {type(spec_data).__name__}"- raise ConceptSpecError(msg)-- # Normalize to a plain dict; ``dict(...)`` also copies so we never mutate the caller's mapping.- spec_data = dict(cast("Mapping[str, Any]", spec_data))-- # Accept common aliases for "concept_code"- for alias in ("the_concept_code", "code", "name", "concept_name", "concept_ref"):- if alias in spec_data:- if "concept_code" not in spec_data:- spec_data["concept_code"] = spec_data.pop(alias)- else:- spec_data.pop(alias)-- # Convert structure if present - need to add field names.- # Validate the raw shape before iterating so a malformed ``structure`` surfaces- # as a typed, INPUT-domain ConceptSpecError instead of a bare AttributeError /- # TypeError (which the caller cannot tell apart from a real programming bug).- # ``is not None`` (not truthiness) so a present-but-falsy non-mapping — ``[]`` /- # ``""`` / ``0`` / ``False`` — still hits the typed guard below instead of- # silently skipping to a bare Pydantic ValidationError; ``None`` / absent both- # mean "no structure" (the field defaults to ``None``).- if spec_data.get("structure") is not None:- structure_value = spec_data["structure"]- if not isinstance(structure_value, Mapping):- msg = f"Concept spec 'structure' must be a mapping of field names to field specs, got {type(structure_value).__name__}"- raise ConceptSpecError(msg)- structure_data = cast("Mapping[str, Any]", structure_value)- converted_structure: dict[str, Any] = {}- for field_name, field_data in structure_data.items():- if isinstance(field_data, str):- # Simple string means just description, default to text type- converted_structure[field_name] = {- "the_field_name": field_name,- "description": field_data,- "type": "text",- }- elif isinstance(field_data, Mapping):- # Full field spec — copy to avoid mutating nested caller data- field_spec_data = dict(cast("Mapping[str, Any]", field_data))- field_spec_data["the_field_name"] = field_name- # Default to "text" when agent omits the type field- if "type" not in field_spec_data:- field_spec_data["type"] = "text"- converted_structure[field_name] = field_spec_data- else:- msg = (- f"Concept spec structure field '{field_name}' must be a description string or a field-spec mapping, "- f"got {type(field_data).__name__}"- )- raise ConceptSpecError(msg)- spec_data["structure"] = converted_structure-- return ConceptSpec.model_validate(spec_data)---def structure_field_to_dict(field_spec: ConceptStructureSpec) -> dict[str, Any]:- """Convert a ConceptStructureSpec to a dictionary for TOML serialization.-- Args:- field_spec: The field specification to convert.-- Returns:- Dictionary with field properties.- """- result: dict[str, Any] = {}-- # Type is always needed unless it's just a text description- if not field_spec.type.is_text or field_spec.required or field_spec.default_value is not None:- result["type"] = field_spec.type-- result["description"] = field_spec.description-- if field_spec.required:- result["required"] = True-- if field_spec.default_value is not None:- result["default_value"] = field_spec.default_value-- if field_spec.concept_ref:- result["concept_ref"] = field_spec.concept_ref-- if field_spec.choices:- result["choices"] = field_spec.choices-- return result---def concept_spec_to_toml(concept_spec: ConceptSpec) -> str:- """Convert a ConceptSpec to TOML string format.-- Args:- concept_spec: The validated ConceptSpec to convert.-- Returns:- TOML string representation of the concept.- """- doc = tomlkit.document()-- # Create the [concept.ConceptName] section- concept_section = tomlkit.table()- concept_item_table = tomlkit.table()-- # Add description- concept_item_table.add("description", concept_spec.description)-- # Add refines if present- if concept_spec.refines:- concept_item_table.add("refines", concept_spec.refines)-- # Add structure if present- if concept_spec.structure:- structure_table = tomlkit.table()- for field_name, field_spec in concept_spec.structure.items():- field_dict = structure_field_to_dict(field_spec)- # If only description is present, use simple string format- if len(field_dict) == 1 and "description" in field_dict:- structure_table.add(field_name, field_dict["description"])- else:- inline_table = tomlkit.inline_table()- for key, value in field_dict.items():- inline_table.append(key, value)- structure_table.add(field_name, inline_table)- concept_item_table.add("structure", structure_table)-- # Build the nested structure: [concept.ConceptName]- concept_section.add(concept_spec.concept_code, concept_item_table)- doc.add("concept", concept_section)- return tomlkit.dumps(doc)diff --git a/pipelex/builder/operations/output_ops.py b/pipelex/builder/operations/output_ops.pydeleted file mode 100644index 2e5207cc3..000000000--- a/pipelex/builder/operations/output_ops.py+++ /dev/null@@ -1,45 +0,0 @@-"""Core operations for generating output JSON for pipes."""--from __future__ import annotations--import json-from typing import Any--from pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormat-from pipelex.interpreter_hub import get_required_entry_pipe-from pipelex.pipe_machinery.rendering.output_renderer import render_output-from pipelex.pipeline.validate_bundle import validate_bundle---async def build_output_for_pipe(- *,- mthds_contents: list[str],- pipe_code: str,- output_format: ConceptRepresentationFormat = ConceptRepresentationFormat.SCHEMA,-) -> dict[str, Any]:- """Generate output JSON representation for a pipe.-- Args:- mthds_contents: List of raw .mthds contents to parse and load.- pipe_code: The pipe code to generate output for.- output_format: Format to generate output in.-- Returns:- Dictionary with output representation.-- Raises:- ValidateBundleError: If bundle validation fails.- """- # validate_bundle opens a library, loads blueprints, and sets it as current.- # allow_signatures=True: rendering a pipe's output representation only needs the pipes loaded,- # not a fully runnable pipeline — an in-progress bundle with PipeSignature placeholders is fine.- await validate_bundle(mthds_contents=mthds_contents, allow_signatures=True)-- the_pipe = get_required_entry_pipe(pipe_code=pipe_code)- output_str = render_output(the_pipe, output_format=output_format)-- match output_format:- case ConceptRepresentationFormat.PYTHON:- return {"output": output_str}- case ConceptRepresentationFormat.SCHEMA | ConceptRepresentationFormat.JSON:- return json.loads(output_str) # type: ignore[no-any-return]diff --git a/pipelex/builder/operations/pipe_ops.py b/pipelex/builder/operations/pipe_ops.pydeleted file mode 100644index dd5397ec7..000000000--- a/pipelex/builder/operations/pipe_ops.py+++ /dev/null@@ -1,415 +0,0 @@-"""Core operations for pipe spec parsing and TOML generation."""--# tomlkit lacks type stubs; pydantic `model` field clashes with BaseModel namespace-# pyright: reportUnknownMemberType=false-# pyright: reportUnknownVariableType=false-# pyright: reportAttributeAccessIssue=false--from typing import Any, cast--import tomlkit-from pydantic import ValidationError-from tomlkit.items import Table--from pipelex.builder.bundle_spec import SIGNATURE_ONLY_SPEC_KEYS-from pipelex.builder.pipe.exceptions import PipeSpecError-from pipelex.builder.pipe.pipe_batch_spec import PipeBatchSpec-from pipelex.builder.pipe.pipe_compose_spec import PipeComposeSpec-from pipelex.builder.pipe.pipe_condition_spec import PipeConditionSpec-from pipelex.builder.pipe.pipe_doc_gen_spec import PipeDocGenSpec-from pipelex.builder.pipe.pipe_extract_spec import PipeExtractSpec-from pipelex.builder.pipe.pipe_func_spec import PipeFuncSpec-from pipelex.builder.pipe.pipe_img_gen_spec import PipeImgGenSpec-from pipelex.builder.pipe.pipe_judge_spec import PipeJudgeSpec-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpec-from pipelex.builder.pipe.pipe_search_spec import PipeSearchSpec-from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.builder.pipe.pipe_signature_spec import PipeSignatureSpec-from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.builder.pipe.pipe_spec_map import pipe_type_to_spec_class-from pipelex.builder.pipe.pipe_structure_spec import PipeStructureSpec-from pipelex.pipe_machinery.pipe_blueprint import (- PIPE_SIGNATURE_TYPE_TAG,- explicit_signature_tag_migration_message,- normalize_typeless_signature_section,-)--# Aliases that agents may use instead of "pipe_code". First found is promoted when canonical key is absent; extras are dropped.-_PIPE_CODE_ALIASES = ("pipe", "the_pipe_code", "code", "name", "pipe_name", "pipe_ref")--# Aliases that agents may use instead of "output". First found is promoted when canonical key is absent; extras are dropped.-_OUTPUT_ALIASES = ("output_concept", "output_type")--# Aliases that agents may use instead of "prompt". First found is promoted when canonical key is absent; extras are dropped.-_PROMPT_ALIASES = ("prompt_template",)---def _normalize_sub_pipe_dict(data: dict[str, Any]) -> None:- """Normalize a step/branch dict: resolve pipe_code aliases and drop extraneous fields."""- _normalize_pipe_code_aliases(data)- # Agents sometimes add "inputs" to individual steps — silently drop.- # Step-level inputs are not supported; inputs set by the pipe definition.- data.pop("inputs", None)---def _normalize_sub_pipe_list(raw_value: Any, *, field_name: str) -> list[dict[str, Any]]:- """Validate and normalize a raw ``steps`` / ``branches`` value into a list of step dicts.-- Each entry is copied (to avoid mutating the caller's nested dicts) and passed- through :func:`_normalize_sub_pipe_dict`. A non-list ``raw_value`` or a- non-mapping entry is a caller-input fault, raised as a typed ``PipeSpecError``- before validation rather than leaking a bare ``TypeError`` / ``ValueError``.- """- if not isinstance(raw_value, list):- msg = f"Pipe spec '{field_name}' must be a list of step mappings, got {type(raw_value).__name__}"- raise PipeSpecError(msg)- normalized: list[dict[str, Any]] = []- for entry in cast("list[Any]", raw_value):- if not isinstance(entry, dict):- msg = f"Each entry in pipe spec '{field_name}' must be a mapping, got {type(entry).__name__}"- raise PipeSpecError(msg)- entry_copy = dict(cast("dict[str, Any]", entry))- _normalize_sub_pipe_dict(entry_copy)- normalized.append(entry_copy)- return normalized---def _normalize_pipe_code_aliases(data: dict[str, Any]) -> None:- """Convert any alias of ``pipe_code`` to the canonical field name, in-place."""- for alias in _PIPE_CODE_ALIASES:- if alias in data:- if "pipe_code" not in data:- data["pipe_code"] = data.pop(alias)- else:- data.pop(alias)---def _normalize_prompt_aliases(data: dict[str, Any]) -> None:- """Convert any alias of ``prompt`` to the canonical field name, in-place."""- for alias in _PROMPT_ALIASES:- if alias in data:- if "prompt" not in data:- data["prompt"] = data.pop(alias)- else:- data.pop(alias)---def _normalize_output(data: dict[str, Any]) -> Any | None:- """Canonicalize output authoring aliases in-place: promote ``output_concept`` / ``output_type`` →- ``output``, and flatten a dict-shaped ``output`` to its concept string.-- Returns the displaced original ``output`` value when an alias overrode an existing ``output`` (so a- typed caller can retry with the alias then fall back to the original), else ``None``. Runs for both- the typeless-signature and typed paths so the same authoring conveniences apply to signatures.- """- # Accept output aliases (e.g. "output_concept", "output_type") for "output".- # When both "output" and an alias coexist, try the alias value first (agents often put- # the correct concept name in the alias), falling back to the original "output" value.- output_fallback: Any | None = None- for output_alias in _OUTPUT_ALIASES:- if output_alias not in data:- continue- alias_value = data.pop(output_alias)- if "output" not in data:- data["output"] = alias_value- else:- output_fallback = data["output"]- data["output"] = alias_value- # First alias wins — drop any remaining aliases without using them.- for remaining_alias in _OUTPUT_ALIASES:- data.pop(remaining_alias, None)- break-- # Accept output as dict → extract the concept string- # Agents sometimes structure the output like inputs (as a dict).- # Handle {"type": "ConceptName"} and single-item dicts like {"result": "Text"}.- if "output" in data and isinstance(data["output"], dict):- output_dict: dict[str, Any] = data["output"]- if "concept_ref" in output_dict:- data["output"] = output_dict["concept_ref"]- elif "type" in output_dict:- data["output"] = output_dict["type"]- elif len(output_dict) == 1:- data["output"] = next(iter(output_dict.values()))- return output_fallback---def parse_pipe_spec(spec_data: Any, *, pipe_type: str | None) -> PipeSpec:- """Parse and validate a PipeSpec from JSON-like data.-- Args:- spec_data: Raw data for the pipe spec (untrusted JSON-like input).- pipe_type: The type of pipe (e.g., "PipeLLM", "PipeSequence"), or ``None`` when the caller- supplied no type. A typeless spec is a signature when it declares only the contract- (``description``, ``inputs``, ``output``, ``signature_for``), else a teaching error. An- explicit ``"PipeSignature"`` is rejected with the migration error — a signature has no type.-- Returns:- Validated PipeSpec instance of the correct type.-- Raises:- ValueError: If the pipe type is invalid, or the retired ``"PipeSignature"`` tag is passed, or a- typeless spec declares more than the contract.- PipeSpecError: If the top-level value is not a mapping, ``steps`` /- ``branches`` is not a list, or an entry within them is not a mapping.- Carries the INPUT error domain.- ValidationError: If Pydantic validation of the assembled spec fails.- """- # Validate the top-level shape first so a non-mapping caller input (scalar / list / None) surfaces- # as a typed, INPUT-domain PipeSpecError instead of a bare TypeError / ValueError, and so the- # typeless-signature routing below can operate on a dict.- if not isinstance(spec_data, dict):- msg = f"Pipe spec must be a mapping, got {type(spec_data).__name__}"- raise PipeSpecError(msg)- # Work on a copy to avoid mutating the caller's dict.- spec_data = dict(cast("dict[str, Any]", spec_data))-- # Canonicalize pipe_code aliases up front so the typeless-signature routing and the migration- # message both see the real pipe code.- _normalize_pipe_code_aliases(spec_data)-- # Canonicalize output authoring aliases (output_concept/output_type, dict output) up front so both- # the typeless-signature path and every typed pipe see a canonical `output` — a signature keeps the- # same authoring conveniences as typed pipes. The typed path reuses the returned fallback for its- # retry-then-fall-back below; the typeless path takes the canonical value directly.- output_fallback = _normalize_output(spec_data)-- # A signature is typeless. Reject the retired explicit `type = "PipeSignature"` tag, and route a- # typeless contract-only spec to `PipeSignatureSpec` via the shared normalizer (which injects the- # internal tag, or raises the same teaching error as the bundle layer for a stray field). This- # mirrors `PipelexBundleSpec.validate_pipe_keys` for the single-pipe authoring surface.- if pipe_type == PIPE_SIGNATURE_TYPE_TAG:- raise ValueError(explicit_signature_tag_migration_message(spec_data.get("pipe_code")))- if pipe_type is None:- normalized = normalize_typeless_signature_section(- pipe_code=spec_data.get("pipe_code"), pipe_section=spec_data, allowed_keys=SIGNATURE_ONLY_SPEC_KEYS- )- return PipeSignatureSpec.model_validate(normalized)-- if pipe_type not in pipe_type_to_spec_class:- valid_types = list(pipe_type_to_spec_class.keys())- msg = f"Invalid pipe type '{pipe_type}'. Must be one of: {valid_types}"- raise ValueError(msg)-- spec_class = pipe_type_to_spec_class[pipe_type]-- # Add type to spec_data- spec_data["type"] = pipe_type-- # Accept common aliases for "prompt" (e.g. "prompt_template")- _normalize_prompt_aliases(spec_data)-- # Handle steps/branches conversion — normalize aliases and drop unknown fields.- # Deep-copy nested dicts to avoid mutating caller's nested structures.- # Validate the raw shape before iterating so a malformed ``steps`` / ``branches``- # surfaces as a typed, INPUT-domain PipeSpecError instead of a bare TypeError /- # ValueError (which the caller cannot tell apart from a real programming bug).- if "steps" in spec_data:- spec_data["steps"] = _normalize_sub_pipe_list(spec_data["steps"], field_name="steps")-- if "branches" in spec_data:- spec_data["branches"] = _normalize_sub_pipe_list(spec_data["branches"], field_name="branches")-- # Handle expression -> jinja2_expression_template for PipeCondition- if pipe_type == "PipeCondition" and "expression" in spec_data:- if "jinja2_expression_template" not in spec_data:- spec_data["jinja2_expression_template"] = spec_data.pop("expression")- else:- spec_data.pop("expression")-- # When an output alias conflicted with an existing "output" (see `_normalize_output` above), try the- # alias value first and fall back to the original value if validation fails.- if output_fallback is not None:- try:- return spec_class.model_validate(spec_data)- except ValidationError:- spec_data["output"] = output_fallback- return spec_class.model_validate(spec_data)---def add_type_specific_fields(*, pipe_spec: PipeSpec, pipe_table: Table) -> None:- """Add type-specific fields to the pipe TOML table.-- Args:- pipe_spec: The pipe spec with type-specific fields.- pipe_table: The TOML table to add fields to.- """- if isinstance(pipe_spec, PipeLLMSpec):- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)- if pipe_spec.system_prompt:- pipe_table.add("system_prompt", pipe_spec.system_prompt)- if pipe_spec.prompt:- pipe_table.add("prompt", pipe_spec.prompt)- if pipe_spec.structuring_method is not None:- pipe_table.add("structuring_method", pipe_spec.structuring_method)-- elif isinstance(pipe_spec, PipeStructureSpec):- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)-- elif isinstance(pipe_spec, PipeDocGenSpec):- pipe_table.add("format", str(pipe_spec.format))- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)- if pipe_spec.template is not None:- pipe_table.add("template", pipe_spec.template)- if pipe_spec.template_file is not None:- pipe_table.add("template_file", pipe_spec.template_file)- if pipe_spec.filename is not None:- pipe_table.add("filename", pipe_spec.filename)-- elif isinstance(pipe_spec, PipeComposeSpec):- if pipe_spec.construct_spec is not None:- # Construct mode: serialize the construct block as a nested TOML table- construct_table = tomlkit.table()- for field_name, field_value in pipe_spec.construct_spec.items():- if isinstance(field_value, dict):- field_inline = tomlkit.inline_table()- inner_dict: dict[str, Any] = field_value- for key, value in inner_dict.items():- field_inline.append(key, value)- construct_table.add(field_name, field_inline)- else:- construct_table.add(field_name, field_value)- pipe_table.add("construct", construct_table)- else:- # Template mode — guard optional fields like other pipe types do- if pipe_spec.target_format is not None:- pipe_table.add("target_format", str(pipe_spec.target_format))- if pipe_spec.template is not None:- pipe_table.add("template", pipe_spec.template)-- elif isinstance(pipe_spec, PipeSequenceSpec):- steps_array = tomlkit.array()- for step in pipe_spec.steps:- step_inline = tomlkit.inline_table()- step_inline.append("pipe", step.pipe_code)- step_inline.append("result", step.result)- if step.batch_over is not None:- step_inline.append("batch_over", step.batch_over)- if step.batch_as is not None:- step_inline.append("batch_as", step.batch_as)- steps_array.append(step_inline)- pipe_table.add("steps", steps_array)-- elif isinstance(pipe_spec, PipeParallelSpec):- pipe_table.add("add_each_output", pipe_spec.add_each_output)- branches_array = tomlkit.array()- for branch in pipe_spec.branches:- branch_inline = tomlkit.inline_table()- branch_inline.append("pipe", branch.pipe_code)- branch_inline.append("result", branch.result)- branches_array.append(branch_inline)- pipe_table.add("branches", branches_array)-- elif isinstance(pipe_spec, PipeConditionSpec):- pipe_table.add("expression", pipe_spec.jinja2_expression_template)- outcomes_table = tomlkit.inline_table()- for condition, outcome in pipe_spec.outcomes.items():- outcomes_table.append(condition, outcome)- pipe_table.add("outcomes", outcomes_table)- pipe_table.add("default_outcome", pipe_spec.default_outcome)-- elif isinstance(pipe_spec, PipeBatchSpec):- pipe_table.add("branch_pipe_code", pipe_spec.branch_pipe_code)- pipe_table.add("input_list_name", pipe_spec.input_list_name)- pipe_table.add("input_item_name", pipe_spec.input_item_name)-- elif isinstance(pipe_spec, PipeExtractSpec):- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)- if pipe_spec.max_page_images is not None:- pipe_table.add("max_page_images", pipe_spec.max_page_images)- if pipe_spec.page_views is not None:- pipe_table.add("page_views", pipe_spec.page_views)-- elif isinstance(pipe_spec, PipeSearchSpec):- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)- pipe_table.add("prompt", pipe_spec.prompt)- if pipe_spec.from_date is not None:- pipe_table.add("from_date", pipe_spec.from_date)- if pipe_spec.to_date is not None:- pipe_table.add("to_date", pipe_spec.to_date)- if pipe_spec.include_domains is not None:- pipe_table.add("include_domains", pipe_spec.include_domains)- if pipe_spec.exclude_domains is not None:- pipe_table.add("exclude_domains", pipe_spec.exclude_domains)- if pipe_spec.max_results is not None:- pipe_table.add("max_results", pipe_spec.max_results)-- elif isinstance(pipe_spec, PipeJudgeSpec):- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)- # A tool that writes a PipeJudge writes `question`, never its `prompt` synonym.- pipe_table.add("question", pipe_spec.question)- if pipe_spec.options is not None:- options_table = tomlkit.inline_table()- for option, description in pipe_spec.options.items():- options_table.append(option, description)- pipe_table.add("options", options_table)- if pipe_spec.levels is not None:- pipe_table.add("levels", pipe_spec.levels)- if pipe_spec.criteria is not None:- criteria_table = tomlkit.inline_table()- for verdict, criterion in pipe_spec.criteria.model_dump(exclude_none=True).items():- criteria_table.append(verdict, criterion)- pipe_table.add("criteria", criteria_table)- if pipe_spec.threshold is not None:- pipe_table.add("threshold", pipe_spec.threshold)-- elif isinstance(pipe_spec, PipeImgGenSpec):- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)- pipe_table.add("prompt", pipe_spec.prompt)-- elif isinstance(pipe_spec, PipeFuncSpec):- pipe_table.add("function_name", pipe_spec.function_name)-- elif isinstance(pipe_spec, PipeSignatureSpec):- # A signature is typeless, but the optional `signature_for` hint still round-trips. Mirrors- # `pipe_cmd._add_type_specific_fields` so the two TOML renderers stay faithful copies.- if pipe_spec.signature_for is not None:- pipe_table.add("signature_for", pipe_spec.signature_for)---def pipe_spec_to_toml(pipe_spec: PipeSpec) -> str:- """Convert a PipeSpec to TOML string format.-- Args:- pipe_spec: The validated PipeSpec to convert.-- Returns:- TOML string representation of the pipe.- """- doc = tomlkit.document()- pipe_item_table = tomlkit.table()-- # Add type — a signature is typeless (no type line; omitting the type IS the signature); every- # concrete pipe names its type.- if not isinstance(pipe_spec, PipeSignatureSpec):- pipe_item_table.add("type", pipe_spec.type)-- # Add description- pipe_item_table.add("description", pipe_spec.description)-- # Add inputs as inline table- if pipe_spec.inputs:- inputs_inline = tomlkit.inline_table()- for input_name, input_concept in pipe_spec.inputs.items():- inputs_inline.append(input_name, input_concept)- pipe_item_table.add("inputs", inputs_inline)-- # Add output- pipe_item_table.add("output", pipe_spec.output)-- # Add type-specific fields- add_type_specific_fields(pipe_spec=pipe_spec, pipe_table=pipe_item_table)-- # Build the nested structure: [pipe.pipe_code]- pipe_section = tomlkit.table()- pipe_section.add(pipe_spec.pipe_code, pipe_item_table)- doc.add("pipe", pipe_section)- return tomlkit.dumps(doc)diff --git a/pipelex/builder/operations/runner_code_ops.py b/pipelex/builder/operations/runner_code_ops.pydeleted file mode 100644index 418cc0694..000000000--- a/pipelex/builder/operations/runner_code_ops.py+++ /dev/null@@ -1,74 +0,0 @@-"""Core operations for generating runner code for pipes."""--from __future__ import annotations--from pipelex.builder.runner_code import generate_runner_code-from pipelex.interpreter_hub import (- clear_current_library,- get_current_library_id_or_none,- get_library_manager,- get_required_entry_pipe,- set_current_library,-)-from pipelex.mthds_parsing.parser import MthdsParser-from pipelex.pipeline.bundle_validator import BundleValidator---async def build_runner_code_for_pipe(- *,- mthds_contents: list[str],- pipe_code: str,-) -> str:- """Generate Python runner code for a pipe from .mthds contents.-- Parses and validates the contents, loads pipes, dry-runs them,- then generates runner code for the specified pipe.-- Args:- mthds_contents: List of raw .mthds contents to parse and load.- pipe_code: The pipe code to generate runner code for.-- Returns:- Generated Python runner code as a string.-- Raises:- MthdsParserError: If MTHDS content fails to parse or validate.- PipeValidationError: If pipe validation fails.- DryRunError: If dry-running the pipes fails.- """- library_manager = get_library_manager()- # Capture the caller's outer current-library so a failure can restore it instead of leaving this- # temporary library current (mirrors validate_bundle's teardown-on-failure-only).- prev_library_id = get_current_library_id_or_none()- library_id, _ = library_manager.open_library()- success = False- try:- set_current_library(library_id=library_id)-- # Parse PLX contents into bundle blueprints- blueprints = [MthdsParser.make_pipelex_bundle_blueprint(mthds_content=content) for content in mthds_contents]-- # Load pipes from the blueprints- pipes = library_manager.load_from_blueprints(library_id=library_id, blueprints=blueprints)-- # Validate (static wiring + dry run) against the open library — never tears it down, so the- # library stays loaded for generate_runner_code below (D6 inner-sweep / loaded-on-success).- await BundleValidator().validate_pipes(pipes=pipes, library_id=library_id)-- # Get the required pipe and generate runner code- pipe = get_required_entry_pipe(pipe_code)- runner_code = generate_runner_code(pipe=pipe)- success = True- return runner_code- finally:- # Loaded-on-success contract (pinned by test_validate_bundle_loaded_on_success): leave the- # library open + current so the caller can keep using it. On FAILURE this caller owns cleanup —- # restore the outer current-library FIRST (so the guarantee survives a teardown raise), then tear- # the temporary library down. set_current_library cannot take None, so route the "no outer was- # set" case through clear_current_library.- if not success:- if prev_library_id is not None:- set_current_library(library_id=prev_library_id)- else:- clear_current_library()- library_manager.teardown(library_id=library_id)diff --git a/pipelex/builder/operations/validate_ops.py b/pipelex/builder/operations/validate_ops.pydeleted file mode 100644index e8de72386..000000000--- a/pipelex/builder/operations/validate_ops.py+++ /dev/null@@ -1,242 +0,0 @@-"""Core operations for validating pipes and bundles."""--from __future__ import annotations--from typing import TYPE_CHECKING, Any--from pipelex.interpreter_hub import (- clear_current_library,- get_current_library_id_or_none,- get_library_manager,- get_required_entry_pipe,- resolve_library_dirs,- set_current_library,-)-from pipelex.pipeline.advisory_warnings import collect_advisory_warnings-from pipelex.pipeline.blueprint_selection import collect_entry_pipe_refs-from pipelex.pipeline.bundle_validator import BundleValidator-from pipelex.pipeline.execution_seams import acquire_library-from pipelex.pipeline.validate_bundle import build_validated_pipes, validate_bundle-from pipelex.pipeline.validate_bundle_translation import translate_to_validate_bundle_error--if TYPE_CHECKING:- from pathlib import Path---async def validate_all(- *,- library_dirs: list[Path] | None = None,-) -> dict[str, Any]:- """Validate all pipes in all libraries.-- Args:- library_dirs: List of library directories to search for pipe definitions.-- Returns:- Dictionary with validation results suitable for JSON serialization.-- Raises:- ValidateBundleError: If validation fails.- """- # The standalone validate-all lifecycle (D6), spelled out rather than through- # BundleValidator.acquire_and_validate so that a refusal is translated while the validated library- # is still current: the translation reads the library's pipe sources to locate an item, and a- # failure of the teardown itself must stay the fault it is rather than become a verdict. A refusal- # of the libraries while they load (the caller's own directories) or of a pipe's dry run is the- # invalid verdict, through the shared bundle-loading cascade, as on `pipelex validate --all`.- prev_library_id = get_current_library_id_or_none()- acquired_id, _ = acquire_library(- library_id="",- library_dirs=[str(library_dir) for library_dir in library_dirs] if library_dirs else None,- library_dirs_are_callers=True,- )- try:- with translate_to_validate_bundle_error():- dry_run_results = await BundleValidator().validate_current_library()- finally:- if prev_library_id is not None:- set_current_library(library_id=prev_library_id)- else:- clear_current_library()- get_library_manager().teardown(library_id=acquired_id)-- # No `pending_signatures` here by design: it is a per-bundle, top-down-build nudge ("which headers- # are still unimplemented in this bundle"), surfaced only by `validate bundle`. The validate-all- # sweep is a whole-library check, not a build step, so it makes no runnability claim to back.- return {- "success": True,- "is_valid": True,- "validated_pipes": build_validated_pipes(dry_run_results),- "total_pipes": len(dry_run_results),- }---async def validate_bundle_file(- bundle_path: Path,- *,- library_dirs: list[Path] | None = None,-) -> dict[str, Any]:- """Validate a bundle file.-- Args:- bundle_path: Path to the bundle file.- library_dirs: List of library directories to search for pipe definitions.-- Returns:- Dictionary with validation results suitable for JSON serialization.-- Raises:- ValidateBundleError: If validation fails.- """- result = await validate_bundle(mthds_file_path=bundle_path, library_dirs=library_dirs)-- # warnings is the advisory lint channel (e.g. the useless-`!` lint) — same item shape as- # validation errors, never flips the verdict. Mirrors the agent-CLI validate_bundle_core twin.- return {- "success": True,- "is_valid": True,- "bundle_path": str(bundle_path),- "validated_pipes": build_validated_pipes(result.dry_run_result),- "total_pipes": len(result.dry_run_result),- "pending_signatures": result.pending_signatures,- "is_runnable": not result.pending_signatures,- "warnings": [- warning.model_dump(exclude_none=True)- for warning in collect_advisory_warnings(pipes=result.pipes, entry_pipe_refs=collect_entry_pipe_refs(result.blueprints))- ],- }---async def validate_bundle_content(- mthds_contents: list[str],-) -> dict[str, Any]:- """Validate bundle content provided as strings.-- Args:- mthds_contents: List of raw .mthds contents to validate.-- Returns:- Dictionary with validation results including the blueprint.-- Raises:- ValidateBundleError: If validation fails.- """- validate_bundle_result = await validate_bundle(mthds_contents=mthds_contents)- blueprints = validate_bundle_result.blueprints-- return {- "success": True,- "is_valid": True,- "mthds_contents": mthds_contents,- "pipelex_bundle_blueprint": [b.model_dump(mode="json") for b in blueprints],- "validated_pipes": build_validated_pipes(validate_bundle_result.dry_run_result),- "total_pipes": len(validate_bundle_result.dry_run_result),- "pending_signatures": validate_bundle_result.pending_signatures,- "is_runnable": not validate_bundle_result.pending_signatures,- "warnings": [- warning.model_dump(exclude_none=True)- for warning in collect_advisory_warnings(pipes=validate_bundle_result.pipes, entry_pipe_refs=collect_entry_pipe_refs(blueprints))- ],- }---async def validate_pipe(- pipe_code: str,- *,- library_dirs: list[Path] | None = None,-) -> dict[str, Any]:- """Validate a single pipe.-- Args:- pipe_code: The pipe code to validate.- library_dirs: List of library directories to search for pipe definitions.-- Returns:- Dictionary with validation results suitable for JSON serialization.-- Raises:- ValidateBundleError: If validation fails.- """- library_manager = get_library_manager()- # Capture the caller's outer current-library so it can be restored after this temporary validation- # library is torn down (mirrors acquire_and_validate / validate_bundle).- prev_library_id = get_current_library_id_or_none()- library_id, _ = library_manager.open_library()- try:- set_current_library(library_id=library_id)- effective_dirs, _ = resolve_library_dirs(library_dirs)-- # A refusal of the libraries while they load, or of the pipe's dry run, is the invalid verdict,- # through the shared bundle-loading cascade, as on `pipelex validate pipe`. The lookup between- # them stays outside it: a code that names no pipe, or several, is an unresolvable target.- if effective_dirs:- with translate_to_validate_bundle_error():- library_manager.load_libraries(library_id=library_id, library_dirs=effective_dirs)-- the_pipe = get_required_entry_pipe(pipe_code=pipe_code)- with translate_to_validate_bundle_error():- dry_run_results = await BundleValidator().validate_pipes(pipes=[the_pipe], library_id=library_id)-- return {- "success": True,- "is_valid": True,- "validated_pipes": build_validated_pipes(dry_run_results),- "total_pipes": len(dry_run_results),- }- finally:- # validate_pipes is the D6 inner sweep and never tears the library down, and validate_pipe does- # not need the library after returning its results dict — so this caller owns the full lifecycle- # on BOTH paths. Restore the outer current-library FIRST (so the guarantee survives a teardown- # raise), then tear the temporary library down. set_current_library cannot take None, so route- # the "no outer was set" case through clear_current_library.- if prev_library_id is not None:- set_current_library(library_id=prev_library_id)- else:- clear_current_library()- library_manager.teardown(library_id=library_id)---async def validate_pipe_in_bundle(- *,- bundle_path: Path,- pipe_code: str,- library_dirs: list[Path] | None = None,-) -> dict[str, Any]:- """Validate a single pipe within a bundle.-- Loads the bundle's pipes into the library (so the requested pipe's dependencies resolve), then- dry-runs ONLY the requested pipe via ``dry_run_pipe_codes`` — so an unrelated unimplemented- ``PipeSignature`` or failing sibling does not block validating one implemented slice. ``validate_bundle``- raises ``EntryPipeNotFoundError`` when ``pipe_code`` is not defined in the bundle (no vacuous success).-- Args:- bundle_path: Path to the bundle file.- pipe_code: The pipe code to validate within the bundle.- library_dirs: List of library directories to search for pipe definitions.-- Returns:- Dictionary with validation results suitable for JSON serialization.-- Raises:- ValidateBundleError: If validation fails.- EntryPipeNotFoundError: If ``pipe_code`` is not defined in the bundle. The caller-supplied- selector makes it INPUT-domained; it is a ``PipeNotFoundError`` subclass, so an existing- ``except PipeNotFoundError`` still catches it.- """- result = await validate_bundle(mthds_file_path=bundle_path, library_dirs=library_dirs, dry_run_pipe_codes=[pipe_code])-- # warnings aggregates over the whole loaded bundle (the lint's cross-flow aggregation needs- # every flow, not just the sliced pipe). Mirrors the agent-CLI validate_pipe_in_bundle_core twin.- return {- "success": True,- "is_valid": True,- "bundle_path": str(bundle_path),- "validated_pipes": build_validated_pipes(result.dry_run_result),- "total_pipes": len(result.dry_run_result),- "pending_signatures": result.pending_signatures,- "is_runnable": not result.pending_signatures,- "warnings": [- warning.model_dump(exclude_none=True)- for warning in collect_advisory_warnings(pipes=result.pipes, entry_pipe_refs=collect_entry_pipe_refs(result.blueprints))- ],- }diff --git a/pipelex/builder/pipe/__init__.py b/pipelex/builder/pipe/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/pipelex/builder/pipe/exceptions.py b/pipelex/builder/pipe/exceptions.pydeleted file mode 100644index 1bb5e55a4..000000000--- a/pipelex/builder/pipe/exceptions.py+++ /dev/null@@ -1,16 +0,0 @@-from pipelex.base_exceptions import ErrorDomain, PipelexError---class PipeSpecError(PipelexError):- """Raised when a pipe spec is malformed against its authoring contract.-- Covers the raw-shape rejections in ``parse_pipe_spec`` — a non-list- ``steps`` / ``branches``, or an entry within them that is not a mapping —- surfaced before the data reaches Pydantic validation. Always describes a- fault in the caller's own input, so it classifies as ``INPUT`` and keeps its- message under STRICT disclosure. The parallel of ``ConceptSpecError`` for the- pipe authoring surface.- """-- error_domain = ErrorDomain.INPUT- _authors_caller_facing_message = Truediff --git a/pipelex/builder/pipe/pipe_batch_spec.py b/pipelex/builder/pipe/pipe_batch_spec.pydeleted file mode 100644index d977c97e2..000000000--- a/pipelex/builder/pipe/pipe_batch_spec.py+++ /dev/null@@ -1,104 +0,0 @@-from typing import TYPE_CHECKING, Literal, Self--from pydantic import Field, model_validator-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprint-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeBatchSpec(PipeSpec):- """Spec for batch processing pipe operations concurrently.-- PipeBatch enables concurrent execution of the same pipe applied to multiple items- provided as an input list. Each item is processed independently. The result is a list- the results of each branch. So this like a map operation.-- Validation Rules:- - There must be at least one input which is a list, corresponding to input_list_name.- That name is typically a plural noun like "ideas" or "images".- And the concept corresponding to that input list must be multiple, using the [] notation,- i.e. something like "Ideas[]" or "Images[]".- - input_item_name is typically the singular noun corresponding to the items in the list, like "idea" or "image".- - input_item_name must NOT be the same as input_list_name.- - input_item_name must NOT match any key in the inputs dict.-- """-- type: Literal["PipeBatch"] = "PipeBatch"- pipe_category: Literal["PipeController"] = "PipeController"- branch_pipe_code: str = Field(- description="The pipe code to execute for each item in the input list. This pipe is instantiated once per item in parallel."- )- input_list_name: str = Field(- description=(- "Name of the list in WorkingMemory to iterate over. "- "Typically a plural noun (e.g., 'items', 'reports'). "- "Must match one of the keys in the inputs dict."- ),- )- input_item_name: str = Field(- description=(- "Name assigned to individual items within each execution branch. "- "Typically the singular form of input_list_name (e.g., 'item', 'report'). "- "Must NOT be the same as input_list_name or any key in the inputs dict."- ),- )-- @model_validator(mode="after")- def validate_input_names(self) -> Self:- """Validate that input_item_name does not collide with input_list_name or inputs keys."""- if self.input_item_name == self.input_list_name:- msg = (- f"input_item_name '{self.input_item_name}' must not be the same as input_list_name "- f"'{self.input_list_name}'. The list name should be plural (e.g., 'reports') and "- f"the item name should be the singular form (e.g., 'report')."- )- raise ValueError(msg)- if self.inputs and self.input_item_name in self.inputs:- msg = (- f"input_item_name '{self.input_item_name}' must not be the same as any key in inputs "- f"(found in: {list(self.inputs.keys())}). "- f"The input_item_name is injected into the branch pipe for each iteration "- f"and must be distinct from the batch pipe's own input names. "- f"Use the singular form of the list name (e.g., 'reports' → 'report')."- )- raise ValueError(msg)- return self-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.text import Text-- # Get base pipe information from parent- base_group = super().rendered_pretty(title=title, depth=depth)-- # Create a group combining base info with batch-specific details- batch_group = Group()- batch_group.renderables.append(base_group)-- # Add batch-specific information- batch_group.renderables.append(Text()) # Blank line- batch_group.renderables.append(Text.from_markup(f"Branch Pipe: [red]{self.branch_pipe_code}[/red]"))- batch_group.renderables.append(Text.from_markup(f"Iterate Over: [bold cyan]{self.input_list_name}[/bold cyan]"))- batch_group.renderables.append(Text.from_markup(f"Item Name: [cyan]{self.input_item_name}[/cyan]"))-- return batch_group-- @override- def to_blueprint(self) -> PipeBatchBlueprint:- base_blueprint = super().to_blueprint()- return PipeBatchBlueprint(- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- branch_pipe_code=self.branch_pipe_code,- input_list_name=self.input_list_name,- input_item_name=self.input_item_name,- )diff --git a/pipelex/builder/pipe/pipe_compose_spec.py b/pipelex/builder/pipe/pipe_compose_spec.pydeleted file mode 100644index 94cdf95db..000000000--- a/pipelex/builder/pipe/pipe_compose_spec.py+++ /dev/null@@ -1,253 +0,0 @@-from enum import StrEnum-from typing import TYPE_CHECKING, Any, Literal, Self--from pydantic import ConfigDict, Field, field_validator, model_validator-from pydantic.json_schema import SkipJsonSchema-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.cogt.templating.template_blueprint import TemplateBlueprint-from pipelex.pipe_operators.compose.pipe_compose_blueprint import PipeComposeBlueprint-from pipelex.tools.jinja2.template_category import TemplateCategory-from pipelex.tools.misc.pretty import require_rich_for_rendering-from pipelex.tools.templating.templating_style import TagStyle, TemplatingStyle-from pipelex.tools.templating.text_format import TextFormat--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class TargetFormat(StrEnum):- PLAIN = "plain"- MARKDOWN = "markdown"- HTML = "html"- JSON = "json"- MERMAID = "mermaid"-- @property- def tag_style(self) -> TagStyle:- match self:- case TargetFormat.PLAIN:- return TagStyle.NO_TAG- case TargetFormat.MARKDOWN:- return TagStyle.TICKS- case TargetFormat.HTML:- return TagStyle.XML- case TargetFormat.JSON:- return TagStyle.SQUARE_BRACKETS- case TargetFormat.MERMAID:- return TagStyle.NO_TAG-- @property- def text_format(self) -> TextFormat:- match self:- case TargetFormat.PLAIN:- return TextFormat.PLAIN- case TargetFormat.MARKDOWN:- return TextFormat.MARKDOWN- case TargetFormat.HTML:- return TextFormat.HTML- case TargetFormat.JSON:- return TextFormat.JSON- case TargetFormat.MERMAID:- return TextFormat.PLAIN-- @property- def templating_style(self) -> TemplatingStyle:- return TemplatingStyle(tag_style=self.tag_style, text_format=self.text_format)-- @property- def category(self) -> TemplateCategory:- match self:- case TargetFormat.PLAIN:- return TemplateCategory.MARKDOWN- case TargetFormat.MARKDOWN:- return TemplateCategory.MARKDOWN- case TargetFormat.HTML:- return TemplateCategory.HTML- case TargetFormat.JSON:- return TemplateCategory.HTML- case TargetFormat.MERMAID:- return TemplateCategory.MERMAID---class PipeComposeSpec(PipeSpec):- """PipeComposeSpec defines a composition operation.-- Two modes are supported:-- **Template mode** (for Text/Html output):- - Renders a template to produce formatted text- - Use Pipelex pre-processor syntax:- - `@variable` renders an entire object with all attributes auto-formatted —- **must be alone on its own line** (leading/trailing whitespace is allowed- and preserved). Inline `@variable` raises a load-time `TemplateSigilSyntaxError`.- - `$variable.field` for inline field access (e.g., "Order #$order.id")- - Only use `{{ variable.field }}` for isolated single-field access- - Escape with `@@` or `$$` to emit a literal `@` or `$` without interpolation- (e.g., `$$10` for a literal dollar amount before a word). Inline CSS at-rules- like `@media`, `@font-face`, `@keyframes`, and code decorators like `@deprecated`- already pass through silently — they only need `@@` if their keyword happens to- match one of this pipe's declared inputs.- - NEVER manually list all attributes - use `@variable` (on its own line) instead-- **Construct mode** (for StructuredContent output):- - Assembles a structured object from working memory variables- - PREFER `{ from = "variable" }` for direct object/value assignment- - Use `{ template = "..." }` ONLY for string composition (e.g., "INV-$order.id")- - NEVER use templates to manually replicate object attributes- """-- model_config = ConfigDict(populate_by_name=True)-- type: SkipJsonSchema[Literal["PipeCompose"]] = "PipeCompose"- pipe_category: SkipJsonSchema[Literal["PipeOperator"]] = "PipeOperator"-- # Template mode fields- template: str | None = Field(- default=None,- description=(- "Template string using Pipelex pre-processor syntax: "- "use @variable (alone on its own line) to render entire objects with auto-formatting, "- "$variable.field for inline access. "- "NEVER manually list all attributes of an object - use @variable instead."- ),- )- target_format: TargetFormat | str | None = Field(- default=None, description="Target format for the output (template mode)", examples=list(TargetFormat)- )-- # Construct mode field- # Note: Named 'construct_spec' to avoid conflict with Pydantic's BaseModel.construct() method- # Accepts both 'construct' and 'construct_spec' as input names (see normalize_construct_field validator)- # mock_format: "ignore" ensures dry run factory only generates template mode (to avoid mutual exclusivity conflict)- construct_spec: dict[str, Any] | None = Field(- default=None,- validation_alias="construct",- description=(- "Field composition spec mapping field names to values. "- "PREFER { from = 'variable' } for direct object assignment. "- "Use { template = '...' } ONLY for string composition like 'INV-$order.id'. "- "NEVER use templates to manually replicate object attributes."- ),- json_schema_extra={"mock_format": "ignore"},- )-- @model_validator(mode="before")- @classmethod- def normalize_construct_field(cls, values: dict[str, Any]) -> dict[str, Any]:- """Accept both 'construct_spec' and 'construct' as input field names.-- The LLM may generate either name, so we normalize 'construct_spec' to 'construct'- which is the validation_alias that Pydantic expects.- """- if "construct_spec" in values and "construct" not in values:- values["construct"] = values.pop("construct_spec")- return values-- @field_validator("target_format", mode="before")- @classmethod- def validate_target_format(cls, target_format_value: str | None) -> TargetFormat | None:- if target_format_value is None:- return None- return TargetFormat(target_format_value)-- @model_validator(mode="after")- def validate_mode_exclusivity(self) -> Self:- """Validate that exactly one mode is used."""- has_template = self.template is not None- has_construct = self.construct_spec is not None-- if not has_template and not has_construct:- msg = "PipeComposeSpec requires either 'template' or 'construct' to be provided"- raise ValueError(msg)- if has_template and has_construct:- msg = "PipeComposeSpec cannot have both 'template' and 'construct' - use one or the other"- raise ValueError(msg)- if has_template and self.target_format is None:- msg = "Template mode requires 'target_format' to be specified"- raise ValueError(msg)- return self-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.panel import Panel- from rich.text import Text-- # Get base pipe information from parent- base_group = super().rendered_pretty(title=title, depth=depth)-- # Create a group combining base info with compose-specific details- compose_group = Group()- compose_group.renderables.append(base_group)-- if self.construct_spec is not None:- # Construct mode- compose_group.renderables.append(Text()) # Blank line- compose_group.renderables.append(Text.from_markup("[bold cyan]Mode:[/bold cyan] Construct"))- construct_panel = Panel(- str(self.construct_spec),- title="Construct",- title_align="left",- border_style="cyan",- padding=(0, 1),- )- compose_group.renderables.append(construct_panel)- else:- # Template mode- compose_group.renderables.append(Text()) # Blank line- compose_group.renderables.append(Text.from_markup(f"Target Format: [bold yellow]{self.target_format}[/bold yellow]"))-- # Add template in a panel- compose_group.renderables.append(Text()) # Blank line- template_panel = Panel(- self.template or "",- title="Template",- title_align="left",- border_style="green",- padding=(0, 1),- )- compose_group.renderables.append(template_panel)-- return compose_group-- @override- def to_blueprint(self) -> PipeComposeBlueprint:- base_blueprint = super().to_blueprint()-- if self.construct_spec is not None:- # Construct mode: pass the raw construct dict via model_validate- # The PipeComposeBlueprint's model_validator expects 'construct' key in raw dict- return PipeComposeBlueprint.model_validate(- {- "description": base_blueprint.description,- "inputs": base_blueprint.inputs_concept_specs,- "output": base_blueprint.output,- "construct": self.construct_spec,- }- )- elif self.template is not None:- # Template mode - target_format is guaranteed non-None by model validator- assert self.target_format is not None- target_format = TargetFormat(self.target_format)- templating_style = target_format.templating_style- category = target_format.category-- template_blueprint = TemplateBlueprint(- template=self.template,- templating_style=templating_style,- category=category,- extra_context=None,- )-- return PipeComposeBlueprint(- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- template=template_blueprint,- )- else:- msg = "PipeComposeSpec must have either 'template' or 'construct' to be provided"- raise ValueError(msg)diff --git a/pipelex/builder/pipe/pipe_condition_spec.py b/pipelex/builder/pipe/pipe_condition_spec.pydeleted file mode 100644index 11ceb4402..000000000--- a/pipelex/builder/pipe/pipe_condition_spec.py+++ /dev/null@@ -1,99 +0,0 @@-from typing import TYPE_CHECKING, Literal--from pydantic import Field-from pydantic.json_schema import SkipJsonSchema-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprint-from pipelex.pipe_controllers.condition.special_outcome import SpecialOutcome-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeConditionSpec(PipeSpec):- """PipeConditionSpec enables branching logic in pipelines by evaluating expressions- and executing different pipes based on the results.-- Validation Rules:- 1. Either expression or expression_template should be provided, not both.- 2. outcomes map keys, must be strings representing possible valmes from expression.- 3. All values in outcomes map and default_outcome must be either valid pipe_code references or special outcomes "fail" or "continue".-- """-- type: SkipJsonSchema[Literal["PipeCondition"]] = "PipeCondition"- pipe_category: SkipJsonSchema[Literal["PipeController"]] = "PipeController"- jinja2_expression_template: str = Field(description="Jinja2 expression to evaluate.")- outcomes: dict[str, str] = Field(..., description="Mapping `dict[str, str]` of condition to outcomes.")- default_outcome: str | SpecialOutcome = Field(description="The fallback outcome if the expression result does not match any key in outcome map.")-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.panel import Panel- from rich.table import Table- from rich.text import Text-- # Get base pipe information from parent- base_group = super().rendered_pretty(title=title, depth=depth)-- # Create a group combining base info with condition-specific details- condition_group = Group()- condition_group.renderables.append(base_group)-- # Add expression template in a panel- condition_group.renderables.append(Text()) # Blank line- expression_panel = Panel(- self.jinja2_expression_template,- title="Expression Template",- title_align="left",- border_style="yellow",- padding=(0, 1),- )- condition_group.renderables.append(expression_panel)-- # Add outcomes as a table- condition_group.renderables.append(Text()) # Blank line- outcomes_table = Table(- title="Outcomes:",- title_justify="left",- title_style="not italic",- show_header=True,- header_style="dim",- show_edge=True,- show_lines=True,- border_style="dim",- )- outcomes_table.add_column("Condition", style="yellow")- outcomes_table.add_column("Pipe", style="cyan")-- for condition, pipe in self.outcomes.items():- outcomes_table.add_row(condition, pipe)-- condition_group.renderables.append(outcomes_table)-- # Add default outcome- condition_group.renderables.append(Text()) # Blank line- condition_group.renderables.append(Text.from_markup(f"Default Outcome: [bold red]{self.default_outcome}[/bold red]"))-- return condition_group-- @override- def to_blueprint(self) -> PipeConditionBlueprint:- base_blueprint = super().to_blueprint()- return PipeConditionBlueprint(- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- type=self.type,- pipe_category=self.pipe_category,- expression_template=self.jinja2_expression_template,- expression=None,- outcomes=self.outcomes,- default_outcome=self.default_outcome,- add_alias_from_expression_to=None,- )diff --git a/pipelex/builder/pipe/pipe_doc_gen_spec.py b/pipelex/builder/pipe/pipe_doc_gen_spec.pydeleted file mode 100644index d598ea3e4..000000000--- a/pipelex/builder/pipe/pipe_doc_gen_spec.py+++ /dev/null@@ -1,95 +0,0 @@-from typing import TYPE_CHECKING, Literal--from pydantic import Field, field_validator-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat-from pipelex.pipe_operators.doc_gen.pipe_doc_gen_blueprint import PipeDocGenBlueprint-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeDocGenSpec(PipeSpec):- """Spec for the PipeDocGen operator, which generates a document file from its inputs and calls no AI model.-- With no template, it lays the inputs out by itself: a `pdf` step without a template is what open Pipelex- prints, on its `reportlab-pdf` engine, and a `Markdown` input comes out formatted. A `pdf` with an HTML- template, and the `xlsx`, `docx` and `pptx` formats, need the Pipelex document generation plugin, and a- runtime without it refuses them when the method loads. `model` names the engine; without it, the model- deck's default for the format prints the file.-- Validation Rules:- - the output must be a single Document, or a concept refining Document.- - `template` (inline HTML and Jinja2) is for `pdf` only; `template_file` names a file beside the bundle- whose suffix matches the format (`.html`, `.xlsx`, `.docx`, `.pptx`); never both.- - `pptx` needs a `template_file`.- """-- type: Literal["PipeDocGen"] = "PipeDocGen"- pipe_category: Literal["PipeOperator"] = "PipeOperator"- format: DocGenFormat = Field(strict=False, description="The file format to generate: pdf, xlsx, docx or pptx.")- model: str | None = Field(- default=None,- description=(- "The document engine that prints the file, a doc_gen model such as 'reportlab-pdf' or, "- "with the document generation plugin, 'pipelex-pdf'. Omit it for the model deck's default for the format."- ),- )- template: str | None = Field(- default=None,- description="An inline HTML and Jinja2 template, for pdf only. Omit it for the auto-layout of the inputs.",- )- template_file: str | None = Field(- default=None,- description="A template file beside the bundle, relative to its file: .html for pdf, .xlsx, .docx or .pptx.",- )- filename: str | None = Field(- default=None,- description="A Jinja expression over the inputs for the file's name, without its suffix, such as 'invoice-{{ invoice.number }}'.",- )-- @field_validator("model", mode="before")- @classmethod- def reject_empty_model(cls, value: str | None) -> str | None:- if isinstance(value, str) and not value.strip():- msg = "Model cannot be an empty string; omit the field to use the default engine"- raise ValueError(msg)- return value-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.markup import escape- from rich.text import Text-- base_group = super().rendered_pretty(title=title, depth=depth)-- doc_gen_group = Group()- doc_gen_group.renderables.append(base_group)-- doc_gen_group.renderables.append(Text()) # Blank line- doc_gen_group.renderables.append(Text.from_markup(f"Format: [bold yellow]{escape(self.format)}[/bold yellow]"))- doc_gen_group.renderables.append(Text.from_markup(f"Model: [bold yellow]{escape(self.model or '(default)')}[/bold yellow]"))- if self.template_file is not None:- doc_gen_group.renderables.append(Text.from_markup(f"Template file: [bold]{escape(self.template_file)}[/bold]"))-- return doc_gen_group-- @override- def to_blueprint(self) -> PipeDocGenBlueprint:- base_blueprint = super().to_blueprint()-- return PipeDocGenBlueprint(- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- format=self.format,- model=self.model,- template=self.template,- template_file=self.template_file,- filename=self.filename,- )diff --git a/pipelex/builder/pipe/pipe_extract_spec.py b/pipelex/builder/pipe/pipe_extract_spec.pydeleted file mode 100644index b0966ee6b..000000000--- a/pipelex/builder/pipe/pipe_extract_spec.py+++ /dev/null@@ -1,113 +0,0 @@-from typing import TYPE_CHECKING, Literal--from pydantic import Field, field_validator-from pydantic.json_schema import SkipJsonSchema-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.cogt.content_generation.dry_run_factory import MockFormat-from pipelex.pipe_operators.extract.pipe_extract_blueprint import PipeExtractBlueprint-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeExtractSpec(PipeSpec):- """Spec for OCR (Optical Character Recognition) pipe operations in the Pipelex framework.-- PipeExtract enables text extraction from images and documents using OCR technology.- Supports various OCR platforms and output configurations including image detection,- caption generation, and page rendering.-- Validation Rules:- - inputs dict must have exactly one input entry, and the value must be either `Image` or `Document` (a PDF is a document).- - output must be "Page"- """-- type: SkipJsonSchema[Literal["PipeExtract"]] = "PipeExtract"- pipe_category: SkipJsonSchema[Literal["PipeOperator"]] = "PipeOperator"- inputs: dict[str, str] = Field(- description=(- "Input specifications mapping variable names to concept codes. "- "PipeExtract must have exactly one input which must be either `Image` or `Document` (a PDF is a document)."- ),- json_schema_extra={"mock_format": MockFormat.DICT_SINGLE_EXTRACT_INPUT},- )- model: str | None = Field(- default=None,- description="Model preset, alias, waterfall, or direct model handle. Use presets from 'pipelex-agent models'.",- )- max_page_images: int | None = Field(- default=None, description="Max number of images to extract from pages: None=unlimited, 0=no images, N=limit to N images."- )- page_views: bool | None = Field(default=None, description="Whether to include rendered page views in the output.")-- @field_validator("model", mode="before")- @classmethod- def reject_empty_model(cls, value: str | None) -> str | None:- if isinstance(value, str) and not value.strip():- msg = "Model cannot be an empty string; omit the field to use defaults"- raise ValueError(msg)- return value-- @override- @field_validator("output", mode="before")- @classmethod- def validate_output(cls, output: str) -> str:- return "Page[]"-- @field_validator("inputs", mode="before")- @classmethod- def validate_extract_inputs(cls, inputs_value: dict[str, str] | None) -> dict[str, str] | None:- if inputs_value is None:- msg = "PipeExtract must have exactly one input which must be either `Image` or `Document` (a PDF is a document)."- raise ValueError(msg)- if len(inputs_value) != 1:- msg = "PipeExtract must have exactly one input which must be either `Image` or `Document` (a PDF is a document)."- raise ValueError(msg)- return inputs_value-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.markup import escape- from rich.text import Text-- # Get base pipe information from parent- base_group = super().rendered_pretty(title=title, depth=depth)-- # Create a group combining base info with extract-specific details- extract_group = Group()- extract_group.renderables.append(base_group)-- # Add extract specific information- extract_group.renderables.append(Text()) # Blank line- extract_group.renderables.append(Text.from_markup(f"Model: [bold yellow]{escape(self.model or '(default)')}[/bold yellow]"))-- # Add optional extraction settings if they are set- if self.max_page_images is not None:- extract_group.renderables.append(Text.from_markup(f"Max Page Images: [bold magenta]{self.max_page_images}[/bold magenta]"))- if self.page_views is not None:- extract_group.renderables.append(Text.from_markup(f"Include Page Views: [bold magenta]{self.page_views}[/bold magenta]"))-- return extract_group-- @override- def to_blueprint(self) -> PipeExtractBlueprint:- base_blueprint = super().to_blueprint()-- return PipeExtractBlueprint(- source=None,- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- model=self.model,- max_page_images=self.max_page_images,- page_image_captions=None,- page_views=self.page_views,- page_views_dpi=None,- render_js=None,- include_raw_html=None,- )diff --git a/pipelex/builder/pipe/pipe_func_spec.py b/pipelex/builder/pipe/pipe_func_spec.pydeleted file mode 100644index eb7629d58..000000000--- a/pipelex/builder/pipe/pipe_func_spec.py+++ /dev/null@@ -1,49 +0,0 @@-from typing import TYPE_CHECKING, Literal--from pydantic import Field-from pydantic.json_schema import SkipJsonSchema-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.pipe_operators.func.pipe_func_blueprint import PipeFuncBlueprint-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeFuncSpec(PipeSpec):- """PipeFunc enables calling custom functions in the Pipelex framework."""-- type: SkipJsonSchema[Literal["PipeFunc"]] = "PipeFunc"- pipe_category: SkipJsonSchema[Literal["PipeOperator"]] = "PipeOperator"- function_name: str = Field(description="The name of the function to call.")-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.text import Text-- # Get base pipe information from parent- base_group = super().rendered_pretty(title=title, depth=depth)-- # Create a group combining base info with func-specific details- func_group = Group()- func_group.renderables.append(base_group)-- # Add function specific information- func_group.renderables.append(Text()) # Blank line- func_group.renderables.append(Text.from_markup(f"Function Name: [bold cyan]{self.function_name}[/bold cyan]"))-- return func_group-- @override- def to_blueprint(self) -> PipeFuncBlueprint:- base_blueprint = super().to_blueprint()- return PipeFuncBlueprint(- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- function_name=self.function_name,- )diff --git a/pipelex/builder/pipe/pipe_img_gen_spec.py b/pipelex/builder/pipe/pipe_img_gen_spec.pydeleted file mode 100644index 3409d94c3..000000000--- a/pipelex/builder/pipe/pipe_img_gen_spec.py+++ /dev/null@@ -1,88 +0,0 @@-from typing import TYPE_CHECKING, Literal--from pydantic import Field, field_validator-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.cogt.img_gen.img_gen_job_components import ImgGenSize-from pipelex.pipe_operators.img_gen.pipe_img_gen_blueprint import PipeImgGenBlueprint-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeImgGenSpec(PipeSpec):- """Specs for image generation pipe operations in the Pipelex framework.-- PipeImgGen enables AI-powered image generation using various models like DALL-E or- diffusion models. Supports static and dynamic prompts with configurable generation- parameters.-- Output Multiplicity:- Specify using bracket notation in output field:- - output = "Image" - single image (default)- - output = "Image[3]" - exactly 3 images- """-- type: Literal["PipeImgGen"] = "PipeImgGen"- pipe_category: Literal["PipeOperator"] = "PipeOperator"- model: str | None = Field(- default=None,- description="Model preset, alias, waterfall, or direct model handle. Use presets from 'pipelex-agent models'.",- )- prompt: str = Field(description="A finalized image generation prompt or prompt template: use `$` prefix for inline variables (e.g., `$topic`).")- size: ImgGenSize | None = Field(- default=None,- description=(- "Image size intent: a portable tier ('1k', '2k', '4k'; '0.5k' is reserved and not yet supported by any model) "- "or exact pixels like '2048x1152' (an exact size implies the aspect ratio). Omit to use the provider default."- ),- )-- @field_validator("model", mode="before")- @classmethod- def reject_empty_model(cls, value: str | None) -> str | None:- if isinstance(value, str) and not value.strip():- msg = "Model cannot be an empty string; omit the field to use defaults"- raise ValueError(msg)- return value-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.markup import escape- from rich.text import Text-- # Get base pipe information from parent- base_group = super().rendered_pretty(title=title, depth=depth)-- # Create a group combining base info with img_gen-specific details- img_gen_group = Group()- img_gen_group.renderables.append(base_group)-- # Add image generation specific information- img_gen_group.renderables.append(Text()) # Blank line- img_gen_group.renderables.append(Text.from_markup(f"Model: [bold yellow]{escape(self.model or '(default)')}[/bold yellow]"))-- return img_gen_group-- @override- def to_blueprint(self) -> PipeImgGenBlueprint:- """Convert this PipeImgGenSpec to the core PipeImgGenBlueprint."""- base_blueprint = super().to_blueprint()-- return PipeImgGenBlueprint(- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- prompt=self.prompt,- model=self.model,- size=self.size,- aspect_ratio=None,- background=None,- output_format=None,- is_raw=None,- seed=None,- )diff --git a/pipelex/builder/pipe/pipe_judge_spec.py b/pipelex/builder/pipe/pipe_judge_spec.pydeleted file mode 100644index 8bd9c2aa1..000000000--- a/pipelex/builder/pipe/pipe_judge_spec.py+++ /dev/null@@ -1,108 +0,0 @@-from typing import TYPE_CHECKING, Any, Literal--from pydantic import Field, field_validator, model_validator-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.pipe_operators.judge.pipe_judge_blueprint import JudgeYesNoCriteria, PipeJudgeBlueprint, read_prompt_as_question-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeJudgeSpec(PipeSpec):- """Specs for judgment pipe operations in the Pipelex framework.-- PipeJudge asks a judging model one closed question about its inputs. Declare `options` for a- choice, `levels` for a rating, or neither for a yes/no question, which may carry `criteria` and a- `threshold`. Every input is material to judge, so the question need not name them.- """-- type: Literal["PipeJudge"] = "PipeJudge"- pipe_category: Literal["PipeOperator"] = "PipeOperator"- model: str | None = Field(- default=None,- description=(- "Judgment model preset, alias, waterfall, or direct model handle. Use presets from 'pipelex-agent models'. "- "Required unless the deck names a default judgment model (`choice_default` under `[judgment]`), which the shipped deck does not."- ),- )- question: str = Field(- description="The one closed question to ask about the inputs: use `$` prefix for an inline parameter (e.g., `Is it about $topic?`).",- )- options: dict[str, str] | None = Field(- default=None,- description="For a choice question: each key is an option, each value describes it as a concrete situation (an empty string for none).",- )- levels: list[str] | None = Field(- default=None,- description="For a rating question: the levels from lowest to highest, each describing a situation rather than a degree.",- )- criteria: JudgeYesNoCriteria | None = Field(default=None, description="For a yes/no question: what a yes and what a no mean.")- threshold: float | None = Field(- default=None,- description="For a yes/no question: the probability of yes at or above which the verdict is yes, strictly between 0 and 1.",- )-- @field_validator("model", mode="before")- @classmethod- def reject_empty_model(cls, value: str | None) -> str | None:- if isinstance(value, str) and not value.strip():- msg = "Model cannot be an empty string: name a judgment model, or omit the field only when the deck names a default one"- raise ValueError(msg)- return value-- @model_validator(mode="before")- @classmethod- def read_prompt_synonym(cls, values: dict[str, Any]) -> dict[str, Any]:- """Accept `prompt` for `question`, the spelling every other inference operator uses, as the blueprint does."""- return read_prompt_as_question(values=values)-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.markup import escape- from rich.panel import Panel- from rich.text import Text-- judge_group = Group()- judge_group.renderables.append(super().rendered_pretty(title=title, depth=depth))- judge_group.renderables.append(Text())- judge_group.renderables.append(Text.from_markup(f"Model: [bold yellow]{escape(self.model or '(default)')}[/bold yellow]"))- judge_group.renderables.append(Text())- judge_group.renderables.append(Panel(Text(self.question), title="Question", title_align="left", border_style="cyan", padding=(0, 1)))- detail_lines: list[str] = []- if self.options is not None:- detail_lines.extend(f"Option {key}: {description}" if description else f"Option {key}" for key, description in self.options.items())- if self.levels is not None:- detail_lines.extend(f"Level {index}: {level}" for index, level in enumerate(self.levels))- if self.criteria is not None:- if self.criteria.yes is not None:- detail_lines.append(f"Yes means: {self.criteria.yes}")- if self.criteria.no is not None:- detail_lines.append(f"No means: {self.criteria.no}")- if self.threshold is not None:- detail_lines.append(f"Threshold: {self.threshold}")- if detail_lines:- judge_group.renderables.append(Text())- for detail_line in detail_lines:- judge_group.renderables.append(Text(detail_line, style="dim"))- return judge_group-- @override- def to_blueprint(self) -> PipeJudgeBlueprint:- """Convert this PipeJudgeSpec to the core PipeJudgeBlueprint."""- base_blueprint = super().to_blueprint()- return PipeJudgeBlueprint(- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- question=self.question,- model=self.model,- options=self.options,- levels=self.levels,- criteria=self.criteria,- threshold=self.threshold,- )diff --git a/pipelex/builder/pipe/pipe_llm_spec.py b/pipelex/builder/pipe/pipe_llm_spec.pydeleted file mode 100644index 96c887e4d..000000000--- a/pipelex/builder/pipe/pipe_llm_spec.py+++ /dev/null@@ -1,144 +0,0 @@-from typing import TYPE_CHECKING, Literal--from pydantic import Field, field_validator-from pydantic.json_schema import SkipJsonSchema-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint, StructuringMethod-from pipelex.tools.misc.pretty import require_rich_for_rendering-from pipelex.tools.templating.templating_style import TagStyle, TemplatingStyle--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeLLMSpec(PipeSpec):- """Spec for LLM-based pipe operations in the Pipelex framework.-- PipeLLM enables Large Language Model processing to generate text or structured output.- Supports text, structured data, and image inputs.-- Output Multiplicity:- Specify using bracket notation in output field:- - output = "Text" - single item (default)- - output = "Text[]" - variable list- - output = "Text[3]" - exactly 3 items-- """-- type: SkipJsonSchema[Literal["PipeLLM"]] = "PipeLLM"- pipe_category: SkipJsonSchema[Literal["PipeOperator"]] = "PipeOperator"- model: str | None = Field(- default=None,- description="Model preset, alias, waterfall, or direct model handle. Use presets from 'pipelex-agent models'.",- )- system_prompt: str | None = Field(default=None, description="A system prompt to guide the LLM's behavior, style and skills. Can be a template.")- structuring_method: StructuringMethod | None = Field(- default=None,- description=(- "Build-time directive that controls how the structured output is produced. "- "Default (None or 'direct'): a single LLM call produces the structured output directly. "- "'preliminary_text': the bundle elaborator splits this pipe into a PipeSequence of "- "[PipeLLM(text), PipeStructure], so the LLM first drafts a free-form text and a second "- "call structures it. Useful when reasoning is easier in prose than in JSON. "- "Cannot be combined with a Text output."- ),- )- prompt: str | None = Field(- default=None,- description="""A template for the user prompt:-Use `$` prefix for inline variables (e.g., `$topic`) and `@` prefix to insert content as a block with delimiters-For example, `@extracted_text` will generate this:-extracted_text: ```-[the extracted_text goes here]-```-so you don't need to write the delimiters yourself.--**Notes**:-• Image variables must be inserted too.-They can be simply added with the `$` prefix on a line, e.g. `$image_1`.-Or you can mention them by their number in order in the inputs section, starting from 1.-Example: `Only analyze the colors from $image_1 and the shapes from $image_2.-• If we are generating a structured concept, DO NOT detail the structure in the prompt: we will add the schema later.-So, don't have to write a bullet-list of all the attributes definitions yourself.-""",- )-- templating_style: TagStyle | TemplatingStyle | None = Field(- default=None,- description=(- "How this pipe's inputs are tagged into the prompt. A bare string names the tag style "- "('xml', 'ticks', 'square_brackets', 'no_tag'); an inline table sets both tag style and "- 'text format, e.g. { tag_style = "xml", text_format = "markdown" }. Omit to use the '- "runtime default."- ),- )-- @field_validator("model", mode="before")- @classmethod- def reject_empty_model(cls, value: str | None) -> str | None:- if isinstance(value, str) and not value.strip():- msg = "Model cannot be an empty string; omit the field to use defaults"- raise ValueError(msg)- return value-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.markup import escape- from rich.panel import Panel- from rich.text import Text-- # Get base pipe information from parent- base_group = super().rendered_pretty(title=title, depth=depth)-- # Create a group combining base info with LLM-specific details- llm_group = Group()- llm_group.renderables.append(base_group)-- # Add LLM-specific information- llm_group.renderables.append(Text()) # Blank line- llm_group.renderables.append(Text.from_markup(f"Model: [bold yellow]{escape(self.model or '(default)')}[/bold yellow]"))-- # Add system prompt if present- if self.system_prompt:- system_prompt_panel = Panel(- self.system_prompt,- title="System Prompt",- title_align="left",- border_style="blue",- padding=(0, 1),- )- llm_group.renderables.append(Text()) # Blank line- llm_group.renderables.append(system_prompt_panel)-- # Add prompt if present- if self.prompt:- prompt_panel = Panel(- self.prompt,- title="Prompt",- title_align="left",- border_style="green",- padding=(0, 1),- )- llm_group.renderables.append(Text()) # Blank line- llm_group.renderables.append(prompt_panel)-- return llm_group-- @override- def to_blueprint(self) -> PipeLLMBlueprint:- base_blueprint = super().to_blueprint()-- return PipeLLMBlueprint(- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- system_prompt=self.system_prompt,- prompt=self.prompt,- model=self.model,- structuring_method=self.structuring_method,- templating_style=self.templating_style,- )diff --git a/pipelex/builder/pipe/pipe_parallel_spec.py b/pipelex/builder/pipe/pipe_parallel_spec.pydeleted file mode 100644index 4f194ea5e..000000000--- a/pipelex/builder/pipe/pipe_parallel_spec.py+++ /dev/null@@ -1,91 +0,0 @@-from typing import TYPE_CHECKING, Literal--from pydantic import Field-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.builder.pipe.sub_pipe_spec import SubPipeSpec-from pipelex.pipe_controllers.parallel.pipe_parallel_blueprint import PipeParallelBlueprint-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeParallelSpec(PipeSpec):- """Spec for parallel pipe execution in the Pipelex framework.-- PipeParallel enables concurrent execution of multiple pipes, improving performance- for independent operations. All parallel pipes receive the same input context.- Their outputs are always combined into the pipe's declared output concept — either- `Composite` (untyped named composition) or a structured concept whose fields- correspond to the branch result names.-- Validation Rules:- 1. Branches list must not be empty.- 2. Each branch must be a valid SubPipeSpec.- 3. Pipe codes in branches must reference existing pipes (snake_case).- 4. The output must be `Composite` or a structured concept compatible with the- branch result names (validated at the blueprint/library level).-- """-- type: Literal["PipeParallel"] = "PipeParallel"- pipe_category: Literal["PipeController"] = "PipeController"- branches: list[SubPipeSpec] = Field(description="List of SubPipeSpec instances to execute concurrently.")- add_each_output: bool = Field(default=False, description="Whether to also expose each branch output by its result name in memory.")-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.table import Table- from rich.text import Text-- # Get base pipe information from parent- base_group = super().rendered_pretty(title=title, depth=depth)-- # Create a group combining base info with parallel-specific details- parallel_group = Group()- parallel_group.renderables.append(base_group)-- # Add parallel configuration- parallel_group.renderables.append(Text()) # Blank line- parallel_group.renderables.append(Text.from_markup(f"Add Each Output: [bold yellow]{self.add_each_output}[/bold yellow]"))-- # Add parallel branches as a table- parallel_group.renderables.append(Text()) # Blank line- branches_table = Table(- title="Parallel Branches:",- title_justify="left",- title_style="not italic",- show_header=True,- header_style="dim",- show_edge=True,- show_lines=True,- border_style="dim",- )- branches_table.add_column("Branch", style="dim", width=6, justify="right")- branches_table.add_column("Pipe", style="red")- branches_table.add_column("Result name", style="cyan")-- for idx, branch in enumerate(self.branches, start=1):- branches_table.add_row(str(idx), branch.pipe_code, branch.result)-- parallel_group.renderables.append(branches_table)-- return parallel_group-- @override- def to_blueprint(self) -> PipeParallelBlueprint:- base_blueprint = super().to_blueprint()- core_branches = [branch.to_blueprint() for branch in self.branches]- return PipeParallelBlueprint(- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- type=self.type,- pipe_category=self.pipe_category,- branches=core_branches,- add_each_output=self.add_each_output,- )diff --git a/pipelex/builder/pipe/pipe_search_spec.py b/pipelex/builder/pipe/pipe_search_spec.pydeleted file mode 100644index a0de80b36..000000000--- a/pipelex/builder/pipe/pipe_search_spec.py+++ /dev/null@@ -1,144 +0,0 @@-import re-from typing import TYPE_CHECKING, Any, Literal--from pydantic import ConfigDict, Field, field_validator, model_validator-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.pipe_operators.search.pipe_search_blueprint import PipeSearchBlueprint-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeSearchSpec(PipeSpec):- """Specs for web search pipe operations in the Pipelex framework.-- PipeSearch enables web search using various search providers.- Supports static and dynamic prompts with configurable search parameters.- """-- model_config = ConfigDict(populate_by_name=True)-- type: Literal["PipeSearch"] = "PipeSearch"- pipe_category: Literal["PipeOperator"] = "PipeOperator"- model: str | None = Field(- default=None,- description="Model preset, alias, waterfall, or direct model handle. Use presets from 'pipelex-agent models'.",- )- prompt: str = Field(- validation_alias="query",- description="A finalized search prompt or prompt template: use `$` prefix for inline variables (e.g., `$topic`).",- )- from_date: str | None = Field(- default=None,- description="Start date filter in ISO 8601 format (YYYY-MM-DD). Only return results from this date onwards.",- examples=["2025-01-01"],- )- to_date: str | None = Field(- default=None,- description="End date filter in ISO 8601 format (YYYY-MM-DD). Only return results up to this date.",- examples=["2025-01-01"],- )- include_domains: list[str] | None = Field(default=None, description="Restrict search to these domains only (e.g., ['reuters.com', 'bbc.com']).")- exclude_domains: list[str] | None = Field(default=None, description="Exclude results from these domains.")- max_results: int | None = Field(- default=None, description="Maximum number of search results to return. If not set, the search provider's default is used."- )-- @field_validator("model", mode="before")- @classmethod- def reject_empty_model(cls, value: str | None) -> str | None:- if isinstance(value, str) and not value.strip():- msg = "Model cannot be an empty string; omit the field to use defaults"- raise ValueError(msg)- return value-- @model_validator(mode="before")- @classmethod- def normalize_prompt_field(cls, values: dict[str, Any]) -> dict[str, Any]:- """Accept both 'prompt' and 'query' as input field names.-- The LLM may generate 'query' instead of 'prompt', so we normalize 'prompt' to 'query'- which is the validation_alias that Pydantic expects.- """- if "prompt" in values and "query" not in values:- values["query"] = values.pop("prompt")- return values-- @field_validator("from_date", "to_date", mode="before")- @classmethod- def validate_date_format(cls, date_value: str | None) -> str | None:- if date_value is None:- return date_value- if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date_value):- msg = f"'{date_value}' is not a valid date (expected YYYY-MM-DD)"- raise ValueError(msg)- return date_value-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.markup import escape- from rich.panel import Panel- from rich.text import Text-- # Get base pipe information from parent- base_group = super().rendered_pretty(title=title, depth=depth)-- # Create a group combining base info with search-specific details- search_group = Group()- search_group.renderables.append(base_group)-- # Add search specific information- search_group.renderables.append(Text()) # Blank line- search_group.renderables.append(Text.from_markup(f"Model: [bold yellow]{escape(self.model or '(default)')}[/bold yellow]"))- prompt_panel = Panel(- self.prompt,- title="Search Prompt",- title_align="left",- border_style="cyan",- padding=(0, 1),- )- search_group.renderables.append(Text()) # Blank line- search_group.renderables.append(prompt_panel)-- # Show filter fields when set- filter_lines: list[str] = []- if self.from_date is not None:- filter_lines.append(f"From date: {self.from_date}")- if self.to_date is not None:- filter_lines.append(f"To date: {self.to_date}")- if self.include_domains is not None:- filter_lines.append(f"Include domains: {', '.join(self.include_domains)}")- if self.exclude_domains is not None:- filter_lines.append(f"Exclude domains: {', '.join(self.exclude_domains)}")- if self.max_results is not None:- filter_lines.append(f"Max results: {self.max_results}")- if filter_lines:- search_group.renderables.append(Text()) # Blank line- for filter_line in filter_lines:- search_group.renderables.append(Text.from_markup(f"[dim]{filter_line}[/dim]"))-- return search_group-- @override- def to_blueprint(self) -> PipeSearchBlueprint:- """Convert this PipeSearchSpec to the core PipeSearchBlueprint."""- base_blueprint = super().to_blueprint()-- return PipeSearchBlueprint(- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- prompt=self.prompt,- model=self.model,- include_images=None,- max_results=self.max_results,- from_date=self.from_date,- to_date=self.to_date,- include_domains=self.include_domains,- exclude_domains=self.exclude_domains,- )diff --git a/pipelex/builder/pipe/pipe_sequence_spec.py b/pipelex/builder/pipe/pipe_sequence_spec.pydeleted file mode 100644index b366ecb95..000000000--- a/pipelex/builder/pipe/pipe_sequence_spec.py+++ /dev/null@@ -1,74 +0,0 @@-from typing import TYPE_CHECKING, Literal--from pydantic import Field-from pydantic.json_schema import SkipJsonSchema-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.builder.pipe.sub_pipe_spec import SubPipeSpec-from pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeSequenceSpec(PipeSpec):- """PipeSequenceSpec orchestrates the execution of multiple pipes in a defined order,- where each pipe's output can be used as input for subsequent pipes. This enables- building powerful methods with step-by-step transformations.- """-- type: SkipJsonSchema[Literal["PipeSequence"]] = "PipeSequence"- pipe_category: SkipJsonSchema[Literal["PipeController"]] = "PipeController"- steps: list[SubPipeSpec] = Field(- description=("List of SubPipeSpec instances to execute sequentially. Each step runs after the previous one completes.")- )-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.table import Table- from rich.text import Text-- # Get base pipe information from parent- base_group = super().rendered_pretty(title=title, depth=depth)-- # Create a group combining base info with sequence-specific details- sequence_group = Group()- sequence_group.renderables.append(base_group)-- # Add sequence steps as a table- sequence_group.renderables.append(Text()) # Blank line- steps_table = Table(- title="Sequence Steps:",- title_justify="left",- title_style="not italic",- show_header=True,- header_style="dim",- show_edge=True,- show_lines=True,- border_style="dim",- )- steps_table.add_column("Step", style="dim", width=4, justify="right")- steps_table.add_column("Pipe", style="red")- steps_table.add_column("Result name", style="cyan")-- for idx, step in enumerate(self.steps, start=1):- steps_table.add_row(str(idx), step.pipe_code, step.result)-- sequence_group.renderables.append(steps_table)-- return sequence_group-- @override- def to_blueprint(self) -> PipeSequenceBlueprint:- base_blueprint = super().to_blueprint()- core_steps = [step.to_blueprint() for step in self.steps]- return PipeSequenceBlueprint(- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- steps=core_steps,- )diff --git a/pipelex/builder/pipe/pipe_signature_spec.py b/pipelex/builder/pipe/pipe_signature_spec.pydeleted file mode 100644index 96615ae1a..000000000--- a/pipelex/builder/pipe/pipe_signature_spec.py+++ /dev/null@@ -1,114 +0,0 @@-from typing import TYPE_CHECKING, Literal--from pydantic import Field-from pydantic.json_schema import SkipJsonSchema-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.pipe_machinery.pipe_blueprint import PipeType-from pipelex.pipe_signature.pipe_signature_blueprint import PipeSignatureBlueprint-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeSignatureSpec(PipeSpec):- """A contract-only pipe: inputs, output, and purpose declared without an implementation.-- Use signatures to sketch a pipeline top-down — author the controller and stub each step- as a `PipeSignature`, then replace each one with a real operator (PipeLLM, PipeFunc, ...)- once the contract is settled.-- Validation behavior:- - Strict (default), single pipe — `pipelex validate <pipe>` refuses any pipeline that- reaches a signature through its dependency graph and reports the controller chain.- - Strict (default), whole bundle — `validate bundle <file>` refuses a bundle that- *contains* a signature at all (reached or not): an unimplemented placeholder means the- bundle is not fully runnable. To validate just the implemented slice of a partially- stubbed bundle, select it with `--pipe <code>` (only that pipe is dry-run).- - Lenient — pass `--allow-signatures` to dry-run signatures as mocks (a `Stuff`- matching the declared output, multiplicity included).- - Live execution always raises `PipeSignatureNotExecutableError`; signatures have- no implementation to run.-- Multiplicity notation (same rules as other pipes — see Understanding Multiplicity):- - `Text` — single item- - `Text[]` — variable-length list- - `Image[3]` — exactly 3 items-- Optional fields:- - `signature_for`: hint naming the downstream pipe type the signature stands in for- (e.g. `PipeType.PIPE_LLM`). Tooling-only; `PipeSignature` is not a `PipeType`, so it- cannot be selected here.- """-- # Internal `PipeSpecUnion` discriminator, never written by the author and never rendered as a- # "type" line (a signature is typeless). `SkipJsonSchema` keeps it out of the authoring schema;- # `exclude=True` keeps it out of `model_dump()` so a dump→revalidate round-trip stays typeless and- # re-injects the tag (mirrors `PipeSignatureBlueprint.type`) instead of tripping the migration error.- type: SkipJsonSchema[Literal["PipeSignature"]] = Field(default="PipeSignature", exclude=True)- # Spec-layer authoring tag only: NOT propagated by `to_blueprint()`, which leaves the blueprint- # (and runtime) at `pipe_category = None` because a signature is outside the executable taxonomy.- # Retained per the signature-taxonomy scope decision; no longer- # surfaced in `rendered_pretty` (a signature now renders as "Signature (contract only)", with no- # type/category line). `exclude=True` (like `type`) keeps it out of `model_dump()` so it is not a- # stray key on a round-trip.- pipe_category: SkipJsonSchema[Literal["PipeSignature"]] = Field(default="PipeSignature", exclude=True)- signature_for: PipeType | None = Field(- default=None,- description="Intended downstream pipe type when this signature is implemented (optional hint for agents).",- )-- @override- def to_blueprint(self) -> PipeSignatureBlueprint:- return PipeSignatureBlueprint(- description=self.description,- inputs=self.inputs,- output=self.output,- signature_for=self.signature_for,- )-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.markup import escape- from rich.table import Table- from rich.text import Text-- pipe_group = Group()- if title:- pipe_group.renderables.append(Text(title, style="bold"))- pipe_group.renderables.append(Text.from_markup(f"Pipe Signature: [red]{escape(self.pipe_code)}[/red]\n", style="bold"))- pipe_group.renderables.append(Text.from_markup("[bold magenta]Signature[/bold magenta] (contract only)\n"))- pipe_group.renderables.append(Text.from_markup(f"Description: [yellow italic]{escape(self.description)}[/yellow italic]\n"))-- if not self.inputs:- pipe_group.renderables.append(Text.from_markup("\nNo inputs"))- elif len(self.inputs) == 1:- input_name, concept_spec = next(iter(self.inputs.items()))- pipe_group.renderables.append(- Text.from_markup(f"\nInput: [cyan]{escape(input_name)}[/cyan] ([bold green]{escape(concept_spec)}[/bold green])")- )- else:- inputs_table = Table(- title="Inputs:",- title_justify="left",- title_style="not italic",- show_header=False,- show_edge=True,- show_lines=True,- border_style="dim",- )- inputs_table.add_column("Variable Name", style="cyan")- inputs_table.add_column("Concept", style="bold green")- for input_name, concept_spec in self.inputs.items():- inputs_table.add_row(escape(input_name), escape(concept_spec))- pipe_group.renderables.append(inputs_table)-- pipe_group.renderables.append(Text.from_markup(f"\nOutput concept: [bold green]{escape(self.output)}[/bold green]"))- if self.signature_for is not None:- pipe_group.renderables.append(Text.from_markup(f"\nSignature for: [bold yellow]{escape(self.signature_for)}[/bold yellow]"))-- return pipe_groupdiff --git a/pipelex/builder/pipe/pipe_spec.py b/pipelex/builder/pipe/pipe_spec.pydeleted file mode 100644index 170b05a9a..000000000--- a/pipelex/builder/pipe/pipe_spec.py+++ /dev/null@@ -1,255 +0,0 @@-import re-from typing import TYPE_CHECKING, Any--from pydantic import ConfigDict, Field, field_validator-from typing_extensions import override--from pipelex import log-from pipelex.cogt.content_generation.dry_run_factory import MockFormat-from pipelex.core.concepts.exceptions import ConceptStringError-from pipelex.core.concepts.validation import validate_concept_ref_or_code-from pipelex.core.pipes.variable_multiplicity import (- MULTIPLICITY_PATTERN,- is_force_presence,- is_multiple_multiplicity,- multiplicity_from_bracket_content,- parse_concept_with_multiplicity,- presence_from_symbol,- presence_symbol,-)-from pipelex.core.stuffs.structured_content import StructuredContent-from pipelex.pipe_machinery.pipe_blueprint import PipeBlueprint, PipeCategory, PipeType, valid_pipe_type_tags-from pipelex.tools.misc.pretty import require_rich_for_rendering-from pipelex.tools.misc.string_utils import is_snake_case, normalize_to_ascii--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeSpec(StructuredContent):- """Spec defining a pipe: an executable component with a clear contract defined by its inputs and output.-- Pipes are the building blocks of a Pipelex pipeline. There are two categories:- - Controllers: Manage execution flow (PipeSequence, PipeParallel, PipeCondition, PipeBatch)- - Operators: Perform specific tasks (PipeLLM, PipeImgGen, PipeExtract, PipeFunc, PipeCompose)-- Multiplicity Notation:- Both inputs and outputs use bracket notation to specify item counts:- - No brackets: single item (default)- - []: variable-length list (e.g., "Text[]")- - [N]: exactly N items (e.g., "Image[3]" for 3 images)-- Presence Notation:- Singular inputs and outputs may carry a presence marker after the concept name:- - ?: optional (e.g., "PenaltyClause?" — the slot may legitimately hold no value)- - !: force (inputs only, e.g., "PenaltyClause!" — assert the value is present, error if absent)- Presence markers never combine with multiplicity brackets: an absent plural is the empty list.-- Examples:- inputs = {"document": "Document", "queries": "Text[]"} # single document, multiple texts- output = "Article[]" # produces a list of articles- output = "Image[5]" # produces exactly 5 images- output = "PenaltyClause?" # may produce no value- """-- model_config = ConfigDict(extra="forbid")-- pipe_code: str = Field(description="Unique pipe identifier. Must be snake_case.", json_schema_extra={"mock_format": MockFormat.SNAKE_CASE})- type: Any = Field(- description=(- f"Pipe type. Validated at runtime, must be one of: {PipeType}. Examples: PipeLLM, PipeImgGen, PipeExtract, PipeSequence, PipeParallel."- ),- # Do NOT set examples here - subclasses have Literal types with defaults- # Setting examples would cause mocking issues where the base class type doesn't match subclass fields- )- # TODO: Change examples to list(PipeCategory) for randomness in mocks- pipe_category: Any = Field(- description=(f"Pipe category. Validated at runtime, must be one of: {PipeCategory}. Either 'PipeController' or 'PipeOperator'."),- examples=["PipeOperator"],- )- description: str = Field(description="Natural language description of the pipe's purpose and functionality.")- inputs: dict[str, str] = Field(- description=(- "Input specifications mapping variable names to concept codes with optional multiplicity or presence marker. "- "Keys: input names in snake_case. "- "Values: ConceptCodes in PascalCase with optional brackets, or a presence marker on singular forms. "- "Examples: 'Text' (single), 'Text[]' (variable list), 'Image[2]' (exactly 2 images), "- "'domain.Concept[]' (domain-qualified list), 'Clause?' (optional input), 'Clause!' (force: error if absent)."- ),- json_schema_extra={"mock_format": MockFormat.DICT_SNAKE_KEY_PASCAL_VALUE},- )- output: str = Field(- description=(- "Output concept code in PascalCase with optional multiplicity brackets, or '?' on singular forms "- "to declare the pipe may produce no value ('!' is not allowed on outputs). "- "Examples: 'Text' (single text), 'Article[]' (list of articles), 'Image[3]' (exactly 3 images), "- "'PenaltyClause?' (may produce no value). "- "IMPORTANT: Always use PascalCase for the concept name."- ),- json_schema_extra={"mock_format": MockFormat.PASCAL_CASE},- )-- @field_validator("pipe_code", mode="before")- @classmethod- def validate_pipe_code(cls, value: str) -> str:- return cls.validate_pipe_code_syntax(value)-- @field_validator("type", mode="after")- @classmethod- def validate_pipe_type(cls, value: Any) -> Any:- allowed = valid_pipe_type_tags()- if value not in allowed:- msg = f"Invalid pipe type '{value}'. Must be one of: {allowed}"- raise ValueError(msg)- return value-- @field_validator("output", mode="after")- @classmethod- def validate_output(cls, output: str) -> str:- # Extract concept without multiplicity/presence markers for validation- parse_result = parse_concept_with_multiplicity(output)- # Mirror the blueprint grammar rules (D1, D4): `!` never on outputs, `?` never with multiplicity- if is_force_presence(presence=parse_result.presence):- msg = (- f"Invalid output: '{output}'. The force marker '!' is not allowed on outputs — "- f"it is a use-site assertion for inputs. To declare that this pipe may produce no value, use '?'."- )- raise ValueError(msg)- if parse_result.presence.is_optional and parse_result.multiplicity is not None:- msg = (- f"Invalid output: '{output}'. The optional marker '?' cannot be combined with multiplicity: "- f"a plural slot is never absent — when nothing is found, it is the empty list."- )- raise ValueError(msg)- try:- validate_concept_ref_or_code(concept_ref_or_code=parse_result.concept_ref_or_code)- except ConceptStringError as exc:- # Wrap so pydantic converts it into a ValidationError; otherwise it escapes the- # field_validator unwrapped (pydantic v2 only auto-wraps ValueError/TypeError/AssertionError).- raise ValueError(str(exc)) from exc- return output-- @field_validator("inputs", mode="after")- @classmethod- def validate_inputs(cls, inputs: dict[str, str] | None) -> dict[str, str] | None:- if inputs is None:- return None-- for input_name, concept_spec in inputs.items():- if not is_snake_case(input_name):- msg = f"Invalid input name syntax '{input_name}'. Must be in snake_case."- raise ValueError(msg)-- # Validate the concept spec format: optional multiplicity brackets then optional- # presence marker. Pattern allows: ConceptName, domain.ConceptName, ConceptName[],- # ConceptName[N], ConceptName?, ConceptName!- match = re.match(MULTIPLICITY_PATTERN, concept_spec)- if not match:- msg = (- f"Invalid input syntax for '{input_name}': '{concept_spec}'. "- f"Expected format: 'ConceptName', 'ConceptName[]', 'ConceptName[N]' where N is an integer, "- f"with an optional presence marker '?' or '!' on singular forms (e.g. 'ConceptName?')."- )- raise ValueError(msg)-- bracket_content = match.group(2)- if bracket_content and int(bracket_content) <= 0:- msg = f"Invalid input '{input_name}': '{concept_spec}'. Multiplicity must be at least 1."- raise ValueError(msg)-- # Mirror the blueprint grammar rule (D1, D4): presence markers never combine with- # multiplicity — and `[1]` is the single form, not multiplicity, so it takes a marker.- presence = presence_from_symbol(symbol=match.group(3))- multiplicity = multiplicity_from_bracket_content(bracket_content=bracket_content)- if not presence.is_plain and is_multiple_multiplicity(multiplicity=multiplicity):- msg = (- f"Invalid input '{input_name}': '{concept_spec}'. "- f"The presence marker '{presence_symbol(presence=presence)}' cannot be combined with multiplicity: "- f"a plural slot is never absent — when nothing is found, it is the empty list."- )- raise ValueError(msg)-- # Extract the concept part (without markers) and validate it- concept_ref_or_code = match.group(1)- try:- validate_concept_ref_or_code(concept_ref_or_code=concept_ref_or_code)- except ConceptStringError as exc:- raise ValueError(str(exc)) from exc-- return inputs-- @classmethod- def validate_pipe_code_syntax(cls, pipe_code: str) -> str:- # Strip namespace prefix if present (e.g., "domain.my_pipe" → "my_pipe").- # The builder LLM sometimes generates dotted pipe codes; the namespace- # comes from the bundle's domain field, not from the pipe code itself.- # This must happen BEFORE ASCII normalization, because normalize_to_ascii()- # strips dots (keeping only alphanumeric + underscore).- if "." in pipe_code:- bare_pipe_code = pipe_code.rsplit(".", maxsplit=1)[1]- log.warning(f"Pipe code '{pipe_code}' contains a namespace prefix, stripped to '{bare_pipe_code}'")- pipe_code = bare_pipe_code-- # Normalize Unicode to ASCII to prevent homograph attacks- normalized_pipe_code = normalize_to_ascii(pipe_code)-- if normalized_pipe_code != pipe_code:- log.warning(f"Pipe code '{pipe_code}' contained non-ASCII characters, normalized to '{normalized_pipe_code}'")-- if not is_snake_case(normalized_pipe_code):- msg = f"Invalid pipe code syntax '{normalized_pipe_code}'. Must be in snake_case."- raise ValueError(msg)- return normalized_pipe_code-- def to_blueprint(self) -> PipeBlueprint:- return PipeBlueprint(- description=self.description,- inputs=self.inputs or None,- output=self.output,- type=self.type,- pipe_category=self.pipe_category,- )-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.table import Table- from rich.text import Text-- pipe_group = Group()- if title:- pipe_group.renderables.append(Text(title, style="bold"))- pipe_group.renderables.append(Text.from_markup(f"Pipe: [bold red]{self.pipe_code}[/bold red]\n"))- pipe_group.renderables.append(Text.from_markup(f"Type: [bold magenta]{self.type}[/bold magenta] ({self.pipe_category})\n"))- if self.description:- pipe_group.renderables.append(Text.from_markup(f"Description: [yellow italic]{self.description}[/yellow italic]\n"))-- # Create inputs section- if not self.inputs:- pipe_group.renderables.append(Text.from_markup("\nNo inputs"))- elif len(self.inputs) == 1:- # Single input: display as a simple line of text- input_name, concept_spec = next(iter(self.inputs.items()))- pipe_group.renderables.append(Text.from_markup(f"\nInput: [cyan]{input_name}[/cyan] ([bold green]{concept_spec}[/bold green])"))- else:- # Multiple inputs: display as a table- inputs_table = Table(- title="Inputs:",- title_justify="left",- title_style="not italic",- show_header=False,- show_edge=True,- show_lines=True,- border_style="dim",- )- inputs_table.add_column("Variable Name", style="cyan")- inputs_table.add_column("Concept", style="bold green")- for input_name, concept_spec in self.inputs.items():- inputs_table.add_row(input_name, concept_spec)- pipe_group.renderables.append(inputs_table)-- # Show output- pipe_group.renderables.append(Text.from_markup(f"\nOutput: [bold green]{self.output}[/bold green]"))-- return pipe_groupdiff --git a/pipelex/builder/pipe/pipe_spec_map.py b/pipelex/builder/pipe/pipe_spec_map.pydeleted file mode 100644index 7ad1ce7c6..000000000--- a/pipelex/builder/pipe/pipe_spec_map.py+++ /dev/null@@ -1,34 +0,0 @@-from pipelex.builder.pipe.pipe_batch_spec import PipeBatchSpec-from pipelex.builder.pipe.pipe_compose_spec import PipeComposeSpec-from pipelex.builder.pipe.pipe_condition_spec import PipeConditionSpec-from pipelex.builder.pipe.pipe_doc_gen_spec import PipeDocGenSpec-from pipelex.builder.pipe.pipe_extract_spec import PipeExtractSpec-from pipelex.builder.pipe.pipe_func_spec import PipeFuncSpec-from pipelex.builder.pipe.pipe_img_gen_spec import PipeImgGenSpec-from pipelex.builder.pipe.pipe_judge_spec import PipeJudgeSpec-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpec-from pipelex.builder.pipe.pipe_search_spec import PipeSearchSpec-from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.builder.pipe.pipe_structure_spec import PipeStructureSpec--# Concrete, user-selectable pipe types only. `PipeSignature` is deliberately absent: a signature is-# not a selectable type — it is the typeless case. The single-pipe authoring path (`parse_pipe_spec`)-# routes a typeless spec to `PipeSignatureSpec` directly and rejects an explicit `type = "PipeSignature"`-# with a migration error before ever consulting this map.-pipe_type_to_spec_class: dict[str, type[PipeSpec]] = {- "PipeFunc": PipeFuncSpec,- "PipeImgGen": PipeImgGenSpec,- "PipeCompose": PipeComposeSpec,- "PipeLLM": PipeLLMSpec,- "PipeExtract": PipeExtractSpec,- "PipeSearch": PipeSearchSpec,- "PipeJudge": PipeJudgeSpec,- "PipeStructure": PipeStructureSpec,- "PipeDocGen": PipeDocGenSpec,- "PipeBatch": PipeBatchSpec,- "PipeCondition": PipeConditionSpec,- "PipeParallel": PipeParallelSpec,- "PipeSequence": PipeSequenceSpec,-}diff --git a/pipelex/builder/pipe/pipe_spec_union.py b/pipelex/builder/pipe/pipe_spec_union.pydeleted file mode 100644index 2e9cafc20..000000000--- a/pipelex/builder/pipe/pipe_spec_union.py+++ /dev/null@@ -1,36 +0,0 @@-from typing import Annotated--from pydantic import Field--from pipelex.builder.pipe.pipe_batch_spec import PipeBatchSpec-from pipelex.builder.pipe.pipe_compose_spec import PipeComposeSpec-from pipelex.builder.pipe.pipe_condition_spec import PipeConditionSpec-from pipelex.builder.pipe.pipe_doc_gen_spec import PipeDocGenSpec-from pipelex.builder.pipe.pipe_extract_spec import PipeExtractSpec-from pipelex.builder.pipe.pipe_func_spec import PipeFuncSpec-from pipelex.builder.pipe.pipe_img_gen_spec import PipeImgGenSpec-from pipelex.builder.pipe.pipe_judge_spec import PipeJudgeSpec-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpec-from pipelex.builder.pipe.pipe_search_spec import PipeSearchSpec-from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.builder.pipe.pipe_signature_spec import PipeSignatureSpec-from pipelex.builder.pipe.pipe_structure_spec import PipeStructureSpec--PipeSpecUnion = Annotated[- PipeFuncSpec- | PipeImgGenSpec- | PipeComposeSpec- | PipeLLMSpec- | PipeExtractSpec- | PipeSearchSpec- | PipeJudgeSpec- | PipeStructureSpec- | PipeDocGenSpec- | PipeBatchSpec- | PipeConditionSpec- | PipeParallelSpec- | PipeSequenceSpec- | PipeSignatureSpec,- Field(discriminator="type"),-]diff --git a/pipelex/builder/pipe/pipe_structure_spec.py b/pipelex/builder/pipe/pipe_structure_spec.pydeleted file mode 100644index ece5fa406..000000000--- a/pipelex/builder/pipe/pipe_structure_spec.py+++ /dev/null@@ -1,68 +0,0 @@-from typing import TYPE_CHECKING, Literal--from pydantic import Field, field_validator-from pydantic.json_schema import SkipJsonSchema-from typing_extensions import override--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.pipe_operators.structure.pipe_structure_blueprint import PipeStructureBlueprint-from pipelex.tools.misc.pretty import require_rich_for_rendering--if TYPE_CHECKING:- from pipelex.tools.misc.pretty import PrettyPrintable---class PipeStructureSpec(PipeSpec):- """Spec for the PipeStructure operator.-- PipeStructure converts a Text-compatible input into a structured concept using an LLM call.- Use it when you already have text (e.g., extracted from a PDF, fetched from a search, or- produced by an earlier pipe) and want to turn it into typed data.-- Validation Rules:- - inputs dict must have exactly one entry, and its concept must be Text-compatible.- - output must NOT be Text-compatible.- """-- type: SkipJsonSchema[Literal["PipeStructure"]] = "PipeStructure"- pipe_category: SkipJsonSchema[Literal["PipeOperator"]] = "PipeOperator"- model: str | None = Field(- default=None,- description="Model preset, alias, waterfall, or direct model handle. Use presets from 'pipelex-agent models'.",- )-- @field_validator("model", mode="before")- @classmethod- def reject_empty_model(cls, value: str | None) -> str | None:- if isinstance(value, str) and not value.strip():- msg = "Model cannot be an empty string; omit the field to use defaults"- raise ValueError(msg)- return value-- @override- def rendered_pretty(self, *, title: str | None = None, depth: int = 0) -> "PrettyPrintable":- require_rich_for_rendering()- from rich.console import Group- from rich.markup import escape- from rich.text import Text-- base_group = super().rendered_pretty(title=title, depth=depth)-- structure_group = Group()- structure_group.renderables.append(base_group)-- structure_group.renderables.append(Text()) # Blank line- structure_group.renderables.append(Text.from_markup(f"Model: [bold yellow]{escape(self.model or '(default)')}[/bold yellow]"))-- return structure_group-- @override- def to_blueprint(self) -> PipeStructureBlueprint:- base_blueprint = super().to_blueprint()-- return PipeStructureBlueprint(- description=base_blueprint.description,- inputs=base_blueprint.inputs_concept_specs,- output=base_blueprint.output,- model=self.model,- )diff --git a/pipelex/builder/pipe/sub_pipe_spec.py b/pipelex/builder/pipe/sub_pipe_spec.pydeleted file mode 100644index c4b10ba56..000000000--- a/pipelex/builder/pipe/sub_pipe_spec.py+++ /dev/null@@ -1,37 +0,0 @@-from pydantic import ConfigDict, Field--from pipelex.cogt.content_generation.dry_run_factory import MockFormat-from pipelex.core.stuffs.structured_content import StructuredContent-from pipelex.pipe_controllers.sub_pipe_blueprint import SubPipeBlueprint---class SubPipeSpec(StructuredContent):- """Spec for a single step within a pipe controller.-- SubPipeSpec defines individual pipe executions within controller pipes- (PipeSequence, PipeParallel, PipeBatch, PipeCondition).-- Attributes:- pipe_code: The pipe code to execute. Must reference an existing pipe in the pipeline.- result: Name to assign to the pipe's output in the context.-- Validation Rules:- - pipe must reference a valid pipe code.- - result, when specified, should follow naming conventions.-- """-- model_config = ConfigDict(extra="forbid")-- pipe_code: str = Field(json_schema_extra={"mock_format": MockFormat.SNAKE_CASE})- result: str = Field(json_schema_extra={"mock_format": MockFormat.SNAKE_CASE})- batch_over: str | None = Field(default=None, json_schema_extra={"mock_format": MockFormat.SNAKE_CASE})- batch_as: str | None = Field(default=None, json_schema_extra={"mock_format": MockFormat.SNAKE_CASE})-- def to_blueprint(self) -> SubPipeBlueprint:- return SubPipeBlueprint(- pipe=self.pipe_code,- result=self.result,- batch_over=self.batch_over,- batch_as=self.batch_as,- )diff --git a/pipelex/builder/runner_code.py b/pipelex/builder/runner_code.pydeleted file mode 100644index 7e85f3460..000000000--- a/pipelex/builder/runner_code.py+++ /dev/null@@ -1,284 +0,0 @@-"""Runner code generation utilities for Pipelex pipelines.--This module provides functions to generate executable Python code for Pipelex pipelines.--Main Functions:----------------- generate_runner_code(pipe): Generate complete executable Python script--Custom structure classes are imported from the codegen engine's single-module projection-(`structures/structures.py`, emitted by `codegen types --target python-structures` — see-`pipelex/codegen/`). A class that lives in a real importable module (a user-registered class backing-a `structure = "<ClassName>"` concept) is imported from that module instead.-"""--from typing import Any--from pipelex.core.concepts.concept_representation_generator import (- ConceptRepresentationFormat,- ConceptRepresentationGenerator,-)-from pipelex.core.concepts.native.concept_native import NativeConceptCode-from pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecs-from pipelex.core.pipes.variable_multiplicity import is_multiple_multiplicity-from pipelex.interpreter_hub import get_concept_library-from pipelex.pipe_machinery.pipe_abstract import PipeAbstract-from pipelex.runtime_hub import get_class_registry--STRUCTURES_MODULE = "structures.structures"-"""Module path of the emitted types projection, relative to the generated script's directory."""---def _format_representation_as_python(representation: dict[str, Any], *, is_multiple: bool = False) -> str:- """Format a representation dict as Python code.-- Args:- representation: Dict with concept and content- is_multiple: If True, wrap content in a list-- Returns:- Python code string- """- concept = representation["concept"]- content = representation["content"]-- # If multiple, wrap content in a list- if is_multiple:- content = f"[{content}]"-- # Content is already a Python instantiation string from the generator- return f'{{\n "concept": "{concept}",\n "content": {content},\n }}'---def _get_structure_class_import(*, class_name: str) -> str | None:- """Get the import statement for a native structure class.-- The import statement is generated dynamically from the class's actual module location,- so it will automatically reflect any file relocations.-- Args:- class_name: The name of the structure class-- Returns:- Import statement string, or None if not a native structure class- """- cls = NativeConceptCode.get_native_structure_class(class_name)- if cls is None:- return None- return f"from {cls.__module__} import {cls.__name__}"---def _custom_import_statement(*, class_name: str, emitted_names: set[str]) -> str:- """Build the import statement for a custom (non-native) structure class.-- A name the codegen engine emitted comes from the single-module projection. Otherwise, a class- registered from a real importable module (a user-authored class backing a- `structure = "<ClassName>"` concept) is imported from that module; runtime-materialized classes- (exec'd, no importable module) fall back to the projection module, which carries their emitted- counterparts.- """- if class_name not in emitted_names:- registered = get_class_registry().get_class(name=class_name)- if registered is not None and registered.__module__ not in {"__main__", "builtins"}:- return f"from {registered.__module__} import {class_name}"- return f"from {STRUCTURES_MODULE} import {class_name}"---def _collect_imports_for_inputs(inputs: InputStuffSpecs, *, class_name_overrides: dict[str, str]) -> tuple[set[str], set[str]]:- """Collect all class names needed for a pipe's inputs.-- Args:- inputs: The pipe inputs- class_name_overrides: Runtime-class-name -> emitted-name mapping applied to the rendered code-- Returns:- Tuple of (native class names, custom class names) — custom names are post-override spellings- """- native_classes: set[str] = set()- custom_classes: set[str] = set()-- for input_req in inputs.root.values():- concept = input_req.concept- structure_class = get_concept_library().get_structure_class(concept=concept)-- # Get imports from the representation generator (includes nested custom classes)- generator = ConceptRepresentationGenerator(ConceptRepresentationFormat.PYTHON, class_name_overrides=class_name_overrides)- generator.generate_representation(concept.concept_ref, structure_class=structure_class)-- for class_name in generator.imports_needed:- if NativeConceptCode.is_native_structure_class(class_name):- native_classes.add(class_name)- else:- custom_classes.add(class_name)-- return native_classes, custom_classes---def generate_runner_code(- pipe: PipeAbstract,- *,- output_multiplicity: bool = False,- library_dir: str | None = None,- class_name_overrides: dict[str, str] | None = None,-) -> str:- """Generate the complete Python runner code for a pipe.-- This generates a runnable Python script with:- - Import statements for all required structure classes- - An async function to run the pipeline with proper return type- - Example input values based on the pipe's input concepts- - Output handling with main_stuff_as (or main_stuff for Anything)-- Args:- pipe: The pipe to generate runner code for- output_multiplicity: Whether the output is a list (e.g., Text[])- library_dir: Directory containing the MTHDS bundles to load- class_name_overrides: Runtime-class-name -> emitted-name mapping so the script spells custom- classes the way the accompanying types projection defines them (bare-when-unique)- """- overrides = class_name_overrides or {}- emitted_names = set(overrides.values())-- # Get output information (spelled per the emitted projection when a mapping is provided)- runtime_output_class_name = pipe.output.concept.structure_class_name- structure_class_name = overrides.get(runtime_output_class_name, runtime_output_class_name)- is_native = NativeConceptCode.is_native_structure_class(structure_class_name)-- # Check if output is the special "Anything" concept (no specific content type)- is_anything_output = pipe.output.concept.code == NativeConceptCode.ANYTHING-- # Collect all imports needed for inputs- native_classes, custom_classes = _collect_imports_for_inputs(pipe.inputs, class_name_overrides=overrides)-- # Track if we need to import Any from typing (for Anything output)- needs_any_import = is_anything_output-- # Add output class to appropriate set (unless it's Anything)- if not is_anything_output:- if is_native:- native_classes.add(structure_class_name)- else:- custom_classes.add(structure_class_name)-- # Build import section- import_lines: list[str] = []-- # Add path setup for custom structure imports (must be before other imports)- if custom_classes:- import_lines.extend(- [- "import sys",- "from pathlib import Path",- "",- "# Add script directory to path for local imports",- "sys.path.insert(0, str(Path(__file__).parent))",- "",- ]- )-- import_lines.extend(["import asyncio", ""])-- # Add typing import if needed (for Anything output)- if needs_any_import:- import_lines.append("from typing import Any")- import_lines.append("")-- # Add native content class imports- native_imports: list[str] = []- for class_name in sorted(native_classes):- import_stmt = _get_structure_class_import(class_name=class_name)- if import_stmt:- native_imports.append(import_stmt)- import_lines.extend(native_imports)-- # Add custom structure class imports (from the types projection or their real module)- if custom_classes:- import_lines.append("")- for class_name in sorted(custom_classes):- import_lines.append(_custom_import_statement(class_name=class_name, emitted_names=emitted_names))-- import_lines.extend(- [- "",- "from pipelex.pipelex import Pipelex",- "from pipelex.pipeline.runner import PipelexMTHDSProtocol",- ]- )-- # Build inputs entries- if not pipe.inputs.is_empty:- input_entries: list[str] = []- for var_name, input_req in pipe.inputs.root.items():- is_multiple = is_multiple_multiplicity(multiplicity=input_req.multiplicity)- result, _ = input_req.concept.render_concept_representation(- structure_class=get_concept_library().get_structure_class(concept=input_req.concept),- output_format=ConceptRepresentationFormat.PYTHON,- multiplicity=input_req.multiplicity,- class_name_overrides=overrides,- )- python_code = _format_representation_as_python(result, is_multiple=is_multiple)- input_entries.append(f' "{var_name}": {python_code},')- input_memory_block = "\n".join(input_entries)- else:- input_memory_block = " # No inputs required"-- # Determine return type annotation and result call- # Special case: Anything output uses Any type and main_stuff (no content type casting)- if is_anything_output:- return_type = "Any"- result_call = "pipe_output.main_stuff"- elif output_multiplicity:- return_type = f"list[{structure_class_name}]"- result_call = f"pipe_output.main_stuff_as_items(item_type={structure_class_name})"- else:- return_type = structure_class_name- result_call = f"pipe_output.main_stuff_as(content_type={structure_class_name})"-- # Build the main function- function_lines = [- "",- "",- f"async def run_{pipe.code}() -> {return_type}:",- " runner = PipelexMTHDSProtocol()",- " response = await runner.execute(",- f' pipe_code="{pipe.code}",',- ]-- if not pipe.inputs.is_empty:- function_lines.extend(- [- " inputs={",- input_memory_block,- " },",- ]- )-- function_lines.extend(- [- " )",- " pipe_output = response.pipe_output",- f" return {result_call}",- "",- "",- 'if __name__ == "__main__":',- " # Initialize Pipelex",- ]- )-- # Add Pipelex.make() with library_dirs if provided- if library_dir:- function_lines.append(f' with Pipelex.make(library_dirs=["{library_dir}"]):')- else:- function_lines.append(" with Pipelex.make():")-- function_lines.extend(- [- " # Run the pipeline",- f" result = asyncio.run(run_{pipe.code}())",- "",- ]- )-- # Combine everything- code_lines = import_lines + function_lines- return "\n".join(code_lines)diff --git a/pipelex/cli/_cli.py b/pipelex/cli/_cli.pyindex 22b4a3719..06366c8e6 100644--- a/pipelex/cli/_cli.py+++ b/pipelex/cli/_cli.py@@ -241,9 +241,7 @@ def migrate_command(migrate_cmd(dry_run=dry_run, yes=yes)-app.add_typer(- build_app, name="build", help="Generate AI methods from natural language requirements: pipelines in .mthds format and python code to run them"-)+app.add_typer(build_app, name="build", help="Generate example inputs, example outputs and structure classes for a pipe")app.add_typer(validate_app,name="validate",diff --git a/pipelex/cli/agent_cli/CLAUDE.md b/pipelex/cli/agent_cli/CLAUDE.mdindex 3d3607bc2..a1658c1b6 100644--- a/pipelex/cli/agent_cli/CLAUDE.md+++ b/pipelex/cli/agent_cli/CLAUDE.md@@ -11,14 +11,14 @@ Two independent options control the two output streams:Only the error format is backed by a module-level `ContextVar` in `agent_output.py` (`_agent_cli_error_format`). The reason: `agent_error()` is called from sites that don't see the Typer option — factory init failures (`agent_cli_factory.py`), the unknown-command handler in `PipelexAgentCLI.get_command`, runner validation in the app callback, and any future site in shared library/runtime code. The ContextVar lets all of them honor `--error-format` (or `--format`'s inherited value) for free. JSON is the default so errors raised before any command opts in stay machine-parseable.-`concept`, `pipe`, `fmt`, `lint`, `accept-gateway-terms` are **always JSON / raw passthrough** — they have neither `--format` nor `--error-format`. Their errors keep flowing through the ContextVar's JSON default.+`fmt`, `lint`, `accept-gateway-terms` are **always JSON / raw passthrough** — they have neither `--format` nor `--error-format`. Their errors keep flowing through the ContextVar's JSON default.-`inputs` is a deliberate deviation: its `--format` takes `json|toml` (an `InputsTemplateFormat`, NOT the `markdown|json` `CliOutputFormat` pair) because it selects the **template serialization**, not a presentation style. `json` (default) keeps the structured success envelope; `toml` prints the raw TOML template to stdout, in the same spirit as the `concept`/`pipe` raw-TOML passthrough. A pipe with no inputs prints a TOML comment line in `toml` mode (valid TOML, loads back as an empty dict). `inputs` still has no `--error-format` — its errors keep flowing through the ContextVar's JSON default.+`inputs` is a deliberate deviation: its `--format` takes `json|toml` (an `InputsTemplateFormat`, NOT the `markdown|json` `CliOutputFormat` pair) because it selects the **template serialization**, not a presentation style. `json` (default) keeps the structured success envelope; `toml` prints the raw TOML template to stdout. A pipe with no inputs prints a TOML comment line in `toml` mode (valid TOML, loads back as an empty dict). `inputs` still has no `--error-format` — its errors keep flowing through the ContextVar's JSON default.Markdown structure per command:- `run`: `# Pipeline run complete`, a `## Result` section (the rendered `main_stuff` markdown with `--with-memory`, otherwise the concept JSON in a fenced block), and output / graph file paths. With the graph on, the `graph_files` object of the `--with-memory` envelope names the viewer (`graph_html`), the graph on a live run (`graph_spec`, the graphspec renamed `live_run_graph.json`) and the graph's three companions written beside it under their canonical names (`pipe_io_contracts`, `input_form`, `output_form` — the validate artifacts describing the graph's data, keyed by `pipe_ref`); the agent CLI settles its graph inclusion (graphspec on, viewer on) before the run rather than at render time, since the companions are built inside the run's library window under that same flag; a viewer resolves them from the graph file's directory, so the rename never moves them. Cost is machine-first: on the local runner, when costs are on (`--costs`, the default) and the run did reportable work (any tokens or any cost), a best-effort `cost_report` object (`{total_cost, by_model: [...]}`, real USD) rides the JSON `--with-memory` envelope — there is **no** Rich cost table on stderr (unlike the human `pipelex run` CLI). The markdown renderer ignores the `cost_report` key, so it is JSON-only. A free/zero-price model still reports its token usage (with `total_cost` 0). The `cost_report` is **absent** when the run did no reportable work (dry runs), when `--no-costs` is passed, on the API-runner path (which does not assemble local usage), or if cost-summary aggregation fails (caught and skipped so it never fails an otherwise-successful run) — so consumers must treat it as optional.-- `validate`: `# Validation passed`, the bundle path when relevant, and a list of validated pipes with their status. Every entry in `validated_pipes` (markdown and JSON) identifies its pipe by the namespaced `pipe_ref` (`domain.code`) — the same unambiguous identity across `validate all`, `validate bundle`, and `validate pipe`, so the same pipe is never reported under two identifiers. `validate bundle`, `validate method`, and `validate all` carry `pending_signatures` — the library-wide list of pipes still declared as `PipeSignature` (unimplemented forward declarations), namespaced by `pipe_ref` — rendered as a "Pending signatures" section in markdown. They also carry a derived `is_runnable` boolean (`true` ⇔ `pending_signatures` is empty), and the markdown adds an explicit plain-English runnability verdict on those surfaces: a complete bundle/library states it is runnable, while one with pending signatures states it is NOT yet runnable immediately above the verbatim "Pending signatures" heading. These whole-bundle/whole-library surfaces are **strict by default**: they exit non-zero on `not is_runnable` unless `--allow-signatures` is passed (which both tolerates the placeholders for the exit code and mock-runs the signature pipes in the sweep). Single-pipe surfaces make no library-wide runnability claim and never gate the exit code on it: bare `validate pipe <code>` omits the key and emits no verdict, while `validate bundle`/`validate method` with `--pipe` still surface the library-wide `pending_signatures` for information but do not gate on it (the requested slice can be fully implemented even when unrelated placeholders remain elsewhere). The whole-bundle and whole-library surfaces also carry a `warnings` array — the advisory lints, rendered as a "Warnings" section in markdown — assembled by `pipelex/pipeline/advisory_warnings.py`, the ONE composition point every advisory-bearing channel calls (this CLI, the bare CLI, the builder ops and the protocol report). Bare `validate pipe <code>` carries none, and neither does the builder's `validate_all`; `validate bundle` / `validate method` with `--pipe` DO carry them, because they validate the whole bundle and only narrow the dry run, so the array stays bundle-wide there. Add a new advisory family there, never at a call site: the sites used to assemble their own and disagreed about which families they carried.+- `validate`: `# Validation passed`, the bundle path when relevant, and a list of validated pipes with their status. Every entry in `validated_pipes` (markdown and JSON) identifies its pipe by the namespaced `pipe_ref` (`domain.code`) — the same unambiguous identity across `validate all`, `validate bundle`, and `validate pipe`, so the same pipe is never reported under two identifiers. `validate bundle`, `validate method`, and `validate all` carry `pending_signatures` — the library-wide list of pipes still declared as `PipeSignature` (unimplemented forward declarations), namespaced by `pipe_ref` — rendered as a "Pending signatures" section in markdown. They also carry a derived `is_runnable` boolean (`true` ⇔ `pending_signatures` is empty), and the markdown adds an explicit plain-English runnability verdict on those surfaces: a complete bundle/library states it is runnable, while one with pending signatures states it is NOT yet runnable immediately above the verbatim "Pending signatures" heading. These whole-bundle/whole-library surfaces are **strict by default**: they exit non-zero on `not is_runnable` unless `--allow-signatures` is passed (which both tolerates the placeholders for the exit code and mock-runs the signature pipes in the sweep). Single-pipe surfaces make no library-wide runnability claim and never gate the exit code on it: bare `validate pipe <code>` omits the key and emits no verdict, while `validate bundle`/`validate method` with `--pipe` still surface the library-wide `pending_signatures` for information but do not gate on it (the requested slice can be fully implemented even when unrelated placeholders remain elsewhere). The whole-bundle and whole-library surfaces also carry a `warnings` array — the advisory lints, rendered as a "Warnings" section in markdown — assembled by `pipelex/pipeline/advisory_warnings.py`, the ONE composition point every advisory-bearing channel calls (this CLI, the bare CLI and the protocol report). Bare `validate pipe <code>` carries none; `validate bundle` / `validate method` with `--pipe` DO carry them, because they validate the whole bundle and only narrow the dry run, so the array stays bundle-wide there. Add a new advisory family there, never at a call site: the sites used to assemble their own and disagreed about which families they carried.- `fix`: `# Fix applied - bundle is valid` after one or more fixes, `# Bundle already valid` when the loop had nothing to apply, or `# Bundle valid but not runnable` when pending `PipeSignature` placeholders remain. The JSON success envelope carries `is_valid`, `bundle_path`, `iterations`, `fixes_applied`, `files_written`, `remaining_errors`, and, on successful validation, `pending_signatures` plus `is_runnable`. Whole-bundle fix runs are strict by default: they emit the success envelope but exit 1 on `not is_runnable` unless `--allow-signatures` is passed. A still-invalid verdict exits 1 via `FixBundleError` on stderr with the same structured result fields plus any `bail_reason`.- `migrate`: `# Configuration migration`, the mode (applied / dry run) and verdict, the directories walked, a files-walked/changed/written count, then one `## <path>` section per file that is not clean listing the entries applied, the entries blocked with their reason and guidance, and any unexplained paths. Paths, operation kinds and ledger-supplied values only — no value read from the user's file is ever rendered, in either format.- `init`: `# Pipelex initialized` with target directory, enabled backends, and routing profile.@@ -72,8 +72,6 @@ commands/fmt_cmd.py # fmt — format file via plxt passthroughlint_cmd.py # lint — lint file via plxt passthroughplxt_passthrough.py # Shared helper for plxt subprocess delegation- concept_cmd.py # concept — JSON spec → raw TOML to stdout- pipe_cmd.py # pipe — JSON spec → raw TOML to stdoutmodels_cmd.py # models — list presets, aliases, waterfallscheck_model_cmd.py # check-model — validate model reference with fuzzy suggestionsinit_cmd.py # init — non-interactive config setup (--global/-g, --config/-c)@@ -92,8 +90,6 @@ commands/| `lint` | Lints a .mthds/.toml/.plx file for errors (delegates to plxt) || `inputs` | Generates an example inputs template for a pipe/bundle/method (pipe\|bundle\|method subcommands). `--format json\|toml` (template serialization, default: json — NOT the markdown\|json pair); `toml` prints raw TOML to stdout || `codegen` | Agent mirror of the bare `pipelex codegen` family (types\|check subcommands). `types --target <flavor>` resolves the closure into the normalized crate and writes stamped typed artifacts + `codegen.lock` (write-if-changed); `check` is the offline drift check (pure hashing, no Pipelex boot — exit 0 current, 1 drift as a structured `CodegenDriftError` with `drifts[]`, 2 no/unreadable lock). Both: `--format markdown\|json` (success, default: markdown) + `--error-format markdown\|json` (errors, defaults to `--format`'s value). |-| `concept` | Converts a JSON concept spec into raw TOML (stdout) |-| `pipe` | Converts a JSON pipe spec into raw TOML (stdout). A spec with a `type` (via `--type` or a `type` key) is that concrete pipe; a **typeless** spec (no `type`) is a signature and renders a `[pipe.x]` section with no type line. An explicit `type = "PipeSignature"` is rejected with a migration error — `PipeSignature` is not a type. || `models` | Lists available model presets, aliases, and waterfalls. `--format markdown\|json` (success, default: markdown) + `--error-format markdown\|json` (errors, defaults to `--format`'s value) || `check-model` | Validates a model reference and suggests alternatives if invalid. `--type`/`-t` for model category, `--format markdown\|json` (success, default: markdown) + `--error-format markdown\|json` (errors, defaults to `--format`'s value) || `migrate` | Migrates this machine's configuration files (global `~/.pipelex/` and project `.pipelex/`, non-recursively) to the current schema by replaying each surface's ledger. Does **not** boot — it is the command for a configuration that cannot load. Writes only with `--yes`; `--dry-run` plans and is the default; the two together are refused with exit 2. `--format markdown\|json` (success, default: markdown) + `--error-format markdown\|json`. The verdict is the structured `needs_attention`, not the exit code. |@@ -101,7 +97,7 @@ commands/## Key Patterns-- **Output contract**: Commands with `--format` emit success via `agent_success_formatted(result, markdown_renderer, output_format)` — JSON or a markdown renderer per the explicit `output_format` argument. `agent_error(message, error_type, cause)` dispatches JSON or markdown by reading the `_agent_cli_error_format` ContextVar, which each `--format`-aware command sets via `set_agent_cli_error_format(error_format or output_format)` at function entry. Exceptions that print directly to stdout: `fmt`/`lint` (plxt passthrough), `concept`/`pipe` (raw TOML). Markdown renderers: `format_run_markdown` (`run/_output_helpers.py`), `format_validate_markdown` (lifted to the non-CLI `pipelex/pipeline/validation_render.py` so `pipelex-api` can import it without CLI/Typer deps), `format_fix_markdown` (non-CLI `pipelex/pipeline/fixes/fix_render.py`), `_format_init_markdown` (`init_cmd.py`).+- **Output contract**: Commands with `--format` emit success via `agent_success_formatted(result, markdown_renderer, output_format)` — JSON or a markdown renderer per the explicit `output_format` argument. `agent_error(message, error_type, cause)` dispatches JSON or markdown by reading the `_agent_cli_error_format` ContextVar, which each `--format`-aware command sets via `set_agent_cli_error_format(error_format or output_format)` at function entry. Exceptions that print directly to stdout: `fmt`/`lint` (plxt passthrough) and `inputs --format toml` (the raw TOML template). Markdown renderers: `format_run_markdown` (`run/_output_helpers.py`), `format_validate_markdown` (lifted to the non-CLI `pipelex/pipeline/validation_render.py` so `pipelex-api` can import it without CLI/Typer deps), `format_fix_markdown` (non-CLI `pipelex/pipeline/fixes/fix_render.py`), `_format_init_markdown` (`init_cmd.py`).- **Error classification**: Each error carries a domain (`input`, `config`, `runtime`), a hint string, and a `retryable` flag. `agent_error()` reads them **report-first**: a `PipelexError` cause's `to_error_report()` wins, and the `AGENT_ERROR_HINTS` / `AGENT_ERROR_DOMAINS` dicts in `agent_output.py` are the fallback for error types that cannot self-describe (builtins, third-party classes, synthetic `error_type` labels). Two ways a class self-describes, and both bar it from the dicts: a class-level `error_domain` / `user_action`, **or** — for the `CogtError` family — an `error_category`, from which `InferenceErrorCategory.error_domain` derives the domain (so `CONTENT` inference failures report `input`, and a dict entry for such a class would be unreachable). `tests/unit/pipelex/cli/test_agent_output_drift.py` enforces both. Because the read is report-first, the `error_type` an arm passes must name the class that actually failed — `type(exc).__name__`, not the base class the `except` caught. A hardcoded label detaches the reported class from the domain and hint riding the same envelope from the cause's report, so a consumer reading `error_type` is told one class produced a classification only another declares; the `validate pipe` / `validate bundle` not-found arms did exactly that until the entry-shaped lookups gained their own INPUT-domain classes. A synthetic label is still legitimate where there is no exception class to name, and that is what the dicts key on. The run arms are the one deliberate exception: they pass `PipelineExecutionError`, the one class a run failure arrives as, and `run_failure_fields()` adds `pipe_code` / `pipe_stack` (the failing pipe and its path) and `cause_type` / `cause_message` (the root fault's, found with `find_root_fault()`, never the router wrapper right under the run error); the classification and the located message come from the run error's report, which is its root fault's. When a derived domain is wrong for a class, declare an explicit `error_domain` on the class — `ModelChoiceNotFoundError` does, because a mistyped model reference is the caller's to fix even though the category is `CONFIGURATION`. The `error_domain` also drives the HTTP-status mapping for downstream APIs — see `error_domain_to_http_status()` in `pipelex/base_exceptions.py` and [Error Model](../../../docs/under-the-hood/error-model.md).- **The `migration` field on a configuration error**: A `PipelexConfigError` carries one when a scan of this machine's configuration directories found something — and only then, so its presence is the test for whether the migration history has anything to say. Whether a command *repairs* it is the separate `would_write` field: true means the configuration is *old*, and the loop is `pipelex-agent migrate --dry-run --format json`, show the user, then `--yes`; false means the block is a diagnosis its `plans` carry and the command would rewrite nothing, so branching on presence alone sends an agent to a run with nothing to do. Its `plans` are the same shape that command emits under its own `plans` key. `error_domain` stays `config`: a domain the hook specification does not know routes to BLOCK, which would stop an agent instead of telling it what to run. See `docs/migration-ledger.md` → "Reporting a stale configuration on a validation error".- **Init**: All commands that need Pipelex use `make_pipelex_for_agent_cli(library_dirs)`. It catches init errors and routes them through `agent_error()`.diff --git a/pipelex/cli/agent_cli/_agent_cli.py b/pipelex/cli/agent_cli/_agent_cli.pyindex e49ea3d36..7dcd54b1f 100644--- a/pipelex/cli/agent_cli/_agent_cli.py+++ b/pipelex/cli/agent_cli/_agent_cli.py@@ -13,7 +13,6 @@ from pipelex.cli.agent_cli.commands.agent_cli_factory import silence_logging_forfrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, agent_error, set_agent_cli_error_formatfrom pipelex.cli.agent_cli.commands.check_model_cmd import agent_check_model_cmdfrom pipelex.cli.agent_cli.commands.codegen.app import codegen_app-from pipelex.cli.agent_cli.commands.concept_cmd import concept_cmdfrom pipelex.cli.agent_cli.commands.doctor_cmd import agent_doctor_cmdfrom pipelex.cli.agent_cli.commands.fix.app import fix_appfrom pipelex.cli.agent_cli.commands.fmt_cmd import fmt_cmd@@ -22,7 +21,6 @@ from pipelex.cli.agent_cli.commands.inputs.app import inputs_appfrom pipelex.cli.agent_cli.commands.lint_cmd import lint_cmdfrom pipelex.cli.agent_cli.commands.migrate_cmd import agent_migrate_cmdfrom pipelex.cli.agent_cli.commands.models_cmd import agent_models_cmd-from pipelex.cli.agent_cli.commands.pipe_cmd import pipe_cmdfrom pipelex.cli.agent_cli.commands.run.app import run_appfrom pipelex.cli.agent_cli.commands.validate.app import validate_appfrom pipelex.cli.version_report import version_report_lines@@ -43,8 +41,6 @@ class PipelexAgentCLI(TyperGroup):"lint","inputs","codegen",- "concept",- "pipe","models","check-model","accept-gateway-terms",@@ -144,8 +140,6 @@ app.command(name="fmt", help="Format a .mthds, .toml, or .plx file in-place")(fmapp.command(name="lint", help="Lint a .mthds, .toml, or .plx file")(lint_cmd)app.add_typer(inputs_app, name="inputs", help="Generate example input JSON for a pipe")app.add_typer(codegen_app, name="codegen", help="Project the crate into typed artifacts (types) and check drift offline (check)")-app.command(name="concept", help="Structure a concept from JSON spec and output TOML")(concept_cmd)-app.command(name="pipe", help="Structure a pipe from JSON spec and output TOML")(pipe_cmd)app.command(name="models", help="List available model presets, aliases, and waterfalls")(agent_models_cmd)app.command(name="check-model", help="Check if a model reference is valid and suggest alternatives")(agent_check_model_cmd)app.command(name="accept-gateway-terms", help="Accept Pipelex Gateway terms and mark inference setup complete")(agent_accept_gateway_terms_cmd)diff --git a/pipelex/cli/agent_cli/commands/agent_output.py b/pipelex/cli/agent_cli/commands/agent_output.pyindex 30ecf4a3b..7a56932e6 100644--- a/pipelex/cli/agent_cli/commands/agent_output.py+++ b/pipelex/cli/agent_cli/commands/agent_output.py@@ -13,9 +13,9 @@ Two independent format axes:``ContextVar``. JSON is the default so any error raised before a command optsin stays machine-parseable.-Commands that don't accept ``--format`` (``inputs``, ``concept``, ``pipe``,-``fmt``, ``lint``, ``accept-gateway-terms``) never touch the ContextVar and-therefore emit JSON errors via the default.+Commands that don't accept ``--format`` (``inputs``, ``fmt``, ``lint``,+``accept-gateway-terms``) never touch the ContextVar and therefore emit JSON+errors via the default."""import sysdiff --git a/pipelex/cli/agent_cli/commands/bundle_path_resolver.py b/pipelex/cli/agent_cli/commands/bundle_path_resolver.pyindex 30339c5d9..a1904517c 100644--- a/pipelex/cli/agent_cli/commands/bundle_path_resolver.py+++ b/pipelex/cli/agent_cli/commands/bundle_path_resolver.py@@ -8,7 +8,6 @@ decision-making; this wrapper owns agent error envelopes.from pathlib import Pathfrom typing import NoReturn-from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.cli.agent_cli.commands.agent_output import agent_errorfrom pipelex.cli.bundle_target_resolution import (BundleTargetResolutionError,@@ -16,6 +15,7 @@ from pipelex.cli.bundle_target_resolution import (BundleTargetResolutionSuccess,resolve_bundle_target_core,)+from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAMEdef _stringify_library_dirs(library_dirs: list[Path] | None) -> list[str] | None:diff --git a/pipelex/cli/agent_cli/commands/check_model_cmd.py b/pipelex/cli/agent_cli/commands/check_model_cmd.pyindex fbf29c499..c0ba11631 100644--- a/pipelex/cli/agent_cli/commands/check_model_cmd.py+++ b/pipelex/cli/agent_cli/commands/check_model_cmd.py@@ -4,10 +4,10 @@ from typing import Annotated, Anyimport typer-from pipelex.builder.operations.models_ops import CATEGORY_TO_MODEL_TYPE, ModelCategoryfrom pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_clifrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, agent_error, agent_success, set_agent_cli_error_formatfrom pipelex.cogt.models.exceptions import ModelReferenceParseError+from pipelex.cogt.models.model_listing import CATEGORY_TO_MODEL_TYPE, ModelCategoryfrom pipelex.cogt.models.model_reference import ModelReferencefrom pipelex.cogt.models.model_suggestion import (KIND_LABELS,diff --git a/pipelex/cli/agent_cli/commands/concept_cmd.py b/pipelex/cli/agent_cli/commands/concept_cmd.pydeleted file mode 100644index 8e5c18818..000000000--- a/pipelex/cli/agent_cli/commands/concept_cmd.py+++ /dev/null@@ -1,134 +0,0 @@-"""Agent CLI concept command - structure concepts from JSON specs with raw TOML output."""--# pyright: reportUnknownMemberType=false--import json-from typing import Annotated, Any--import tomlkit-import typer-from pydantic import ValidationError--from pipelex.builder.concept.concept_spec import ConceptSpec-from pipelex.builder.operations.concept_ops import parse_concept_spec, structure_field_to_dict-from pipelex.cli.agent_cli.commands.agent_output import agent_error-from pipelex.language.toml_string_utils import format_toml_string-from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error_for_agent---def _concept_spec_to_toml(concept_spec: ConceptSpec) -> str:- """Convert a ConceptSpec to TOML string format.-- Args:- concept_spec: The validated ConceptSpec to convert.-- Returns:- TOML string representation of the concept.- """- doc = tomlkit.document()-- # Create the [concept.ConceptName] section- concept_section = tomlkit.table()- concept_item_table = tomlkit.table()-- # Add description- concept_item_table.add("description", format_toml_string(concept_spec.description))-- # Add refines if present- if concept_spec.refines:- concept_item_table.add("refines", concept_spec.refines)-- # Add structure if present- if concept_spec.structure:- structure_table = tomlkit.table()- for field_name, field_spec in concept_spec.structure.items():- field_dict = structure_field_to_dict(field_spec)- # If only description is present, use simple string format- if len(field_dict) == 1 and "description" in field_dict:- structure_table.add(field_name, format_toml_string(field_dict["description"]))- else:- inline_table = tomlkit.inline_table()- for key, value in field_dict.items():- inline_table.append(key, value)- structure_table.add(field_name, inline_table)- concept_item_table.add("structure", structure_table)-- # Build the nested structure: [concept.ConceptName]- concept_section.add(concept_spec.concept_code, concept_item_table)- doc.add("concept", concept_section)- return tomlkit.dumps(doc)---def concept_cmd(- spec: Annotated[- str | None,- typer.Option("--spec", "-s", help="JSON string with concept specification"),- ] = None,- spec_file: Annotated[- str | None,- typer.Option("--spec-file", "-f", help="Path to JSON file with concept specification"),- ] = None,-) -> None:- """Structure a concept from JSON spec and output TOML.-- Takes a concept specification in JSON format and converts it to valid Pipelex- TOML format. Validates the spec before conversion.-- Outputs raw TOML to stdout on success, JSON to stderr on error with exit code 1.-- JSON spec format:- {- "concept_code": "MyConceptName",- "description": "Description of the concept",- "refines": "Text", // Optional: native concept to refine- "structure": { // Optional: for structured concepts- "field_name": "Field description", // Simple text field- "typed_field": {- "type": "integer",- "description": "Field description",- "required": true- }- }- }-- Examples:- pipelex-agent concept --spec '{"concept_code": "Invoice", "description": "A commercial invoice", "refines": "Text"}'- pipelex-agent concept --spec-file concept.json- """- # Validate that exactly one of spec or spec_file is provided- if spec is None and spec_file is None:- agent_error("Either --spec or --spec-file must be provided", error_type="ArgumentError")-- if spec is not None and spec_file is not None:- agent_error("Cannot use both --spec and --spec-file", error_type="ArgumentError")-- # Load spec data- spec_data: dict[str, Any]- try:- if spec_file:- with open(spec_file, encoding="utf-8") as the_file:- spec_data = json.load(the_file)- else:- spec_data = json.loads(spec) # type: ignore[arg-type]- except FileNotFoundError as exc:- agent_error(f"Spec file not found: {spec_file}", error_type="FileNotFoundError", cause=exc)- except json.JSONDecodeError as exc:- agent_error(f"Invalid JSON: {exc.msg}", error_type="JSONDecodeError", cause=exc)-- # Validate and convert spec- try:- concept_spec = parse_concept_spec(spec_data)- toml_content = _concept_spec_to_toml(concept_spec)-- print(toml_content, end="" if toml_content.endswith("\n") else "\n")-- except ValidationError as exc:- message, details = format_pydantic_validation_error_for_agent(exc)- agent_error(message, error_type="ValidationError", cause=exc, validation_details=details)-- except ValueError as exc:- agent_error(str(exc), error_type="ValueError", cause=exc)-- except Exception as exc: # ruff: ignore[blind-except]- # Agent CLI command boundary: agent_error() (NoReturn) converts any unexpected failure into the structured error payload.- agent_error(str(exc), error_type=type(exc).__name__, cause=exc)diff --git a/pipelex/cli/agent_cli/commands/inputs/_inputs_core.py b/pipelex/cli/agent_cli/commands/inputs/_inputs_core.pyindex 57233a095..416102964 100644--- a/pipelex/cli/agent_cli/commands/inputs/_inputs_core.py+++ b/pipelex/cli/agent_cli/commands/inputs/_inputs_core.py@@ -4,9 +4,9 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any, cast-from pipelex.builder.operations.inputs_ops import build_inputs_for_pipefrom pipelex.cli.agent_cli.commands.agent_output import agent_successfrom pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormat, serialize_inputs_template_to_toml+from pipelex.pipeline.inputs_template import build_inputs_for_pipeif TYPE_CHECKING:from pathlib import Path@@ -42,8 +42,7 @@ def emit_inputs_result(result: dict[str, Any], *, template_format: InputsTemplat"""Emit an inputs-generation result in the requested template format.JSON keeps the structured success envelope; TOML prints the raw template to- stdout, in the same spirit as the ``concept``/``pipe`` raw-TOML passthrough- commands. The default light template needs the inline-table layout (``light=True``) so a+ stdout. The default light template needs the inline-table layout (``light=True``) so abare scalar declared after a structured value stays valid TOML, and carries the declaredconcept as a ``# concept: ...`` comment per key (same hints the human ``build inputs --formattoml`` writes); ``--explicit`` restores the all-tables envelope layout. A pipe that declaresdiff --git a/pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py b/pipelex/cli/agent_cli/commands/inputs/bundle_cmd.pyindex a3cab23f8..e42c08315 100644--- a/pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py+++ b/pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py@@ -8,7 +8,6 @@ from typing import Annotated, Anyimport typer-from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_clifrom pipelex.cli.agent_cli.commands.agent_output import agent_error, extract_validation_errorsfrom pipelex.cli.agent_cli.commands.inputs._inputs_core import emit_inputs_result, inputs_core@@ -17,6 +16,7 @@ from pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_filefrom pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormatfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import Pipelex+from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.pipeline.exceptions import ValidateBundleErrordiff --git a/pipelex/cli/agent_cli/commands/models_cmd.py b/pipelex/cli/agent_cli/commands/models_cmd.pyindex 5678c00ab..e1e17e86d 100644--- a/pipelex/cli/agent_cli/commands/models_cmd.py+++ b/pipelex/cli/agent_cli/commands/models_cmd.py@@ -4,9 +4,9 @@ from typing import Annotatedimport typer-from pipelex.builder.operations.models_ops import ModelCategory, format_models_markdown, list_modelsfrom pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_clifrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, agent_error, agent_success, set_agent_cli_error_format+from pipelex.cogt.models.model_listing import ModelCategory, format_models_markdown, list_modelsfrom pipelex.pipelex import Pipelexdiff --git a/pipelex/cli/agent_cli/commands/pipe_cmd.py b/pipelex/cli/agent_cli/commands/pipe_cmd.pydeleted file mode 100644index b040d1f71..000000000--- a/pipelex/cli/agent_cli/commands/pipe_cmd.py+++ /dev/null@@ -1,356 +0,0 @@-"""Agent CLI pipe command - structure pipes from JSON specs with raw TOML output."""--# pyright: reportUnknownMemberType=false-# pyright: reportArgumentType=false-# pyright: reportUnknownVariableType=false-# pyright: reportUnusedExcept=false-# mypy: disable-error-code="arg-type,no-any-return,attr-defined"--import json-from typing import Annotated, Any--import tomlkit-import typer-from pydantic import ValidationError--from pipelex.builder.operations.pipe_ops import parse_pipe_spec-from pipelex.builder.pipe.pipe_batch_spec import PipeBatchSpec-from pipelex.builder.pipe.pipe_compose_spec import PipeComposeSpec-from pipelex.builder.pipe.pipe_condition_spec import PipeConditionSpec-from pipelex.builder.pipe.pipe_doc_gen_spec import PipeDocGenSpec-from pipelex.builder.pipe.pipe_extract_spec import PipeExtractSpec-from pipelex.builder.pipe.pipe_func_spec import PipeFuncSpec-from pipelex.builder.pipe.pipe_img_gen_spec import PipeImgGenSpec-from pipelex.builder.pipe.pipe_judge_spec import PipeJudgeSpec-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpec-from pipelex.builder.pipe.pipe_search_spec import PipeSearchSpec-from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.builder.pipe.pipe_signature_spec import PipeSignatureSpec-from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.builder.pipe.pipe_spec_map import pipe_type_to_spec_class-from pipelex.builder.pipe.pipe_structure_spec import PipeStructureSpec-from pipelex.cli.agent_cli.commands.agent_output import agent_error-from pipelex.language.toml_string_utils import format_toml_string-from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error_for_agent---def _pipe_spec_to_toml(pipe_spec: PipeSpec) -> str:- """Convert a PipeSpec to TOML string format.-- Args:- pipe_spec: The validated PipeSpec to convert.-- Returns:- TOML string representation of the pipe.- """- doc = tomlkit.document()- pipe_item_table = tomlkit.table()-- # Add type — a signature is typeless (no type line; omitting the type IS the signature); every- # concrete pipe names its type.- if not isinstance(pipe_spec, PipeSignatureSpec):- pipe_item_table.add("type", pipe_spec.type)-- # Add description- pipe_item_table.add("description", format_toml_string(pipe_spec.description))-- # Add inputs as inline table- if pipe_spec.inputs:- inputs_inline = tomlkit.inline_table()- for input_name, input_concept in pipe_spec.inputs.items():- inputs_inline.append(input_name, input_concept)- pipe_item_table.add("inputs", inputs_inline)-- # Add output- pipe_item_table.add("output", pipe_spec.output)-- # Add type-specific fields- _add_type_specific_fields(pipe_spec=pipe_spec, pipe_table=pipe_item_table)-- # Build the nested structure: [pipe.pipe_code]- pipe_section = tomlkit.table()- pipe_section.add(pipe_spec.pipe_code, pipe_item_table)- doc.add("pipe", pipe_section)- return tomlkit.dumps(doc)---def _add_type_specific_fields(*, pipe_spec: PipeSpec, pipe_table: tomlkit.TOMLDocument | tomlkit.items.Table) -> None: # type: ignore[name-defined]- """Add type-specific fields to the pipe TOML table.-- Args:- pipe_spec: The pipe spec with type-specific fields.- pipe_table: The TOML table to add fields to.- """- if isinstance(pipe_spec, PipeLLMSpec):- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)- if pipe_spec.system_prompt:- pipe_table.add("system_prompt", format_toml_string(pipe_spec.system_prompt))- if pipe_spec.prompt:- pipe_table.add("prompt", format_toml_string(pipe_spec.prompt))- if pipe_spec.structuring_method is not None:- pipe_table.add("structuring_method", pipe_spec.structuring_method)-- elif isinstance(pipe_spec, PipeStructureSpec):- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)-- elif isinstance(pipe_spec, PipeDocGenSpec):- pipe_table.add("format", str(pipe_spec.format))- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)- if pipe_spec.template is not None:- pipe_table.add("template", format_toml_string(pipe_spec.template))- if pipe_spec.template_file is not None:- pipe_table.add("template_file", pipe_spec.template_file)- if pipe_spec.filename is not None:- pipe_table.add("filename", pipe_spec.filename)-- elif isinstance(pipe_spec, PipeComposeSpec):- if pipe_spec.construct_spec is not None:- # Construct mode: serialize the construct block as a nested TOML table- construct_table = tomlkit.table()- for field_name, field_value in pipe_spec.construct_spec.items():- if isinstance(field_value, dict):- field_inline = tomlkit.inline_table()- inner_dict: dict[str, Any] = field_value- for key, value in inner_dict.items():- field_inline.append(key, value)- construct_table.add(field_name, field_inline)- else:- construct_table.add(field_name, field_value)- pipe_table.add("construct", construct_table)- else:- # Template mode — guard optional fields like other pipe types do- if pipe_spec.target_format is not None:- pipe_table.add("target_format", str(pipe_spec.target_format))- if pipe_spec.template is not None:- pipe_table.add("template", format_toml_string(pipe_spec.template))-- elif isinstance(pipe_spec, PipeSequenceSpec):- steps_array = tomlkit.array()- for step in pipe_spec.steps:- step_inline = tomlkit.inline_table()- step_inline.append("pipe", step.pipe_code)- step_inline.append("result", step.result)- if step.batch_over is not None:- step_inline.append("batch_over", step.batch_over)- if step.batch_as is not None:- step_inline.append("batch_as", step.batch_as)- steps_array.append(step_inline)- pipe_table.add("steps", steps_array)-- elif isinstance(pipe_spec, PipeParallelSpec):- pipe_table.add("add_each_output", pipe_spec.add_each_output)- branches_array = tomlkit.array()- for branch in pipe_spec.branches:- branch_inline = tomlkit.inline_table()- branch_inline.append("pipe", branch.pipe_code)- branch_inline.append("result", branch.result)- branches_array.append(branch_inline)- pipe_table.add("branches", branches_array)-- elif isinstance(pipe_spec, PipeConditionSpec):- pipe_table.add("expression", pipe_spec.jinja2_expression_template)- outcomes_table = tomlkit.inline_table()- for condition, outcome in pipe_spec.outcomes.items():- outcomes_table.append(condition, outcome)- pipe_table.add("outcomes", outcomes_table)- pipe_table.add("default_outcome", pipe_spec.default_outcome)-- elif isinstance(pipe_spec, PipeBatchSpec):- pipe_table.add("branch_pipe_code", pipe_spec.branch_pipe_code)- pipe_table.add("input_list_name", pipe_spec.input_list_name)- pipe_table.add("input_item_name", pipe_spec.input_item_name)-- elif isinstance(pipe_spec, PipeExtractSpec):- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)-- elif isinstance(pipe_spec, PipeImgGenSpec):- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)- pipe_table.add("prompt", format_toml_string(pipe_spec.prompt))-- elif isinstance(pipe_spec, PipeFuncSpec):- pipe_table.add("function_name", pipe_spec.function_name)-- elif isinstance(pipe_spec, PipeSearchSpec):- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)- pipe_table.add("prompt", format_toml_string(pipe_spec.prompt))- if pipe_spec.from_date is not None:- pipe_table.add("from_date", pipe_spec.from_date)- if pipe_spec.to_date is not None:- pipe_table.add("to_date", pipe_spec.to_date)- if pipe_spec.include_domains is not None:- pipe_table.add("include_domains", pipe_spec.include_domains)- if pipe_spec.exclude_domains is not None:- pipe_table.add("exclude_domains", pipe_spec.exclude_domains)- if pipe_spec.max_results is not None:- pipe_table.add("max_results", pipe_spec.max_results)-- elif isinstance(pipe_spec, PipeJudgeSpec):- if pipe_spec.model:- pipe_table.add("model", pipe_spec.model)- # A tool that writes a PipeJudge writes `question`, never its `prompt` synonym.- pipe_table.add("question", format_toml_string(pipe_spec.question))- if pipe_spec.options is not None:- options_table = tomlkit.inline_table()- for option, description in pipe_spec.options.items():- options_table.append(option, description)- pipe_table.add("options", options_table)- if pipe_spec.levels is not None:- pipe_table.add("levels", pipe_spec.levels)- if pipe_spec.criteria is not None:- criteria_table = tomlkit.inline_table()- for verdict, criterion in pipe_spec.criteria.model_dump(exclude_none=True).items():- criteria_table.append(verdict, criterion)- pipe_table.add("criteria", criteria_table)- if pipe_spec.threshold is not None:- pipe_table.add("threshold", pipe_spec.threshold)-- elif isinstance(pipe_spec, PipeSignatureSpec):- if pipe_spec.signature_for is not None:- pipe_table.add("signature_for", pipe_spec.signature_for)---def pipe_cmd(- pipe_type: Annotated[- str | None,- typer.Option(- "--type",- "--pipe-type",- "--pipe_type",- "-t",- help=f"Pipe type. Must be one of: {list(pipe_type_to_spec_class)}. Omit for a signature (contract only, no type).",- ),- ] = None,- spec: Annotated[- str | None,- typer.Option("--spec", "-s", help="JSON string with pipe specification"),- ] = None,- spec_file: Annotated[- str | None,- typer.Option("--spec-file", "-f", help="Path to JSON file with pipe specification"),- ] = None,-) -> None:- """Structure a pipe from JSON spec and output TOML.-- Takes a pipe specification in JSON format and converts it to valid Pipelex- TOML format. Validates the spec before conversion.-- Outputs raw TOML to stdout on success, JSON to stderr on error with exit code 1.-- JSON spec format (varies by pipe type):-- PipeLLM:- {- "pipe_code": "my_pipe",- "description": "What the pipe does",- "inputs": {"input_name": "ConceptName"},- "output": "OutputConcept",- "model": "$writing-creative",- "prompt": "Your prompt with @block and $inline vars"- }-- PipeSequence:- {- "pipe_code": "my_sequence",- "description": "Chain of operations",- "inputs": {"doc": "Document"},- "output": "Result",- "steps": [- {"pipe": "step_one", "result": "step_one_result"},- {"pipe": "step_two", "result": "step_two_result"}- ]- }-- PipeSignature (contract only — omit the type): a pipe with no type and no implementation is a- signature. Omit --type (and any "type" key) and declare only the contract:- {- "pipe_code": "summarize_doc",- "description": "Produces a summary of a document.",- "inputs": {"doc": "Document"},- "output": "Text"- }-- Examples:- pipelex-agent pipe --type PipeLLM --spec '{"pipe_code": "summarize", ...}'- pipelex-agent pipe --type PipeSequence --spec-file pipe.json- pipelex-agent pipe --spec '{"pipe_code": "summarize_doc", "description": "...", "output": "Text"}'- """- # Validate that exactly one of spec or spec_file is provided- if spec is None and spec_file is None:- agent_error("Either --spec or --spec-file must be provided", error_type="ArgumentError")-- if spec is not None and spec_file is not None:- agent_error("Cannot use both --spec and --spec-file", error_type="ArgumentError")-- # Load spec data- spec_data: dict[str, Any]- try:- if spec_file:- with open(spec_file, encoding="utf-8") as the_file:- spec_data = json.load(the_file)- else:- spec_data = json.loads(spec) # type: ignore[arg-type]- except FileNotFoundError as exc:- agent_error(f"Spec file not found: {spec_file}", error_type="FileNotFoundError", cause=exc)- except json.JSONDecodeError as exc:- agent_error(f"Invalid JSON: {exc.msg}", error_type="JSONDecodeError", cause=exc)-- # Accept "pipe_type" as an alias for "type" in the JSON spec- if "pipe_type" in spec_data and "type" not in spec_data:- spec_data["type"] = spec_data.pop("pipe_type")- elif "pipe_type" in spec_data:- spec_data.pop("pipe_type")-- # Resolve pipe type: CLI option takes precedence, then extract from spec JSON, else None (typeless).- # A typeless spec is a signature — parse_pipe_spec routes it to PipeSignatureSpec (or raises a- # teaching error if it declares more than the contract). An explicit "PipeSignature" is rejected- # there with a migration error — a signature has no type.- resolved_pipe_type: str | None- if pipe_type is not None:- resolved_pipe_type = pipe_type- elif "type" in spec_data:- raw_pipe_type = spec_data.pop("type")- if raw_pipe_type is None:- # A signature is authored by OMITTING the `type` key — an explicit null is not the same as- # absent, and must not silently collapse to a typeless signature.- agent_error(- "A JSON `type` key cannot be null. Delete the `type` key — a pipe with no `type` and no "- "implementation is a signature (contract only).",- error_type="ArgumentError",- )- if not isinstance(raw_pipe_type, str):- # A non-string `type` (list/dict/number) is an authoring mistake — sanitize it at this- # untrusted-input boundary so it surfaces as an actionable ArgumentError, not a cryptic- # internal TypeError (an unhashable list/dict would blow up the membership test downstream).- agent_error(- f"Invalid pipe type '{raw_pipe_type}'. Must be one of: {list(pipe_type_to_spec_class)}, "- "or omit `type` for a signature (contract only, no type).",- error_type="ArgumentError",- )- resolved_pipe_type = raw_pipe_type- else:- resolved_pipe_type = None-- # Validate and convert spec- try:- pipe_spec = parse_pipe_spec(spec_data, pipe_type=resolved_pipe_type)- toml_content = _pipe_spec_to_toml(pipe_spec)-- print(toml_content, end="" if toml_content.endswith("\n") else "\n")-- except ValidationError as exc:- message, details = format_pydantic_validation_error_for_agent(exc)- agent_error(message, error_type="ValidationError", cause=exc, validation_details=details)-- except ValueError as exc:- agent_error(str(exc), error_type="ValueError", cause=exc)-- except Exception as exc: # ruff: ignore[blind-except]- # Agent CLI command boundary: agent_error() (NoReturn) converts any unexpected failure into the structured error payload.- agent_error(str(exc), error_type=type(exc).__name__, cause=exc)diff --git a/pipelex/cli/agent_cli/commands/run/bundle_cmd.py b/pipelex/cli/agent_cli/commands/run/bundle_cmd.pyindex 950fbfb28..b1c01b3ad 100644--- a/pipelex/cli/agent_cli/commands/run/bundle_cmd.py+++ b/pipelex/cli/agent_cli/commands/run/bundle_cmd.py@@ -12,7 +12,6 @@ from mthds.protocol.exceptions import PipelineRequestErrorfrom mthds.runners.api.exceptions import ApiResponseError, ClientAuthenticationErrorfrom mthds.runners.types import RunnerType-from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_clifrom pipelex.cli.agent_cli.commands.agent_output import (CliOutputFormat,@@ -30,6 +29,7 @@ from pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_filefrom pipelex.mthds_parsing.parser import MthdsParserfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import Pipelex+from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.pipeline.exceptions import PipelineExecutionError, ValidateBundleErrorfrom pipelex.pipeline.validate_bundle_translation import translate_to_validate_bundle_errordiff --git a/pipelex/cli/agent_cli/commands/validate/_validate_core.py b/pipelex/cli/agent_cli/commands/validate/_validate_core.pyindex 96d0f9f17..2a04aeff9 100644--- a/pipelex/cli/agent_cli/commands/validate/_validate_core.py+++ b/pipelex/cli/agent_cli/commands/validate/_validate_core.py@@ -160,7 +160,7 @@ async def validate_pipe_core("""library_manager = get_library_manager()# Capture the caller's outer current-library so it can be restored after this temporary validation- # library is torn down (mirrors the builder validate_ops.validate_pipe twin).+ # library is torn down.prev_library_id = get_current_library_id_or_none()library_id, _ = library_manager.open_library()try:diff --git a/pipelex/cli/bundle_target_resolution.py b/pipelex/cli/bundle_target_resolution.pyindex 8dccc50b7..460aa997e 100644--- a/pipelex/cli/bundle_target_resolution.py+++ b/pipelex/cli/bundle_target_resolution.py@@ -4,8 +4,8 @@ from enum import StrEnumfrom pathlib import Pathfrom typing import NamedTuple-from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_file+from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAMEclass BundleTargetResolutionErrorKind(StrEnum):diff --git a/pipelex/cli/commands/build/app.py b/pipelex/cli/commands/build/app.pyindex 0a96edab2..d3205e1dc 100644--- a/pipelex/cli/commands/build/app.py+++ b/pipelex/cli/commands/build/app.py@@ -2,13 +2,11 @@ import typerfrom pipelex.cli.commands.build.inputs.app import build_inputs_appfrom pipelex.cli.commands.build.output.app import build_output_app-from pipelex.cli.commands.build.runner.app import build_runner_appfrom pipelex.cli.commands.build.structures_cmd import build_structures_command-build_app = typer.Typer(help="Build working pipelines from natural language requirements", no_args_is_help=True)+build_app = typer.Typer(help="Generate example inputs, example outputs and structure classes for a pipe", no_args_is_help=True)-# inputs, output, runner are now Typer groups with method/pipe subcommands+# inputs and output are Typer groups with bundle/method/pipe subcommandsbuild_app.add_typer(build_inputs_app, name="inputs", help="Generate example input JSON for a pipe")build_app.add_typer(build_output_app, name="output", help="Generate example output representation for a pipe (JSON, Python, or JSON Schema)")-build_app.add_typer(build_runner_app, name="runner", help="Build the Python code to run a pipe with the necessary inputs")build_app.command("structures", help="Generate Python structure files from concept definitions in MTHDS files")(build_structures_command)diff --git a/pipelex/cli/commands/build/inputs/_inputs_core.py b/pipelex/cli/commands/build/inputs/_inputs_core.pyindex 50317e058..6f3f7a541 100644--- a/pipelex/cli/commands/build/inputs/_inputs_core.py+++ b/pipelex/cli/commands/build/inputs/_inputs_core.py@@ -6,7 +6,6 @@ from pathlib import Pathimport typerfrom posthog import tag-from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTS_TOML_FILE_NAMEfrom pipelex.cli.cli_factory import make_pipelex_for_clifrom pipelex.cli.error_handlers import (ErrorContext,@@ -19,6 +18,7 @@ from pipelex.interpreter_hub import get_library_manager, get_required_entry_pipefrom pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormat, NoInputsRequiredError, render_inputs, render_inputs_tomlfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import PACKAGE_VERSION+from pipelex.pipeline.default_file_names import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTS_TOML_FILE_NAMEfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle import validate_bundlefrom pipelex.runtime_hub import get_telemetry_managerdiff --git a/pipelex/cli/commands/build/inputs/bundle_cmd.py b/pipelex/cli/commands/build/inputs/bundle_cmd.pyindex 0cd99e9d3..699980753 100644--- a/pipelex/cli/commands/build/inputs/bundle_cmd.py+++ b/pipelex/cli/commands/build/inputs/bundle_cmd.py@@ -5,10 +5,10 @@ from typing import Annotatedimport typer-from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.cli.commands.build.inputs._inputs_core import execute_generate_inputsfrom pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_filefrom pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormat+from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAMEdef build_inputs_bundle_cmd(diff --git a/pipelex/cli/commands/build/inputs/method_cmd.py b/pipelex/cli/commands/build/inputs/method_cmd.pyindex 34d3a67c3..2fcaea4f0 100644--- a/pipelex/cli/commands/build/inputs/method_cmd.py+++ b/pipelex/cli/commands/build/inputs/method_cmd.py@@ -5,10 +5,10 @@ from typing import Annotatedimport typer-from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTS_TOML_FILE_NAMEfrom pipelex.cli.commands.build.inputs._inputs_core import execute_generate_inputsfrom pipelex.cli.method_resolver import method_output_base_dir, resolve_method_targetfrom pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormat+from pipelex.pipeline.default_file_names import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTS_TOML_FILE_NAMEdef build_inputs_method_cmd(diff --git a/pipelex/cli/commands/build/output/bundle_cmd.py b/pipelex/cli/commands/build/output/bundle_cmd.pyindex 54c07aedb..7cafc5543 100644--- a/pipelex/cli/commands/build/output/bundle_cmd.py+++ b/pipelex/cli/commands/build/output/bundle_cmd.py@@ -5,10 +5,10 @@ from typing import Annotatedimport typer-from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.cli.commands.build.output._output_core import execute_generate_outputfrom pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormatfrom pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_file+from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAMEdef build_output_bundle_cmd(diff --git a/pipelex/cli/commands/build/runner/__init__.py b/pipelex/cli/commands/build/runner/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/pipelex/cli/commands/build/runner/_runner_core.py b/pipelex/cli/commands/build/runner/_runner_core.pydeleted file mode 100644index e4745231c..000000000--- a/pipelex/cli/commands/build/runner/_runner_core.py+++ /dev/null@@ -1,193 +0,0 @@-from __future__ import annotations--import asyncio-from typing import TYPE_CHECKING--import typer-from mthds.package.manifest.schema import MTHDS_STANDARD_VERSION-from posthog import tag--from pipelex.builder.runner_code import generate_runner_code-from pipelex.cli.cli_factory import make_pipelex_for_cli-from pipelex.cli.error_handlers import (- ErrorContext,- handle_model_availability_error,- handle_model_choice_error,-)-from pipelex.codegen.emission import write_stamped_projection-from pipelex.codegen.emitters.naming import runtime_to_emitted_class_names-from pipelex.codegen.emitters.target import CodegenKind, CodegenTarget-from pipelex.codegen.emitters.types_emitter import emit_types-from pipelex.codegen.resolved_concepts import resolve_concepts_from_crate-from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError-from pipelex.core.pipes.inputs.exceptions import PipeInputError-from pipelex.core.pipes.variable_multiplicity import parse_concept_with_multiplicity-from pipelex.interpreter_hub import get_current_library_id_or_none, get_library_manager, get_required_entry_pipe-from pipelex.libraries.crate_normalization import normalize_crate-from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError-from pipelex.pipelex import PACKAGE_VERSION-from pipelex.pipeline.exceptions import ValidateBundleError-from pipelex.pipeline.validate_bundle import validate_bundle-from pipelex.runtime_hub import get_telemetry_manager-from pipelex.system.runtime import IntegrationMode-from pipelex.system.telemetry.events import EventProperty-from pipelex.tools.misc.file_utils import (- ensure_directory_for_file_path,- save_text_to_path,-)--if TYPE_CHECKING:- from pathlib import Path-- from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipelexBundleBlueprint--COMMAND = "build"-SUB_COMMAND_RUNNER = "runner"---async def _prepare_runner_core(- *, pipe_code: str | None = None, bundle_path: Path | None = None, output_path: Path | None = None, library_dirs: list[Path] | None = None-) -> None:- """Core logic for generating a Python runner file."""- all_blueprints: list[PipelexBundleBlueprint] = []-- if bundle_path:- try:- validate_bundle_result = await validate_bundle(mthds_file_path=bundle_path, library_dirs=library_dirs)- all_blueprints.extend(validate_bundle_result.blueprints)- first_blueprint = validate_bundle_result.blueprints[0]- if not pipe_code:- main_pipe_code = first_blueprint.main_pipe- if not main_pipe_code:- typer.secho(- f"Bundle '{bundle_path}' has no main_pipe declared. Use --pipe to specify which pipe to use.",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(1)- typer.echo(f"Using main pipe '{main_pipe_code}' from bundle '{bundle_path}'")- pipe_code = main_pipe_code- else:- typer.echo(f"Using pipe '{pipe_code}' from bundle '{bundle_path}'")- except FileNotFoundError as exc:- typer.secho(f"Failed to load bundle '{bundle_path}': {exc}", fg=typer.colors.RED, err=True)- raise typer.Exit(1) from exc- except ValidateBundleError as exc:- typer.secho(f"Failed to load bundle '{bundle_path}': {exc}", fg=typer.colors.RED, err=True)- raise typer.Exit(1) from exc- except PipeInputError as exc:- typer.secho(f"Failed to load bundle '{bundle_path}': {exc}", fg=typer.colors.RED, err=True)- raise typer.Exit(1) from exc- else:- typer.secho("Failed to run: no bundle file specified", fg=typer.colors.RED, err=True)- raise typer.Exit(1)-- try:- the_pipe = get_required_entry_pipe(pipe_code=pipe_code)- except Exception as exc:- # CLI command boundary: any failure resolving the pipe is reported to the user and exits via typer.Exit.- typer.secho(f"Error: Failed to resolve pipe '{pipe_code}': {exc}", fg=typer.colors.RED)- raise typer.Exit(1) from exc-- if output_path:- final_output_path = output_path- else:- bundle_dir = bundle_path.parent- final_output_path = bundle_dir / f"run_{pipe_code}.py"- output_dir = final_output_path.parent-- # Emit the types projection (stamped structures.py + codegen.lock) into structures/ via the- # codegen engine. validate_bundle left its loaded-and-validated library open and current, so the- # crate is read from there (D6: the normalized crate is built from a valid library).- structures_output_dir = output_dir / "structures"- class_name_overrides: dict[str, str] = {}- library_id = get_current_library_id_or_none()- crate = get_library_manager().get_crate(library_id) if library_id else None- if crate is not None:- normalized_crate = normalize_crate(crate, mthds_version=MTHDS_STANDARD_VERSION)- emitted = emit_types(normalized_crate, target=CodegenTarget.PYTHON_STRUCTURES)- report = write_stamped_projection(- emitted,- output_dir=structures_output_dir,- crate_fingerprint=normalized_crate.fingerprint,- engine_version=PACKAGE_VERSION,- kind=CodegenKind.TYPES,- target=CodegenTarget.PYTHON_STRUCTURES,- )- for filename in report.written:- typer.secho(f"Generated {structures_output_dir / filename}", fg=typer.colors.GREEN)- for filename in report.unchanged:- typer.secho(f"Unchanged {structures_output_dir / filename}", fg=typer.colors.BLUE)- for filename in report.removed:- typer.secho(f"Removed stale {structures_output_dir / filename}", fg=typer.colors.YELLOW)- class_name_overrides = runtime_to_emitted_class_names(resolve_concepts_from_crate(normalized_crate))-- output_is_list = False- for blueprint in all_blueprints:- if blueprint.pipe and pipe_code in blueprint.pipe:- pipe_blueprint = blueprint.pipe[pipe_code]- output_parse = parse_concept_with_multiplicity(pipe_blueprint.output)- output_is_list = output_parse.multiplicity is not None- break-- if library_dirs:- pipelex_library_dir = str(library_dirs[0].resolve())- else:- pipelex_library_dir = str(bundle_path.parent.resolve())-- try:- runner_code = generate_runner_code(- pipe=the_pipe,- output_multiplicity=output_is_list,- library_dir=pipelex_library_dir,- class_name_overrides=class_name_overrides,- )- except Exception as exc:- # CLI command boundary: any failure generating the runner code is reported to the user and exits via typer.Exit.- typer.secho(f"Error generating runner code: {exc}", fg=typer.colors.RED)- raise typer.Exit(1) from exc-- try:- ensure_directory_for_file_path(file_path=final_output_path)- save_text_to_path(text=runner_code, path=final_output_path)- typer.secho(f"Generated runner file: {final_output_path}", fg=typer.colors.GREEN)- except Exception as exc:- # CLI command boundary: any failure writing the file is reported to the user and exits via typer.Exit.- typer.secho(f"Error saving file: {exc}", fg=typer.colors.RED)- raise typer.Exit(1) from exc---def execute_prepare_runner(- *,- pipe_code: str | None,- bundle_path: Path | None,- output_path: Path | None,- library_dirs: list[Path] | None = None,- telemetry_command_label: str = f"{COMMAND} {SUB_COMMAND_RUNNER}",-) -> None:- """Synchronous entry point wrapping the async runner generation with Pipelex setup/teardown."""- pipelex_instance = make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_BUILD_RUNNER)-- try:- with get_telemetry_manager().telemetry_context():- tag(name=EventProperty.INTEGRATION, value=IntegrationMode.CLI)- tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)- tag(name=EventProperty.CLI_COMMAND, value=telemetry_command_label)-- asyncio.run(- _prepare_runner_core(- pipe_code=pipe_code,- bundle_path=bundle_path,- output_path=output_path,- library_dirs=library_dirs,- )- )-- except PipeOperatorModelChoiceError as exc:- handle_model_choice_error(exc, context=ErrorContext.BUILD)-- except PipeOperatorModelAvailabilityError as exc:- handle_model_availability_error(exc, context=ErrorContext.BUILD)-- finally:- pipelex_instance.teardown()diff --git a/pipelex/cli/commands/build/runner/app.py b/pipelex/cli/commands/build/runner/app.pydeleted file mode 100644index b5aa321ed..000000000--- a/pipelex/cli/commands/build/runner/app.py+++ /dev/null@@ -1,9 +0,0 @@-import typer--from pipelex.cli.commands.build.runner.bundle_cmd import build_runner_bundle_cmd-from pipelex.cli.commands.build.runner.method_cmd import build_runner_method_cmd--build_runner_app = typer.Typer(help="Build Python code to run a pipe", no_args_is_help=True)--build_runner_app.command("bundle", help="Build runner from a bundle file or directory")(build_runner_bundle_cmd)-build_runner_app.command("method", help="Build runner for an installed method")(build_runner_method_cmd)diff --git a/pipelex/cli/commands/build/runner/bundle_cmd.py b/pipelex/cli/commands/build/runner/bundle_cmd.pydeleted file mode 100644index 5b5ca0628..000000000--- a/pipelex/cli/commands/build/runner/bundle_cmd.py+++ /dev/null@@ -1,95 +0,0 @@-from __future__ import annotations--from pathlib import Path-from typing import Annotated--import typer--from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAME-from pipelex.cli.commands.build.runner._runner_core import execute_prepare_runner-from pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_file---def build_runner_bundle_cmd(- path: Annotated[- str,- typer.Argument(help="Path to a .mthds bundle file or a pipeline directory"),- ],- pipe: Annotated[- str | None,- typer.Option("--pipe", help="Pipe code to use (optional if the .mthds declares a main_pipe)"),- ] = None,- output_path: Annotated[- str | None,- typer.Option("--output", "-o", help="Path to save the generated Python file (defaults to target's directory)"),- ] = None,- library_dirs: Annotated[- list[str] | None,- typer.Option("--library-dirs", "-L", help="Directories to search for pipe definitions (.mthds files). Can be specified multiple times."),- ] = None,-) -> None:- """Build a Python runner file from a bundle file or pipeline directory.-- Examples:- pipelex build runner bundle my_bundle.mthds- pipelex build runner bundle pipeline_01/- pipelex build runner bundle my_bundle.mthds --pipe my_pipe- pipelex build runner bundle my_bundle.mthds --output runner.py- """- target_path = Path(path)- bundle_path: Path- output_path_path = Path(output_path) if output_path else None-- if target_path.is_dir():- bundle_file = target_path / DEFAULT_BUNDLE_FILE_NAME- if bundle_file.is_file():- bundle_path = bundle_file- else:- mthds_files = list(target_path.glob(f"*{MTHDS_EXTENSION}"))- if len(mthds_files) == 0:- typer.secho(- f"Failed to run: no .mthds bundle file found in directory '{path}'",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(1)- if len(mthds_files) > 1:- mthds_names = ", ".join(mthds_file.name for mthds_file in mthds_files)- typer.secho(- f"Failed to run: multiple .mthds files found in '{path}' ({mthds_names}) "- f"and no '{DEFAULT_BUNDLE_FILE_NAME}'. "- f"Pass the .mthds file directly, e.g.: pipelex build runner bundle {target_path / mthds_files[0].name}",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(1)- bundle_path = mthds_files[0]-- # Add directory as library dir- target_dir_str = str(target_path)- if library_dirs is None:- library_dirs = [target_dir_str]- elif target_dir_str not in library_dirs:- library_dirs = [target_dir_str, *library_dirs]-- typer.echo(f"Auto-detected bundle: {bundle_path}")-- elif is_pipelex_file(target_path):- bundle_path = target_path- else:- typer.secho(- f"Failed to run: '{path}' is not a .mthds file or directory.\n"- f" To build a runner, pass a .mthds file or directory: pipelex build runner bundle <path>",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(1)-- library_dirs_paths = [Path(lib_dir) for lib_dir in library_dirs] if library_dirs else None-- execute_prepare_runner(- pipe_code=pipe,- bundle_path=bundle_path,- output_path=output_path_path,- library_dirs=library_dirs_paths,- )diff --git a/pipelex/cli/commands/build/runner/method_cmd.py b/pipelex/cli/commands/build/runner/method_cmd.pydeleted file mode 100644index cea9a0365..000000000--- a/pipelex/cli/commands/build/runner/method_cmd.py+++ /dev/null@@ -1,82 +0,0 @@-from __future__ import annotations--import shutil-from pathlib import Path-from typing import Annotated--import typer--from pipelex.cli.commands.build.runner._runner_core import execute_prepare_runner-from pipelex.cli.method_resolver import method_output_base_dir, resolve_method_target---def build_runner_method_cmd(- name: Annotated[- str,- typer.Argument(help="Installed method name, method address (github.com/owner/repo\\[/name]\\[@tag]), or GitHub URL"),- ],- pipe: Annotated[- str | None,- typer.Option("--pipe", help="Pipe code (overrides method's main_pipe)"),- ] = None,- output_path: Annotated[- str | None,- typer.Option("--output", "-o", help="Path to save the generated Python file"),- ] = None,- library_dirs: Annotated[- list[str] | None,- typer.Option("--library-dirs", "-L", help="Directories to search for pipe definitions (.mthds files). Can be specified multiple times."),- ] = None,-) -> None:- """Build a Python runner file for an installed method.-- Resolves the method, finds a .mthds bundle in its directory,- and generates a runner file.-- Examples:- pipelex build runner method my-method- pipelex build runner method my-method --pipe custom_pipe- pipelex build runner method my-method --output runner.py- """- pipe_code, method_library_dirs, method = resolve_method_target(- method_name=name,- pipe_override=pipe,- library_dirs=library_dirs,- )- if not method.mthds_files:- typer.secho(- f"Method '{name}' has no .mthds bundle files.",- fg=typer.colors.RED,- err=True,- )- raise typer.Exit(1)-- bundle_path = method.mthds_files[0]- # Default output to a results/ folder under the method's output base (the caller's CWD for fetched methods)- output_path_path: Path- if output_path:- output_path_path = Path(output_path)- else:- output_path_path = method_output_base_dir(method=method) / "results" / f"run_{pipe_code}.py"-- if method.provenance is not None:- # The generated script embeds the library dir it loads at run time, and a fetched- # package's directory is an ephemeral clone deleted at process exit — so a runner- # pointing there would be broken on first use. Materialize the package beside the- # generated script and embed that path instead, keeping the artifact self-contained.- materialized_dir = output_path_path.parent / method.name- shutil.copytree(method.path, materialized_dir, ignore=shutil.ignore_patterns(".git", "__pycache__"), dirs_exist_ok=True)- bundle_path = materialized_dir / bundle_path.relative_to(method.path)- method_library_dirs = [str(materialized_dir)]- typer.secho(f"Copied fetched package into {materialized_dir} (referenced by the generated runner)", fg=typer.colors.BLUE, err=True)-- library_dirs_paths = [Path(lib_dir) for lib_dir in method_library_dirs]- if library_dirs:- library_dirs_paths.extend(Path(lib_dir) for lib_dir in library_dirs)-- execute_prepare_runner(- pipe_code=pipe_code,- bundle_path=bundle_path,- output_path=output_path_path,- library_dirs=library_dirs_paths,- )diff --git a/pipelex/cli/commands/bundle_path_resolver.py b/pipelex/cli/commands/bundle_path_resolver.pyindex 60c6a2994..c98794b23 100644--- a/pipelex/cli/commands/bundle_path_resolver.py+++ b/pipelex/cli/commands/bundle_path_resolver.py@@ -10,13 +10,13 @@ from typing import NoReturnimport typer-from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.cli.bundle_target_resolution import (BundleTargetResolutionError,BundleTargetResolutionErrorKind,BundleTargetResolutionSuccess,resolve_bundle_target_core,)+from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAMEdef _stringify_library_dirs(library_dirs: list[Path] | None) -> list[str] | None:diff --git a/pipelex/cli/commands/codegen/inputs_cmd.py b/pipelex/cli/commands/codegen/inputs_cmd.pyindex 20738a9e4..9957ee119 100644--- a/pipelex/cli/commands/codegen/inputs_cmd.py+++ b/pipelex/cli/commands/codegen/inputs_cmd.py@@ -14,7 +14,6 @@ from typing import Annotatedimport typerfrom posthog import tag-from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTS_TOML_FILE_NAMEfrom pipelex.cli.cli_factory import make_pipelex_for_clifrom pipelex.cli.commands.crate_loading import load_normalized_crate_or_exitfrom pipelex.cli.error_handlers import ErrorContext@@ -24,6 +23,7 @@ from pipelex.libraries.pipe.exceptions import PipeLibraryErrorfrom pipelex.pipe_machinery.pipe_abstract import PipeAbstractfrom pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormat, NoInputsRequiredError, render_inputs, render_inputs_tomlfrom pipelex.pipelex import Pipelex+from pipelex.pipeline.default_file_names import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTS_TOML_FILE_NAMEfrom pipelex.runtime_hub import get_telemetry_managerfrom pipelex.system.runtime import IntegrationModefrom pipelex.system.telemetry.events import EventPropertydiff --git a/pipelex/cli/commands/run/_inputs_file_loader.py b/pipelex/cli/commands/run/_inputs_file_loader.pyindex dde781f84..957e6eb00 100644--- a/pipelex/cli/commands/run/_inputs_file_loader.py+++ b/pipelex/cli/commands/run/_inputs_file_loader.py@@ -14,10 +14,10 @@ import datetimefrom pathlib import Pathfrom typing import Any-from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTS_TOML_FILE_NAMEfrom pipelex.cli.commands.run.exceptions import AmbiguousInputsFilesErrorfrom pipelex.core.stuffs.date_content import DateContentfrom pipelex.core.stuffs.time_content import TimeContent+from pipelex.pipeline.default_file_names import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTS_TOML_FILE_NAMEfrom pipelex.tools.misc.json_utils import load_json_dict_from_pathfrom pipelex.tools.misc.toml_utils import load_toml_from_pathdiff --git a/pipelex/cli/commands/run/bundle_cmd.py b/pipelex/cli/commands/run/bundle_cmd.pyindex cb420bf48..13d68d533 100644--- a/pipelex/cli/commands/run/bundle_cmd.py+++ b/pipelex/cli/commands/run/bundle_cmd.py@@ -5,11 +5,11 @@ from typing import Annotatedimport typer-from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.cli.commands.run._inputs_file_loader import find_default_inputs_filefrom pipelex.cli.commands.run._run_core import COMMAND, execute_run, validate_run_flag_combinationfrom pipelex.cli.commands.run.exceptions import AmbiguousInputsFilesErrorfrom pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_file+from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAMEdef run_bundle_cmd(diff --git a/pipelex/cli/dev_cli/commands/generate_corpus_vocabulary_cmd.py b/pipelex/cli/dev_cli/commands/generate_corpus_vocabulary_cmd.pyindex 99ed10b52..0ab1683c0 100644--- a/pipelex/cli/dev_cli/commands/generate_corpus_vocabulary_cmd.py+++ b/pipelex/cli/dev_cli/commands/generate_corpus_vocabulary_cmd.py@@ -144,14 +144,6 @@ _PIPE_TYPE_EXCLUSIONS: dict[PipeType, str] = {# exclusion maps are: a code that leaves the registry breaks this module at import instead of leaving# a dead exclusion behind in the generated file._ERROR_TYPE_EXCLUSIONS: dict[ValidationErrorType, str] = {- PipeValidationErrorType.CIRCULAR_DEPENDENCY_ERROR: (- "Raised only from the pipe sorter, and the pipe sorter runs only on `PipelexBundleSpec.to_blueprint()` "- "— the builder's spec-to-blueprint conversion, which is how an AI-authored spec becomes a bundle. A "- "`.mthds` file parses straight into a blueprint and never passes through it, so no corpus entry can "- "produce this. Measured rather than read off the call graph: a self-referencing PipeSequence fails the "- "dry run with `DryRunError`, and a mutually recursive PipeCondition pair exhausts the interpreter's "- "stack — neither reports a circular dependency."- ),PipeValidationErrorType.OPTIONAL_FORCE_REDUNDANT: ("Advisory-only: it rides the validation report's `warnings` array and never makes a verdict invalid. An ""entry contract that models one `expected_error` on an invalid entry has nowhere to put a warning on a "diff --git a/pipelex/cli/dev_cli/commands/keyword_only_guard.py b/pipelex/cli/dev_cli/commands/keyword_only_guard.pyindex e0be8c72d..dfa8b2eee 100644--- a/pipelex/cli/dev_cli/commands/keyword_only_guard.py+++ b/pipelex/cli/dev_cli/commands/keyword_only_guard.py@@ -751,7 +751,7 @@ def find_violations_in_source(source: str, *, module_qname: str, relative_path:Args:source: The Python source text to scan.- module_qname: The dotted module path used to qualify each def (e.g. ``pipelex.builder.foo``).+ module_qname: The dotted module path used to qualify each def (e.g. ``pipelex.cogt.foo``).relative_path: The source file path relative to the repo root (used in the violation's sort/identity key).grants: The subject-grants registry content (see :func:`load_subject_grants`).@@ -812,7 +812,7 @@ def fix_source(Args:source: The Python source text to fix.- module_qname: The dotted module path used to qualify each def (e.g. ``pipelex.builder.foo``).+ module_qname: The dotted module path used to qualify each def (e.g. ``pipelex.cogt.foo``).relative_path: The source file path relative to the repo root (used in each violation's key).grants: The subject-grants registry content (an ungranted subject is a fixable violation)."""diff --git a/pipelex/cli/error_handlers.py b/pipelex/cli/error_handlers.pyindex 4b97a9c89..978a836fc 100644--- a/pipelex/cli/error_handlers.py+++ b/pipelex/cli/error_handlers.py@@ -43,7 +43,6 @@ class ErrorContext(StrEnum):VALIDATION_BEFORE_SHOW_MODELS = "Pre-validation (show models)"VALIDATION_BEFORE_SHOW_BACKENDS = "Pre-validation (show backends)"VALIDATION_BEFORE_PIPE_RUN = "Pre-validation (pipe run)"- VALIDATION_BEFORE_BUILD_RUNNER = "Pre-validation (build runner)"VALIDATION_BEFORE_BUILD_INPUTS = "Pre-validation (build inputs)"VALIDATION_BEFORE_BUILD_OUTPUT = "Pre-validation (build output)"KIT = "Kit operation"diff --git a/pipelex/codegen/emitters/naming.py b/pipelex/codegen/emitters/naming.pyindex 8134eaff8..28eb8bb00 100644--- a/pipelex/codegen/emitters/naming.py+++ b/pipelex/codegen/emitters/naming.py@@ -82,21 +82,3 @@ def allocate_ts_type_names(library: ResolvedLibrary) -> dict[str, str]:def _ts_symbols_are_free(type_name: str, *, used_symbols: set[str]) -> bool:"""Whether a type and its derived schema identifier are both unclaimed."""return type_name not in used_symbols and f"{type_name}Schema" not in used_symbols---def runtime_to_emitted_class_names(library: ResolvedLibrary) -> dict[str, str]:- """Map each concept's runtime structure-class name to its emitted Python class name.-- The runtime materializes every non-native concept under the domain-qualified spelling- (`make_qualified_structure_class_name`), while the Python emitters name bare-when-unique — this- mapping lets a consumer (the runner-script generator) spell classes the way the emitted- projection defines them. Opaque Python-backed concepts (`structure = "<ClassName>"`) keep the- user's real class at runtime, so they are deliberately not remapped.- """- mapping: dict[str, str] = {}- for concept in library.concepts:- if concept.is_native or concept.opaque_python_class:- continue- runtime_name = make_qualified_structure_class_name(domain_code=concept.domain, concept_code=concept.code)- mapping[runtime_name] = python_class_name(domain=concept.domain, code=concept.code, needs_qualification=concept.needs_qualification)- return mappingdiff --git a/pipelex/cogt/content_generation/dry_mock.py b/pipelex/cogt/content_generation/dry_mock.pyindex 0547a4e54..c6d6fe93c 100644--- a/pipelex/cogt/content_generation/dry_mock.py+++ b/pipelex/cogt/content_generation/dry_mock.py@@ -33,7 +33,6 @@ class than the one the provider is constrained by. Exotic format constraintsmust declare ``examples`` / ``mock_format`` — see ``DryRunObjectFidelityError``."""-from collections.abc import Sequencefrom datetime import datetimefrom typing import Any, Protocol@@ -86,10 +85,6 @@ from pipelex.system.job_metadata import JobMetadatafrom pipelex.tools.jinja2.jinja2_parsing import check_jinja2_parsingfrom pipelex.tools.typing.pydantic_utils import BaseModelTypeVar-# The pipe code every mocked bundle answers to — shared with BundleHeaderSpec.main_pipe's-# examples so bundle dry-validation's mocked header names a pipe that exists (D3).-MOCK_MAIN_PIPE_CODE = "mock_main"-# Sentinel model identifiers so a synthetic usage record is never confused with real inference.DRY_RUN_INFERENCE_MODEL_NAME = "dry_run"DRY_RUN_INFERENCE_MODEL_ID = "dry_run"@@ -211,29 +206,6 @@ def build_mock_objects(model_class: type[BaseModelTypeVar], *, count: int) -> liraise DryRunMockBuildError.for_object_class(model_class.__name__) from exc-def stamp_mock_main_coordination(items: Sequence[Any]) -> None:- """Set the first item's ``pipe_code`` to ``"mock_main"`` — the single home of this coordination (D3).-- WHY: bundle dry-validation mocks a ``BundleHeaderSpec`` whose ``main_pipe`` field declares- ``examples=["mock_main"]`` (``pipelex/builder/bundle_header_spec.py``), so the polyfactory mock- header names ``mock_main`` as the bundle's main pipe. Every mock that fabricates a *list of pipe- specs* must therefore make its first item answer to that name, or the mocked bundle fails its own- main-pipe check. Callers: the mock-input factory (``working_memory_factory``), the batch- controller's dry aggregation (``pipe_batch``), and the dry object-list leaf mock- (:func:`dry_llm_gen_object_list`). The stamp is a no-op for items without a ``pipe_code`` field.-- The item is now the *caller's own* class, not a throwaway schema rebuild, so the assignment can hit- a model config the caller chose — ``frozen=True`` or ``validate_assignment`` — and raise. Surface- that as the same typed :class:`DryRunMockBuildError` the surrounding mock build uses, rather than- letting a raw ``ValidationError`` escape from a mutation the caller never asked for.- """- if items and hasattr(items[0], "pipe_code"):- try:- items[0].pipe_code = MOCK_MAIN_PIPE_CODE- except ValidationError as exc:- raise DryRunMockBuildError.for_object_class(type(items[0]).__name__) from exc--def _nb_list_items(object_assignment: ObjectAssignment) -> int:"""Resolve the object-list mock length: the assignment's fixed ``nb_items`` wins (D11), including 0."""if object_assignment.nb_items is not None:@@ -322,17 +294,9 @@ def dry_llm_gen_object(object_assignment: ObjectAssignment, *, object_class: typdef dry_llm_gen_object_list(object_assignment: ObjectAssignment, *, object_class: type[BaseModel] | None = None) -> list[BaseModel]:- """Dry leaf for ``llm_gen_object_list``: ``nb_items`` mocks + one synthetic report.-- Applies :func:`stamp_mock_main_coordination` so bundle dry-validation's mocked- ``BundleHeaderSpec.main_pipe`` check passes through the leaf mock (D3). The stamp is- unconditional on ``is_mock_usage`` — it only matters to bundle dry-validation and is- harmless elsewhere.- """+ """Dry leaf for ``llm_gen_object_list``: ``nb_items`` mocks + one synthetic report."""log.verbose(f"🤡 DRY RUN: llm_gen_object_list for '{object_assignment.object_class_name}'")- items = _leaf_gen_object_list(object_assignment, report_func=_dry_report_func(object_assignment.cogt_run_params), object_class=object_class)- stamp_mock_main_coordination(items)- return items+ return _leaf_gen_object_list(object_assignment, report_func=_dry_report_func(object_assignment.cogt_run_params), object_class=object_class)def dry_templating_gen_text(templating_assignment: TemplatingAssignment) -> str:diff --git a/pipelex/builder/operations/models_ops.py b/pipelex/cogt/models/model_listing.pysimilarity index 98%rename from pipelex/builder/operations/models_ops.pyrename to pipelex/cogt/models/model_listing.pyindex 0c933ea84..25a01cc92 100644--- a/pipelex/builder/operations/models_ops.py+++ b/pipelex/cogt/models/model_listing.py@@ -1,4 +1,7 @@-"""Core operation for listing model presets, aliases, and waterfalls."""+"""The model listing: the deck's presets, aliases and waterfalls, by category.++Behind `pipelex-agent models`, `pipelex-agent check-model` and the runner's model listing.+"""from enum import StrEnumfrom typing import Anydiff --git a/pipelex/core/concepts/concept.py b/pipelex/core/concepts/concept.pyindex 973dbfcc7..0233b77d1 100644--- a/pipelex/core/concepts/concept.py+++ b/pipelex/core/concepts/concept.py@@ -183,7 +183,6 @@ class Concept(ConceptAbstract):structure_class: type[StuffContent],output_format: ConceptRepresentationFormat,multiplicity: VariableMultiplicity | None = None,- class_name_overrides: dict[str, str] | None = None,) -> tuple[dict[str, Any], set[str]]:"""Render a representation for this concept.@@ -196,8 +195,6 @@ class Concept(ConceptAbstract):variable-length list, an int for a fixed count. A list-shaped multiplicity wrapsthe content in a list/array, and a fixed count reaches the SCHEMA render as`minItems`/`maxItems` bounds.- class_name_overrides: Optional runtime-class-name -> rendered-name mapping applied to- Python instantiation code and imports (see ConceptRepresentationGenerator)Returns:Tuple of (representation dict, imports_needed set)@@ -209,7 +206,7 @@ class Concept(ConceptAbstract):case ConceptRepresentationFormat.SCHEMA:return self._render_schema_representation(structure_class=structure_class, multiplicity=multiplicity)case ConceptRepresentationFormat.JSON | ConceptRepresentationFormat.PYTHON:- generator = ConceptRepresentationGenerator(output_format, class_name_overrides=class_name_overrides)+ generator = ConceptRepresentationGenerator(output_format)# For inputs, we only want required fields (not optional ones)result = generator.generate_representation(self.concept_ref, structure_class=structure_class, include_optional=False)diff --git a/pipelex/core/concepts/concept_representation_generator.py b/pipelex/core/concepts/concept_representation_generator.pyindex 682169e10..4e1db0766 100644--- a/pipelex/core/concepts/concept_representation_generator.py+++ b/pipelex/core/concepts/concept_representation_generator.py@@ -38,19 +38,13 @@ class ConceptRepresentationGenerator:{"concept": "domain.ConceptCode", "content": "MyClass(field1='value1', ...)"}"""- def __init__(self, output_format: ConceptRepresentationFormat, *, class_name_overrides: dict[str, str] | None = None):+ def __init__(self, output_format: ConceptRepresentationFormat):"""Initialize the generator.Args:output_format: The representation format to generate.- class_name_overrides: Optional runtime-class-name -> rendered-name mapping. Python- representations spell class names as the runtime classes are named; a caller that- pairs the representation with codegen-emitted classes (whose names may differ, e.g.- bare-when-unique vs domain-qualified) passes the mapping so instantiation code and- ``imports_needed`` use the emitted spellings."""self.output_format = output_format- self._class_name_overrides = class_name_overrides or {}self._imports_needed: set[str] = set()@property@@ -101,7 +95,7 @@ class ConceptRepresentationGenerator:Returns:Dict (JSON) or string (Python) representing the class"""- class_name = self._class_name_overrides.get(content_class.__name__, content_class.__name__)+ class_name = content_class.__name__self._imports_needed.add(class_name)fields_dict = self._generate_fields_dict(content_class, include_optional=include_optional)@@ -283,7 +277,7 @@ class ConceptRepresentationGenerator:Returns:Dict (JSON) or string (Python)"""- class_name = self._class_name_overrides.get(model_class.__name__, model_class.__name__)+ class_name = model_class.__name__self._imports_needed.add(class_name)fields_dict: dict[str, Any] = {}diff --git a/pipelex/core/memory/working_memory_factory.py b/pipelex/core/memory/working_memory_factory.pyindex 7c534ac69..790c425b5 100644--- a/pipelex/core/memory/working_memory_factory.py+++ b/pipelex/core/memory/working_memory_factory.py@@ -6,7 +6,6 @@ from polyfactory.exceptions import FactoryExceptionfrom pydantic import BaseModel, ValidationErrorfrom pipelex import log-from pipelex.cogt.content_generation.dry_mock import stamp_mock_main_coordinationfrom pipelex.cogt.content_generation.dry_run_factory import DryRunFactoryfrom pipelex.core.concepts.concept_provider_abstract import ConceptProviderAbstractfrom pipelex.core.memory.exceptions import WorkingMemoryFactoryError@@ -21,12 +20,10 @@ from pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.core.stuffs.text_content import TextContentfrom pipelex.runtime_hub import get_class_registry-# Field names that require snake_case format for pipelex bundle specs-# Note: main_pipe is NOT included here because BundleHeaderSpec.main_pipe has-# examples=["mock_main"] that should take precedence to coordinate with pipe_specs mocking+# Field names whose mocked values must be snake_case codes, as MTHDS domain and pipe codes areSNAKE_CASE_FIELD_NAMES = {"domain", "domain_code", "pipe_code"}-# Field names that require PascalCase format for pipelex concept specs+# Field names whose mocked values must be PascalCase codes, as MTHDS concept codes arePASCAL_CASE_FIELD_NAMES = {"concept_code"}@@ -214,15 +211,9 @@ class WorkingMemoryFactory(BaseModel):Uses DryRunFactory to generate mock values with field-specific generatorsfor known constrained fields (e.g., domain, pipe_code require snake_case).-- For base classes that have concrete subclasses (like PipeSpec), picks a random- subclass for mocking to ensure discriminator fields are valid."""structure_class = typed_named_stuff_spec.structure_class- # Check if this is a base class with subclasses and pick a concrete one for mocking- structure_class = cls._get_mockable_class(structure_class)-mock_factory = DryRunFactory.make_dry_run_factory(object_class=structure_class,snake_case_field_names=SNAKE_CASE_FIELD_NAMES,@@ -230,26 +221,6 @@ class WorkingMemoryFactory(BaseModel):)return mock_factory.build(factory_use_construct=True) # type: ignore[no-any-return]- @classmethod- def _get_mockable_class(cls, structure_class: type[StuffContent]) -> type[StuffContent]:- """Get a concrete class to use for mocking.-- If the class has subclasses defined in the same module (indicating it's a base class- for a discriminated union), picks a random subclass. Otherwise returns the class as-is.- """- # Import here to avoid circular imports- from pipelex.builder.pipe.pipe_spec import PipeSpec # ruff: ignore[import-outside-top-level]-- # Check for specific base classes that need special handling- if structure_class is PipeSpec:- # PipeSpec has many subclasses - pick one that has minimal extra required fields- # PipeBatchSpec is chosen as it's commonly used and has straightforward fields- from pipelex.builder.pipe.pipe_batch_spec import PipeBatchSpec # ruff: ignore[import-outside-top-level]-- return PipeBatchSpec-- return structure_class-@classmethoddef make_mock_stuff(cls, typed_named_stuff_spec: TypedNamedStuffSpec) -> Stuff:"""Create a single mock `Stuff` from a `TypedNamedStuffSpec`.@@ -274,7 +245,6 @@ class WorkingMemoryFactory(BaseModel):nb_stuffs = typed_named_stuff_spec.multiplicityitems: list[StuffContent] = [cls.make_mock_content(typed_named_stuff_spec) for _ in range(nb_stuffs)]- stamp_mock_main_coordination(items)mock_list_content = ListContent[StuffContent](items=items)return StuffFactory.make_stuff(diff --git a/pipelex/errors/error_pages_generator.py b/pipelex/errors/error_pages_generator.pyindex 006a57b8d..15ea75275 100644--- a/pipelex/errors/error_pages_generator.py+++ b/pipelex/errors/error_pages_generator.py@@ -402,7 +402,6 @@ _SUBSYSTEM_SECTIONS: tuple[tuple[str, str, str], ...] = (("pipe_operators", "authoring-and-language", "Pipe operators"),("pipe_controllers", "authoring-and-language", "Pipe controllers"),("pipe_signature", "authoring-and-language", "Pipe signatures"),- ("builder", "authoring-and-language", "Builder"),("libraries", "authoring-and-language", "Libraries"),# Execution & runtime("pipe_run", "execution-and-runtime", "Pipe execution"),diff --git a/pipelex/kit/agent_rules/pipelex_standards.md b/pipelex/kit/agent_rules/pipelex_standards.mdindex 79fbe2768..424f4d2bc 100644--- a/pipelex/kit/agent_rules/pipelex_standards.md+++ b/pipelex/kit/agent_rules/pipelex_standards.md@@ -1,11 +1,8 @@# Standards related to developing the Pipelex codebase-## Spec vs Blueprint Architecture+## Blueprints-- **Blueprints** (`pipelex/pipe_operators/`, `pipelex/pipe_controllers/`, `pipelex/pipe_machinery/`, `pipelex/mthds_parsing/`, `pipelex/core/`) are the MTHDS language reference — what `.mthds` files parse into. The base `PipeBlueprint` lives in `pipe_machinery/`, the bundle blueprint the parser produces in `mthds_parsing/`, and the concept/domain blueprints in `core/`.-- **Specs** (`pipelex/builder/pipe/`) are a convenience authoring format for AI agents. Each spec has `to_blueprint()` that transforms it into the corresponding blueprint. Spec-level fields may differ from blueprint-level fields.--When adding validation or fields, decide which layer they belong to. Language rules go on blueprints; authoring convenience goes on specs. See `pipelex/builder/CLAUDE.md` for details.+**Blueprints** (`pipelex/pipe_operators/`, `pipelex/pipe_controllers/`, `pipelex/pipe_machinery/`, `pipelex/mthds_parsing/`, `pipelex/core/`) are the MTHDS language reference — what `.mthds` files parse into. The base `PipeBlueprint` lives in `pipe_machinery/`, the bundle blueprint the parser produces in `mthds_parsing/`, and the concept/domain blueprints in `core/`. A language rule or field goes on the blueprint, since a method is written as MTHDS directly.## Main configdiff --git a/pipelex/language/toml_string_utils.py b/pipelex/language/toml_string_utils.pyindex 121f1f1c6..a0baf6e67 100644--- a/pipelex/language/toml_string_utils.py+++ b/pipelex/language/toml_string_utils.py@@ -1,7 +1,7 @@"""Shared TOML string formatting utilities.Provides a pure function for building tomlkit string nodes with multi-line-support, used by both MthdsFactory (with config) and the agent CLI (with defaults).+support, used by MthdsFactory."""from __future__ import annotationsdiff --git a/pipelex/libraries/library_manager.py b/pipelex/libraries/library_manager.pyindex bdab7e608..46ab8bf95 100644--- a/pipelex/libraries/library_manager.py+++ b/pipelex/libraries/library_manager.py@@ -14,7 +14,6 @@ from mthds.package.manifest.schema import MTHDS_STANDARD_VERSION, MethodsManifesfrom pydantic import BaseModel, PydanticUserError, ValidationErrorfrom typing_extensions import override-import pipelex.builder as builder_pkg # package import — used for __file__ pathfrom pipelex import logfrom pipelex.base_exceptions import PipelexError, SecurityError, error_domain_is_inputfrom pipelex.cogt.exceptions import ModelChoiceNotFoundError@@ -506,9 +505,7 @@ class LibraryManager(LibraryManagerAbstract):# built class escapes; such a file then travels as source and still never executes here.sources_by_dir = {library_dir: FuncRegistryUtils.read_py_sources(folder_path=library_dir) for library_dir in all_dirs}ensure_no_structured_content_in_library_sources(sources_by_dir=sources_by_dir)- # No force-include here (unlike the direct branch): the only force-included dir is pipelex's- # own builder package, which must NOT travel in a customer crate — the sandbox has pipelex- # installed. Accumulate across dirs, but fail loud on a relpath collision: the sandbox writes+ # Accumulate across dirs, but fail loud on a relpath collision: the sandbox writes# sources flat by relpath, so two dirs sharing a path would otherwise silently clobber one# customer's code and run the wrong PipeFunc body.captured_sources = self._library_sources.setdefault(library_id, {})@@ -534,14 +531,10 @@ class LibraryManager(LibraryManagerAbstract):ClassRegistryUtils.import_modules_in_folder(folder_path=library_dir,base_class_names=[StructuredContent.__name__],- force_include_dirs=[Path(builder_pkg.__file__).parent],)# Import files that contain @pipe_func decorated functions (uses AST pre-check) and# register them in the process-global func_registry.- FuncRegistryUtils.register_funcs_in_folder(- folder_path=library_dir,- force_include_dirs=[Path(builder_pkg.__file__).parent],- )+ FuncRegistryUtils.register_funcs_in_folder(folder_path=library_dir)# Auto-discover and register all StructuredContent classes from sys.modulesnum_registered = ClassRegistryUtils.auto_register_all_subclasses(diff --git a/pipelex/libraries/library_utils.py b/pipelex/libraries/library_utils.pyindex 7fc6f305b..39992931b 100644--- a/pipelex/libraries/library_utils.py+++ b/pipelex/libraries/library_utils.py@@ -2,7 +2,6 @@ from importlib.resources import filesfrom importlib.resources.abc import Traversablefrom pathlib import Path-import pipelex.builder as builder_pkg # package import — used for __file__ pathfrom pipelex import logfrom pipelex.config import get_configfrom pipelex.mthds_parsing.helpers import MTHDS_EXTENSION, is_pipelex_file@@ -76,7 +75,6 @@ def get_pipelex_mthds_files_from_dirs(dirs: set[Path]) -> list[Path]:dir_path=dir_path,pattern=f"*{MTHDS_EXTENSION}",excluded_dirs=list(get_config().interpreter.scan.excluded_dirs),- force_include_dirs=[str(Path(builder_pkg.__file__).parent)],)# Filter to only include valid Pipelex filesdiff --git a/pipelex/mthds_parsing/pipe_sorter.py b/pipelex/mthds_parsing/pipe_sorter.pydeleted file mode 100644index 6717abdce..000000000--- a/pipelex/mthds_parsing/pipe_sorter.py+++ /dev/null@@ -1,99 +0,0 @@-"""Topological sorting utilities for pipe dependencies."""--from pipelex.core.pipes.exceptions import PipeValidationError-from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipeBlueprintUnion-from pipelex.validation_error_types import PipeValidationErrorType---def sort_pipes_by_dependencies(- pipes: dict[str, PipeBlueprintUnion],- *,- domain_code: str | None = None,-) -> list[tuple[str, PipeBlueprintUnion]]:- """Sort pipes by their dependencies using depth-first pre-order traversal.-- This performs a depth-first traversal where controllers appear before their dependencies,- and dependencies are visited in the order specified by the controller (e.g., step order- for PipeSequence). This ordering is intuitive for understanding pipeline structure.-- Args:- pipes: Dictionary mapping pipe_code to PipeBlueprintUnion- domain_code: Declaring domain of the bundle, carried onto the- circular-dependency error so the wire item stays domain-qualified-- Returns:- List of (pipe_code, pipe_blueprint) tuples sorted with controllers before dependencies.- For PipeSequence, dependencies follow step order. For others, alphabetical order.-- Raises:- PipeValidationError: If circular dependencies are detected among pipes-- Example:- >>> pipes = {- ... "pipe_c": pipe_c_blueprint, # sequence with steps: pipe_a, pipe_b- ... "pipe_a": pipe_a_blueprint, # no dependencies- ... "pipe_b": pipe_b_blueprint, # no dependencies- ... }- >>> sorted_pipes = sort_pipes_by_dependencies(pipes)- >>> [code for code, _ in sorted_pipes]- ['pipe_c', 'pipe_a', 'pipe_b']- """- # Find root pipes (those not depended upon by anyone)- all_dependencies: set[str] = set()- for pipe_blueprint in pipes.values():- all_dependencies.update(pipe_blueprint.pipe_dependencies)-- root_pipes = [code for code in pipes if code not in all_dependencies]-- # Depth-first traversal to order pipes- visited: set[str] = set()- visiting: set[str] = set() # For cycle detection- sorted_pipes: list[tuple[str, PipeBlueprintUnion]] = []-- def visit(pipe_code: str) -> None:- if pipe_code in visited:- return- if pipe_code in visiting:- msg = f"Circular dependency detected involving pipe: {pipe_code}"- raise PipeValidationError(- message=msg,- domain_code=domain_code,- pipe_code=pipe_code,- error_type=PipeValidationErrorType.CIRCULAR_DEPENDENCY_ERROR,- )- if pipe_code not in pipes:- # Dependency not in this bundle, skip it- return-- visiting.add(pipe_code)- pipe_blueprint = pipes[pipe_code]-- # Add current pipe first (pre-order)- sorted_pipes.append((pipe_code, pipe_blueprint))-- # Visit dependencies in order- ordered_deps = pipe_blueprint.ordered_pipe_dependencies- if ordered_deps:- # Use ordered dependencies (e.g., PipeSequence steps)- for dep_code in ordered_deps:- if dep_code in pipes:- visit(dep_code)- else:- # Use alphabetical order for determinism- for dep_code in sorted(pipe_blueprint.pipe_dependencies):- if dep_code in pipes:- visit(dep_code)-- visited.add(pipe_code)- visiting.remove(pipe_code)-- # Start traversal from root pipes (sorted for determinism)- for pipe_code in sorted(root_pipes):- visit(pipe_code)-- # Ensure all pipes are included (handle disconnected components)- for pipe_code in sorted(pipes.keys()):- if pipe_code not in visited:- visit(pipe_code)-- return sorted_pipesdiff --git a/pipelex/mthds_parsing/validation_error_categorizer.py b/pipelex/mthds_parsing/validation_error_categorizer.pyindex a7ec37375..30feee71e 100644--- a/pipelex/mthds_parsing/validation_error_categorizer.py+++ b/pipelex/mthds_parsing/validation_error_categorizer.py@@ -20,9 +20,9 @@ PIPELEX_BUNDLE_BLUEPRINT_SOURCE_FIELD = "source"PIPELEX_BUNDLE_BLUEPRINT_MAIN_PIPE_FIELD = "main_pipe"PIPELEX_BUNDLE_BLUEPRINT_PIPE_FIELD = "pipe"-# Distinctive fragments of the two type-tag errors raised by the `pipe` before-validators (via-# `normalize_typeless_signature_section` in `pipe_blueprint.py`, shared by the blueprint and spec-# layers). Kept in sync with those single-source messages. They map to DIFFERENT structured+# Distinctive fragments of the two type-tag errors raised by the bundle blueprint's `pipe`+# before-validator (via `normalize_typeless_signature_section` in `pipe_blueprint.py`). Kept in sync+# with those single-source messages. They map to DIFFERENT structured# categories — no-type-declared is `MISSING_PIPE_TYPE`, the retired-tag-declared is `UNKNOWN_PIPE_TYPE`# (a declared-but-invalid type) — and both name the pipe as ``Pipe `<code>``` so the pipe code is# recoverable from the message. See `_categorize_typeless_pipe_error`.diff --git a/pipelex/pipe_controllers/batch/pipe_batch.py b/pipelex/pipe_controllers/batch/pipe_batch.pyindex 784343760..8f0ec0f14 100644--- a/pipelex/pipe_controllers/batch/pipe_batch.py+++ b/pipelex/pipe_controllers/batch/pipe_batch.py@@ -4,14 +4,12 @@ from typing import TYPE_CHECKING, Any, Literal, castfrom typing_extensions import overridefrom pipelex import log-from pipelex.cogt.content_generation.dry_mock import stamp_mock_main_coordinationfrom pipelex.core.memory.absence import AbsenceRecordfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.pipes.exceptions import PipeRunErrorfrom pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecsfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.core.stuffs.list_content import ListContent-from pipelex.core.stuffs.stuff import Stufffrom pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.graph.graph_tracer_manager import GraphTracerManagerfrom pipelex.interpreter_hub import get_pipe_router, get_required_pipe@@ -25,6 +23,7 @@ from pipelex.urls import URLsif TYPE_CHECKING:from collections.abc import Awaitable, Callable+ from pipelex.core.stuffs.stuff import Stufffrom pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.libraries.library_crate import LibraryCrate@@ -267,23 +266,13 @@ class PipeBatch(PipeController):output_name: str | None = None,library_crate: "LibraryCrate | None" = None,) -> PipeOutput:- pipe_output = await self._live_run_controller_pipe(+ return await self._live_run_controller_pipe(job_metadata=job_metadata,working_memory=working_memory,pipe_run_params=pipe_run_params,output_name=output_name,library_crate=library_crate,)- # Dry-run coordination: see stamp_mock_main_coordination's docstring (single home, D3).- # Tri-state read for robustness: the batch's own aggregated output is always stamped by the- # live arm today, but this site must never crash on a resolved-as-absent main.- main_resolved = pipe_output.working_memory.resolve_main_stuff()- if isinstance(main_resolved, Stuff):- content = main_resolved.content- if isinstance(content, ListContent):- list_content = cast("ListContent[StuffContent]", content)- stamp_mock_main_coordination(list_content.items)- return pipe_output@overrideasync def _validate_after_run(diff --git a/pipelex/pipe_machinery/pipe_abstract.py b/pipelex/pipe_machinery/pipe_abstract.pyindex d7c2b0889..4de2593f4 100644--- a/pipelex/pipe_machinery/pipe_abstract.py+++ b/pipelex/pipe_machinery/pipe_abstract.py@@ -204,7 +204,7 @@ class PipeAbstract(ABC, BaseModel):@classmethoddef validate_pipe_code_syntax(cls, code: str) -> str:# Strip namespace prefix if present (e.g., "domain.my_pipe" → "my_pipe").- # The builder LLM sometimes generates dotted pipe codes; the namespace+ # An LLM author sometimes writes dotted pipe codes; the namespace# comes from the bundle's domain field, not from the pipe code itself.if "." in code:bare_code = code.rsplit(".", maxsplit=1)[1]diff --git a/pipelex/pipe_machinery/pipe_blueprint.py b/pipelex/pipe_machinery/pipe_blueprint.pyindex 7c4f1f160..3454deb27 100644--- a/pipelex/pipe_machinery/pipe_blueprint.py+++ b/pipelex/pipe_machinery/pipe_blueprint.py@@ -34,14 +34,12 @@ PIPE_SIGNATURE_TYPE_TAG = "PipeSignature"# is a non-user blueprint field, admitted defensively so this set matches `PipeSignatureBlueprint`'s# writable contract; it is unreachable via the stray-key path today (a section carrying `source` was# dumped from a blueprint, so it also carries `type`, which short-circuits before this set is-# consulted). Single source of truth for the blueprint and spec (authoring) layers — the spec layer-# reuses it augmented with its structural `pipe_code` field (see `SIGNATURE_ONLY_SPEC_KEYS`).+# consulted).SIGNATURE_ONLY_KEYS: frozenset[str] = frozenset({"description", "inputs", "output", "signature_for", "source"})# The contract keys advertised to authors in the typeless-signature teaching message, in display order.-# Deliberately NOT derived from `SIGNATURE_ONLY_KEYS` / `SIGNATURE_ONLY_SPEC_KEYS`: those admit internal-# keys never written by an author (`source`, and the spec layer's structural `pipe_code`) that must not-# leak into a user-facing message. Kept here so the message can never drift from the advertisable set.+# Deliberately NOT derived from `SIGNATURE_ONLY_KEYS`: it admits `source`, an internal key never written+# by an author, which must not leak into a user-facing message. Kept here so the message can never drift from the advertisable set._ADVERTISABLE_SIGNATURE_KEYS: tuple[str, ...] = ("description", "inputs", "output", "signature_for")@@ -50,8 +48,7 @@ def explicit_signature_tag_migration_message(pipe_code: Any) -> str:Starts with ``Pipe `<code>``` so the validation-error categorizer recovers the pipe code from themessage (the error is raised on the aggregate `pipe` field, which carries no pipe code in its- pydantic `loc`). Single source of truth for the blueprint and spec layers and the single-pipe- authoring path (`parse_pipe_spec`).+ pydantic `loc`)."""return (f'Pipe `{pipe_code}` sets `type = "PipeSignature"`, which is no longer a pipe type. '@@ -59,18 +56,15 @@ def explicit_signature_tag_migration_message(pipe_code: Any) -> str:)-def normalize_typeless_signature_section(*, pipe_code: Any, pipe_section: Any, allowed_keys: frozenset[str] = SIGNATURE_ONLY_KEYS) -> Any:+def normalize_typeless_signature_section(*, pipe_code: Any, pipe_section: Any) -> Any:"""Inject the internal `PipeSignature` tag on a typeless contract-only section, reject a typelesssection that declares more than the contract, and reject a section that still writes the retiredexplicit `type = "PipeSignature"` tag. Non-dict values (already-built pipe instances) and sectionsthat name a concrete `type` pass through unchanged.- Shared by the blueprint (`PipelexBundleBlueprint`) and spec (`PipelexBundleSpec`) `pipe`- before-validators so both teaching messages — whose exact wording the validation-error categorizer- keys off (`_MISSING_PIPE_TYPE_MARKER` / `_EXPLICIT_SIGNATURE_TAG_MARKER` in- `validation_error_categorizer.py`) — have a single source of truth. `allowed_keys` differs per- layer: the spec section additionally carries the structural `pipe_code` field, so it passes- `SIGNATURE_ONLY_SPEC_KEYS`.+ Called by the `pipe` before-validator of `PipelexBundleBlueprint`. The exact wording of both+ teaching messages is what the validation-error categorizer keys off (`_MISSING_PIPE_TYPE_MARKER` /+ `_EXPLICIT_SIGNATURE_TAG_MARKER` in `validation_error_categorizer.py`).The injected tag never re-enters this function: it is returned in a fresh dict that downstreamvalidation consumes directly, and `PipeSignatureBlueprint` excludes `type` from its serialization,@@ -84,7 +78,7 @@ def normalize_typeless_signature_section(*, pipe_code: Any, pipe_section: Any, aif typed_section["type"] == PIPE_SIGNATURE_TYPE_TAG:raise ValueError(explicit_signature_tag_migration_message(pipe_code))return typed_section- stray_keys = [key for key in typed_section if key not in allowed_keys]+ stray_keys = [key for key in typed_section if key not in SIGNATURE_ONLY_KEYS]if stray_keys:stray = ", ".join(f"`{key}`" for key in stray_keys)allowed = ", ".join(f"`{key}`" for key in _ADVERTISABLE_SIGNATURE_KEYS)@@ -182,7 +176,7 @@ def valid_pipe_type_tags() -> list[str]:typeless section, so the injected value must pass the `type` field validator and therefore belongsin this allowlist. It is never written by users: an explicit `type = "PipeSignature"` is rejectedupstream in the before-validator (`normalize_typeless_signature_section`). Single source of truth- for the three layers (`PipeBlueprint`, `PipeAbstract`, `PipeSpec`) that gate `type`.+ for the two layers (`PipeBlueprint`, `PipeAbstract`) that gate `type`."""return [*PipeType.value_list(), PIPE_SIGNATURE_TYPE_TAG]diff --git a/pipelex/pipe_signature/pipe_signature.py b/pipelex/pipe_signature/pipe_signature.pyindex 4235454c1..2087eda52 100644--- a/pipelex/pipe_signature/pipe_signature.py+++ b/pipelex/pipe_signature/pipe_signature.py@@ -17,7 +17,7 @@ if TYPE_CHECKING:class PipeSignature(PipeAbstract):- """Runtime stand-in for a contract-only `PipeSignatureSpec`.+ """Runtime pipe for a contract-only `PipeSignatureBlueprint`.Dry-run mints a mock output via the declared `StuffSpec`. Live-run raises`PipeSignatureNotExecutableError` to enforce that signatures must be replaced withdiff --git a/pipelex/pipeline/blueprint_selection.py b/pipelex/pipeline/blueprint_selection.pyindex 146989cb4..4ad15eaff 100644--- a/pipelex/pipeline/blueprint_selection.py+++ b/pipelex/pipeline/blueprint_selection.py@@ -5,7 +5,7 @@ report's ``bundle_blueprint``, the graph arm's target derivation, the Temporal alibrary acquisition, dry-run and inputs derivation) — one rule, one implementation.Lives in its own dedicated module (not next to ``validate_bundle``) so that callers below-the validation layer (``execution_seams``, ``dry_run_pipeline``, ``inputs_ops``) can use it+the validation layer (``execution_seams``, ``dry_run_pipeline``, ``inputs_template``) can use itwithout an import cycle through ``bundle_validator``."""diff --git a/pipelex/pipeline/default_file_names.py b/pipelex/pipeline/default_file_names.pynew file mode 100644index 000000000..0fa4010b3--- /dev/null+++ b/pipelex/pipeline/default_file_names.py@@ -0,0 +1,11 @@+"""The default file names of a method directory: its bundle and its inputs.++`pipelex run` and `pipelex-agent run` look for these names when given a directory, and+`pipelex build inputs` and `pipelex codegen inputs` write the inputs file under them.+"""++from pipelex.mthds_parsing.helpers import MTHDS_EXTENSION++DEFAULT_BUNDLE_FILE_NAME = f"bundle{MTHDS_EXTENSION}"+DEFAULT_INPUTS_FILE_NAME = "inputs.json"+DEFAULT_INPUTS_TOML_FILE_NAME = "inputs.toml"diff --git a/pipelex/builder/operations/inputs_ops.py b/pipelex/pipeline/inputs_template.pysimilarity index 98%rename from pipelex/builder/operations/inputs_ops.pyrename to pipelex/pipeline/inputs_template.pyindex c28a659db..aef37e0c1 100644--- a/pipelex/builder/operations/inputs_ops.py+++ b/pipelex/pipeline/inputs_template.py@@ -1,4 +1,4 @@-"""Core operations for generating input JSON for pipes."""+"""The inputs template engine behind `pipelex-agent inputs`: load a pipe and render the inputs it expects."""from __future__ import annotationsdiff --git a/pipelex/pipeline/runner.py b/pipelex/pipeline/runner.pyindex 702226ffb..7d772d6c6 100644--- a/pipelex/pipeline/runner.py+++ b/pipelex/pipeline/runner.py@@ -15,7 +15,7 @@ from pydantic import Field, ValidationErrorfrom typing_extensions import overridefrom pipelex.base_exceptions import PipelexError-from pipelex.builder.operations.models_ops import ModelCategory, list_models+from pipelex.cogt.models.model_listing import ModelCategory, list_modelsfrom pipelex.config import get_configfrom pipelex.graph.graph_tracer_manager import GraphTracerManagerfrom pipelex.interpreter_hub import (@@ -67,7 +67,7 @@ class PipelexModelDeck(MthdsModelDeck):waterfalls: dict[str, dict[str, list[str]]] = Field(default_factory=dict)-def _protocol_category_of(*, builder_category: ModelCategory) -> MthdsModelCategory:+def _protocol_category_of(*, listing_category: ModelCategory) -> MthdsModelCategory:"""The protocol's model category a category this runtime serves is listed under in `models`.The match is exhaustive on purpose, with no default arm. A runner must never put a value the@@ -79,12 +79,12 @@ def _protocol_category_of(*, builder_category: ModelCategory) -> MthdsModelCategcategory.Args:- builder_category: A category of the builder's model listing.+ listing_category: A category of the model listing.Returns:The protocol category of the same settings family."""- match builder_category:+ match listing_category:case ModelCategory.LLM:return MthdsModelCategory.LLMcase ModelCategory.EXTRACT:@@ -97,8 +97,8 @@ def _protocol_category_of(*, builder_category: ModelCategory) -> MthdsModelCategreturn MthdsModelCategory.JUDGMENT-def _builder_category_of(*, protocol_category: MthdsModelCategory) -> ModelCategory:- """The builder category a protocol `?type=` filter selects.+def _listing_category_of(*, protocol_category: MthdsModelCategory) -> ModelCategory:+ """The model listing's category a protocol `?type=` filter selects.Exhaustive like its inverse: a category a later protocol release adds stops the type checkerhere when the `mthds` pin moves, rather than surfacing as a `ValueError` on the first request@@ -108,7 +108,7 @@ def _builder_category_of(*, protocol_category: MthdsModelCategory) -> ModelCategprotocol_category: A category of the protocol's model list.Returns:- The builder category of the same settings family.+ The model listing's category of the same settings family."""match protocol_category:case MthdsModelCategory.LLM:@@ -469,7 +469,7 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):verdict — `pending_signatures` (qualified refs of pipes still declaredas `PipeSignature` in the assembled library) plus`is_runnable = not pending_signatures`, the same convention as the- agent-CLI / builder validate envelopes. Signatures are never a validation+ agent-CLI validate envelopes. Signatures are never a validationerror (D-B): strict and lenient return the same report body — `allow_signatures`only controls whether signature pipes are mock-run and listed in`validated_pipes`, not the verdict. The "is an unsatisfied signature a@@ -526,7 +526,7 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):async def models(self, category: MthdsModelCategory | None = None) -> PipelexModelDeck:"""The model deck this runtime can route to — protocol `models`.- Wraps the builder's `list_models`: presets project into the protocol's flat+ Wraps the model listing's `list_models`: presets project into the protocol's flat`models` list (each entry carries its category as `type`); the aliases andwaterfalls routing extensions stay keyed by category — the same alias nameexists in several categories pointing at different models, so flattening@@ -539,14 +539,14 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):PipelexModelDeck with the flat model list and the category-keyedaliases and routing waterfalls."""- categories = [_builder_category_of(protocol_category=category)] if category is not None else None+ categories = [_listing_category_of(protocol_category=category)] if category is not None else Nonedeck_raw = list_models(categories=categories)models: list[MthdsModelInfo] = []presets_by_category: dict[str, list[dict[str, Any]]] = deck_raw["presets"]aliases_by_category: dict[str, dict[str, str]] = deck_raw["aliases"]waterfalls_by_category: dict[str, dict[str, list[str]]] = deck_raw["waterfalls"]for category_key, category_presets in presets_by_category.items():- protocol_category = _protocol_category_of(builder_category=ModelCategory(category_key))+ protocol_category = _protocol_category_of(listing_category=ModelCategory(category_key))for preset in category_presets:models.append(MthdsModelInfo(name=preset["name"], type=protocol_category))return PipelexModelDeck(models=models, aliases=aliases_by_category, waterfalls=waterfalls_by_category)diff --git a/pipelex/pipeline/validate_bundle.py b/pipelex/pipeline/validate_bundle.pyindex c3e7a9477..6d2c547ac 100644--- a/pipelex/pipeline/validate_bundle.py+++ b/pipelex/pipeline/validate_bundle.py@@ -56,7 +56,7 @@ class ValidatedPipeEntry(TypedDict):def build_validated_pipes(dry_run_result: dict[str, DryRunOutput]) -> list[ValidatedPipeEntry]:- """Project a dry-run result map into the ``validated_pipes`` JSON list (agent CLI + builder ops).+ """Project a dry-run result map into the ``validated_pipes`` JSON list (agent CLI).Each entry is built from the real per-pipe outcome, so allowed-to-fail FAILUREs and cross-packageSKIPPEDs are reported truthfully rather than flattened to SUCCESS. The entry id is the namespaceddiff --git a/pipelex/runtime_hub.py b/pipelex/runtime_hub.pyindex b6dcef79b..485fefa16 100644--- a/pipelex/runtime_hub.py+++ b/pipelex/runtime_hub.py@@ -7,8 +7,8 @@ execution time whatever is loaded — the **kernel layer**, in the language-impl**The one rule:** ``interpreter_hub`` imports ``runtime_hub``; ``runtime_hub`` must never import``interpreter_hub``. Nothing here may name ``libraries``, ``pipe_operators``, ``pipe_controllers``,-``codegen``, ``builder``, ``interpreter_plugins``, ``pipe_machinery``, ``pipe_signature``,-``mthds_parsing``, ``pipeline`` or ``pipe_run`` at module level. That list is the interpreter's+``codegen``, ``interpreter_plugins``, ``pipe_machinery``, ``pipe_signature``, ``mthds_parsing``,+``pipeline`` or ``pipe_run`` at module level. That list is the interpreter'stop-level packages — all of them, with no qualification — so the property it buys is statedoutright: **importing the Pipelex kernel layer loads zero interpreter modules.** It used to have to trail"…or the Pipe-touching modules of ``core.pipes``", because some of what it forbids lived under adiff --git a/pipelex/system/registries/class_registry_utils.py b/pipelex/system/registries/class_registry_utils.pyindex e8e99ed73..108480d43 100644--- a/pipelex/system/registries/class_registry_utils.py+++ b/pipelex/system/registries/class_registry_utils.py@@ -78,7 +78,6 @@ class ClassRegistryUtils:cls,folder_path: Path,*,- force_include_dirs: list[Path] | None = None,is_recursive: bool = True,base_class_names: list[str] | None = None,) -> None:@@ -97,7 +96,6 @@ class ClassRegistryUtils:base_class_names: Optional list of base class names (e.g. ["StructuredContent"]).If provided, only imports files that contain classes inheritingfrom these base classes. If None, imports all Python files.- force_include_dirs: List of directories to force include even if they are within excluded_dirs."""python_files = find_files_in_dir(@@ -105,7 +103,6 @@ class ClassRegistryUtils:pattern="*.py",is_recursive=is_recursive,excluded_dirs=list(get_config().interpreter.scan.excluded_dirs),- force_include_dirs=[str(force_include_dir) for force_include_dir in force_include_dirs] if force_include_dirs is not None else None,)for python_file in python_files:diff --git a/pipelex/system/registries/func_registry_utils.py b/pipelex/system/registries/func_registry_utils.pyindex 5212979dd..76521235b 100644--- a/pipelex/system/registries/func_registry_utils.py+++ b/pipelex/system/registries/func_registry_utils.py@@ -19,7 +19,7 @@ class FuncRegistryUtils:"""Register all @pipe_func decorated functions from a package.Args:- package_name: Full name of the package (e.g. "pipelex.builder")+ package_name: Full name of the package (e.g. "my_project.pipe_funcs")package: The imported package objectReturns:@@ -76,7 +76,6 @@ class FuncRegistryUtils:cls,folder_path: Path,*,- force_include_dirs: list[Path] | None = None,is_recursive: bool = True,) -> None:"""Discovers and attempts to register all functions in Python files within a folder.@@ -95,7 +94,6 @@ class FuncRegistryUtils:Args:folder_path: Path to folder containing Python filesis_recursive: Whether to search recursively in subdirectories- force_include_dirs: List of directories to force include even if they are within excluded_dirs."""python_files = find_files_in_dir(@@ -103,7 +101,6 @@ class FuncRegistryUtils:pattern="*.py",is_recursive=is_recursive,excluded_dirs=list(get_config().interpreter.scan.excluded_dirs),- force_include_dirs=[str(force_include_dir) for force_include_dir in force_include_dirs] if force_include_dirs is not None else None,)for python_file in python_files:diff --git a/pipelex/test_extras/mthds_corpus/loader.py b/pipelex/test_extras/mthds_corpus/loader.pyindex eabcf81a4..a81eca707 100644--- a/pipelex/test_extras/mthds_corpus/loader.py+++ b/pipelex/test_extras/mthds_corpus/loader.py@@ -11,8 +11,8 @@ from pathlib import Pathfrom pydantic import BaseModel, ConfigDict-from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAMEfrom pipelex.cli.bundle_target_resolution import BundleTargetResolutionError, resolve_bundle_target_core+from pipelex.pipeline.default_file_names import DEFAULT_INPUTS_FILE_NAMEfrom pipelex.test_extras.mthds_corpus.exceptions import CorpusEntryErrorfrom pipelex.test_extras.mthds_corpus.manifest import (ENTRY_NAME_PATTERN,diff --git a/pipelex/test_extras/mthds_corpus/vocabulary.toml b/pipelex/test_extras/mthds_corpus/vocabulary.tomlindex 4f4ff983b..dea67ae3b 100644--- a/pipelex/test_extras/mthds_corpus/vocabulary.toml+++ b/pipelex/test_extras/mthds_corpus/vocabulary.toml@@ -128,10 +128,6 @@ fails_at = "runtime"code = "inadequate_output_multiplicity"fails_at = "runtime"-[error.circular_dependency_error]-code = "circular_dependency_error"-excluded = "Raised only from the pipe sorter, and the pipe sorter runs only on `PipelexBundleSpec.to_blueprint()` — the builder's spec-to-blueprint conversion, which is how an AI-authored spec becomes a bundle. A `.mthds` file parses straight into a blueprint and never passes through it, so no corpus entry can produce this. Measured rather than read off the call graph: a self-referencing PipeSequence fails the dry run with `DryRunError`, and a mutually recursive PipeCondition pair exhausts the interpreter's stack — neither reports a circular dependency."-[error.llm_output_cannot_be_image]code = "llm_output_cannot_be_image"fails_at = "runtime"diff --git a/pipelex/tools/misc/file_utils.py b/pipelex/tools/misc/file_utils.pyindex 1422f909c..10a5099e5 100644--- a/pipelex/tools/misc/file_utils.py+++ b/pipelex/tools/misc/file_utils.py@@ -570,7 +570,6 @@ def find_files_in_dir(pattern: str,is_recursive: bool = True,excluded_dirs: list[str] | None = None,- force_include_dirs: list[str] | None = None,) -> list[Path]:"""Find files matching a pattern in a directory.@@ -579,8 +578,6 @@ def find_files_in_dir(pattern: File pattern to match (e.g. "*.py")is_recursive: Whether to search recursively in subdirectoriesexcluded_dirs: List of directory names to exclude from the search (e.g. [".venv", "node_modules"])- force_include_dirs: List of directories to force include even if they are within excluded_dirs.- Can be either full absolute paths or directory names.Returns:List of matching Path objects@@ -617,28 +614,7 @@ def find_files_in_dir(is_excluded = Truebreak- # Check if file is in a force include directory (forced inclusion despite exclusions)- # Force include dirs can be full paths or directory names- should_force_include = False- if force_include_dirs is not None:- for force_include_dir in force_include_dirs:- force_include_path = Path(force_include_dir)- # If force_include_dir is an absolute path, check if file is under it- if force_include_path.is_absolute():- try:- file.relative_to(force_include_path)- should_force_include = True- break- except ValueError:- # file is not relative to force_include_path- continue- # If force_include_dir is just a directory name, check if it's in the file path parts- elif force_include_dir in file.parts:- should_force_include = True- break-- # Include if not excluded, or if force included- if not is_excluded or should_force_include:+ if not is_excluded:filtered_files.append(file)return filtered_filesdiff --git a/pipelex/tools/typing/pydantic_utils.py b/pipelex/tools/typing/pydantic_utils.pyindex e2846f7e7..2fead90f7 100644--- a/pipelex/tools/typing/pydantic_utils.py+++ b/pipelex/tools/typing/pydantic_utils.py@@ -1,6 +1,5 @@from __future__ import annotations-import json as json_modulefrom enum import StrEnumfrom typing import TYPE_CHECKING, Any, TypeVar, cast@@ -171,128 +170,6 @@ def format_pydantic_validation_error(exc: ValidationError) -> str:return analyze_pydantic_validation_error(exc).error_msg-def _serialize_input_value(value: Any) -> Any:- """Serialize an input value for JSON output, falling back to repr() for non-serializable objects.-- Args:- value: The input value from a pydantic validation error.-- Returns:- A JSON-serializable representation of the value.-- """- if value is None or isinstance(value, (bool, int, float, str)):- return value- if isinstance(value, (dict, list)):- typed_value: dict[str, Any] | list[Any] = cast("dict[str, Any] | list[Any]", value)- try:- json_module.dumps(typed_value)- return typed_value- except (TypeError, ValueError):- return repr(typed_value)- return repr(value)---def _serialize_context(ctx: dict[str, Any]) -> dict[str, Any]:- """Serialize a pydantic error context dict so every value is JSON-safe.-- Pydantic context dicts can contain non-JSON-serializable objects (type objects,- enum instances, etc.). This applies _serialize_input_value() to each value.-- Args:- ctx: The context dict from a pydantic validation error.-- Returns:- A dict with all values guaranteed to be JSON-serializable.-- """- return {key: _serialize_input_value(value) for key, value in ctx.items()}---def format_pydantic_validation_error_for_agent(exc: ValidationError) -> tuple[str, dict[str, Any]]:- """Format a Pydantic ValidationError into a concise message and structured details dict for agent CLI output.-- Args:- exc: The Pydantic ValidationError exception-- Returns:- A tuple of (message, details) where message is a concise summary string- and details is a structured dict with model name, error count, categories, and per-error info.-- """- analysis = analyze_pydantic_validation_error(exc)- model_name = exc.title- error_count = exc.error_count()-- # Build categories dict with only non-empty lists- all_categories: dict[str, list[str]] = {- "missing_fields": analysis.missing_fields,- "extra_fields": analysis.extra_fields,- "type_errors": analysis.type_errors,- "value_errors": analysis.value_errors,- "enum_errors": analysis.enum_errors,- "literal_errors": analysis.literal_errors,- "union_tag_errors": analysis.union_tag_errors,- "model_type_errors": analysis.model_type_errors,- "other_errors": analysis.other_errors,- }- categories = {key: value for key, value in all_categories.items() if value}-- # Build per-error details list- errors: list[dict[str, Any]] = []- for err in exc.errors():- field_path = ".".join(map(str, err["loc"])) if err["loc"] else ""- error_detail: dict[str, Any] = {- "field_path": field_path,- "error_type": err["type"],- "message": err["msg"],- "input_value": _serialize_input_value(err.get("input")),- "context": _serialize_context(err.get("ctx", {})),- }- errors.append(error_detail)-- # Build concise summary message- category_summaries: list[str] = []- if analysis.missing_fields:- field_names = ", ".join(f.strip("'") for f in analysis.missing_fields)- category_summaries.append(- f"missing required fields: '{field_names}'"- if len(analysis.missing_fields) == 1- else f"missing required fields: {', '.join(analysis.missing_fields)}"- )- if analysis.extra_fields:- category_summaries.append(f"extra forbidden fields: {', '.join(analysis.extra_fields)}")- if analysis.type_errors:- category_summaries.append(f"type errors: {', '.join(analysis.type_errors)}")- if analysis.value_errors:- category_summaries.append(f"value errors: {', '.join(analysis.value_errors)}")- if analysis.enum_errors:- category_summaries.append(f"enum errors: {', '.join(analysis.enum_errors)}")- if analysis.literal_errors:- category_summaries.append(f"literal errors: {', '.join(analysis.literal_errors)}")- if analysis.union_tag_errors:- category_summaries.append(f"union tag errors: {', '.join(analysis.union_tag_errors)}")- if analysis.model_type_errors:- category_summaries.append(f"model type errors: {', '.join(analysis.model_type_errors)}")- if analysis.other_errors:- category_summaries.append(f"other errors: {', '.join(analysis.other_errors)}")-- error_word = "error" if error_count == 1 else "errors"- if category_summaries:- message = f"Validation failed for {model_name}: {error_count} {error_word} ({'; '.join(category_summaries)})"- else:- message = f"Validation failed for {model_name}: {error_count} {error_word}"-- details: dict[str, Any] = {- "model": model_name,- "error_count": error_count,- "categories": categories,- "errors": errors,- }-- return message, details--def convert_strenum_to_str(obj: dict[str, Any] | list[Any] | StrEnum | Any,) -> dict[str, Any] | list[Any] | str | Any:diff --git a/pipelex/validation_error_types.py b/pipelex/validation_error_types.pyindex 9c77df7a8..e48a79866 100644--- a/pipelex/validation_error_types.py+++ b/pipelex/validation_error_types.py@@ -46,8 +46,6 @@ class PipeValidationErrorType(StrEnum):INADEQUATE_OUTPUT_CONCEPT = "inadequate_output_concept"INADEQUATE_OUTPUT_MULTIPLICITY = "inadequate_output_multiplicity"- CIRCULAR_DEPENDENCY_ERROR = "circular_dependency_error"-LLM_OUTPUT_CANNOT_BE_IMAGE = "llm_output_cannot_be_image"INVALID_PIPE_CODE_SYNTAX = "invalid_pipe_code_syntax"UNKNOWN_PIPE_TYPE = "unknown_pipe_type"@@ -117,7 +115,6 @@ class PipeValidationErrorType(StrEnum):case (PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT| PipeValidationErrorType.INADEQUATE_OUTPUT_MULTIPLICITY- | PipeValidationErrorType.CIRCULAR_DEPENDENCY_ERROR| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE| PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX| PipeValidationErrorType.UNKNOWN_PIPE_TYPE@@ -149,7 +146,6 @@ class PipeValidationErrorType(StrEnum):PipeValidationErrorType.MISSING_INPUT_VARIABLE| PipeValidationErrorType.EXTRANEOUS_INPUT_VARIABLE| PipeValidationErrorType.INPUT_STUFF_SPEC_MISMATCH- | PipeValidationErrorType.CIRCULAR_DEPENDENCY_ERROR| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE| PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX| PipeValidationErrorType.UNKNOWN_PIPE_TYPE@@ -188,7 +184,6 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.EXTRANEOUS_INPUT_VARIABLE| PipeValidationErrorType.INPUT_STUFF_SPEC_MISMATCH| PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT- | PipeValidationErrorType.CIRCULAR_DEPENDENCY_ERROR| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE| PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX| PipeValidationErrorType.UNKNOWN_PIPE_TYPE@@ -222,7 +217,6 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.INPUT_STUFF_SPEC_MISMATCH| PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT| PipeValidationErrorType.INADEQUATE_OUTPUT_MULTIPLICITY- | PipeValidationErrorType.CIRCULAR_DEPENDENCY_ERROR| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE| PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX| PipeValidationErrorType.UNKNOWN_PIPE_TYPE@@ -260,7 +254,6 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.INPUT_STUFF_SPEC_MISMATCH| PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT| PipeValidationErrorType.INADEQUATE_OUTPUT_MULTIPLICITY- | PipeValidationErrorType.CIRCULAR_DEPENDENCY_ERROR| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE| PipeValidationErrorType.UNKNOWN_PIPE_TYPE| PipeValidationErrorType.MISSING_PIPE_TYPE@@ -293,7 +286,6 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.INPUT_STUFF_SPEC_MISMATCH| PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT| PipeValidationErrorType.INADEQUATE_OUTPUT_MULTIPLICITY- | PipeValidationErrorType.CIRCULAR_DEPENDENCY_ERROR| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE| PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX| PipeValidationErrorType.UNKNOWN_PIPE_TYPEdiff --git a/subject_grants.toml b/subject_grants.tomlindex 5dcf8911d..ace8873e2 100644--- a/subject_grants.toml+++ b/subject_grants.toml@@ -28,98 +28,6 @@ rationale = "Conversion: maps the error domain to a status; single operand."param = "exc"rationale = "Verb-object: iterates the exception's cause chain; single operand."-["pipelex/builder/concept/concept_spec.py::ConceptSpec._format_type_display"]-param = "field_spec"-rationale = "Verb-object: formats the field spec's type display; single operand."--["pipelex/builder/operations/concept_ops.py::concept_spec_to_toml"]-param = "concept_spec"-rationale = "Conversion: the concept spec being rendered to TOML; single operand."--["pipelex/builder/operations/concept_ops.py::parse_concept_spec"]-param = "spec_data"-rationale = "Verb-object: parses the raw spec data; single operand."--["pipelex/builder/operations/concept_ops.py::structure_field_to_dict"]-param = "field_spec"-rationale = "Conversion: the field spec being dictified; single operand."--["pipelex/builder/operations/models_ops.py::_filter_aliases_by_backend"]-param = "aliases"-rationale = "Verb-object: the alias mapping being filtered; backend context stays keyword."--["pipelex/builder/operations/models_ops.py::_filter_presets_by_backend"]-param = "presets_list"-rationale = "Verb-object: the preset list being filtered; backend context stays keyword."--["pipelex/builder/operations/models_ops.py::_filter_waterfalls_by_backend"]-param = "waterfalls"-rationale = "Verb-object: the waterfall mapping being filtered; backend context stays keyword."--["pipelex/builder/operations/models_ops.py::_should_include"]-param = "category"-rationale = "Predicate on the candidate category; the filter list stays keyword."--["pipelex/builder/operations/models_ops.py::format_models_markdown"]-param = "result"-rationale = "Verb-object: formats the list_models result dict; single operand."--["pipelex/builder/operations/pipe_ops.py::_normalize_output"]-param = "data"-rationale = "Single-operand normalization of the raw spec data."--["pipelex/builder/operations/pipe_ops.py::_normalize_pipe_code_aliases"]-param = "data"-rationale = "Verb-object: normalizes the dict in place; single operand."--["pipelex/builder/operations/pipe_ops.py::_normalize_prompt_aliases"]-param = "data"-rationale = "Verb-object: normalizes the dict in place; single operand."--["pipelex/builder/operations/pipe_ops.py::_normalize_sub_pipe_dict"]-param = "data"-rationale = "Verb-object: normalizes the step/branch dict in place; single operand."--["pipelex/builder/operations/pipe_ops.py::_normalize_sub_pipe_list"]-param = "raw_value"-rationale = "Verb-object: the raw steps/branches value being normalized; field_name stays keyword."--["pipelex/builder/operations/pipe_ops.py::parse_pipe_spec"]-param = "spec_data"-rationale = "Verb-object: parses the raw spec data; pipe_type stays keyword."--["pipelex/builder/operations/pipe_ops.py::pipe_spec_to_toml"]-param = "pipe_spec"-rationale = "Conversion: the pipe spec being rendered to TOML; single operand."--["pipelex/builder/operations/validate_ops.py::validate_bundle_content"]-param = "mthds_contents"-rationale = "Verb-object: validates the given .mthds contents; single operand."--["pipelex/builder/operations/validate_ops.py::validate_bundle_file"]-param = "bundle_path"-rationale = "Verb-object: validates the bundle at the given path; library_dirs stays keyword."--["pipelex/builder/operations/validate_ops.py::validate_pipe"]-param = "pipe_code"-rationale = "Verb-object: validates the pipe named by the code; single operand."--["pipelex/builder/pipe/pipe_spec.py::PipeSpec.validate_pipe_code_syntax"]-param = "pipe_code"-rationale = "Verb-object: validates/normalizes the pipe code; also invoked positionally by the field validator."--["pipelex/builder/runner_code.py::_collect_imports_for_inputs"]-param = "inputs"-rationale = "Verb-object: collects imports for the pipe inputs; single operand."--["pipelex/builder/runner_code.py::_format_representation_as_python"]-param = "representation"-rationale = "Verb-object: formats the representation dict as Python; is_multiple stays keyword."--["pipelex/builder/runner_code.py::generate_runner_code"]-param = "pipe"-rationale = "Verb-object: generates runner code for the pipe; single obvious operand."-["pipelex/cli/agent_cli/commands/agent_output.py::_agent_error_json"]param = "message"rationale = "Builds the error JSON around the message; single operand."@@ -196,10 +104,6 @@ rationale = "Positional-Callable protocol: passed as markdown_renderer, invokedparam = "result"rationale = "Positional-Callable protocol: passed as markdown_renderer, invoked renderer(result)."-["pipelex/cli/agent_cli/commands/concept_cmd.py::_concept_spec_to_toml"]-param = "concept_spec"-rationale = "Serializes the concept_spec to TOML; single operand."-["pipelex/cli/agent_cli/commands/doctor_cmd.py::_format_doctor_markdown"]param = "result"rationale = "Renders the result; single operand."@@ -244,10 +148,6 @@ rationale = "Verb-object: emits the result; format options stay keyword."param = "result"rationale = "Positional-Callable protocol: passed as markdown_renderer, invoked renderer(result)."-["pipelex/cli/agent_cli/commands/pipe_cmd.py::_pipe_spec_to_toml"]-param = "pipe_spec"-rationale = "Serializes the pipe_spec to TOML; single operand."-["pipelex/cli/agent_cli/commands/plxt_passthrough.py::run_plxt"]param = "subcommand"rationale = "Runs the given plxt subcommand; single operand."@@ -936,10 +836,6 @@ rationale = "Predicate on the type name; used_symbols is context."param = "library"rationale = "Single-operand transformation: derives the name mapping over the whole library."-["pipelex/codegen/emitters/naming.py::runtime_to_emitted_class_names"]-param = "library"-rationale = "Single-operand transformation: derives the class-name mapping over the whole library."-["pipelex/codegen/emitters/naming.py::snake_to_pascal"]param = "name"rationale = "Single-operand conversion of the name."@@ -1376,10 +1272,6 @@ rationale = "Positional-Callable reporter protocol (_ReportLLMJobFunc.__call__):param = "job_metadata"rationale = "Positional-Callable reporter protocol (_ReportLLMJobFunc.__call__): job_metadata stays positional to match report_func(job_metadata, ...)."-["pipelex/cogt/content_generation/dry_mock.py::stamp_mock_main_coordination"]-param = "items"-rationale = "Consumes the items; single operand."-["pipelex/cogt/content_generation/dry_run_factory.py::DryRunFactory._create_nested_factory"]param = "nested_class"rationale = "Builds a nested mock factory for the class; single operand."@@ -2352,6 +2244,26 @@ rationale = "Verb–object: validates/checks the search_choice; single operand."param = "model_deck_paths"rationale = "Deck/file op on the model_deck_paths; single operand."+["pipelex/cogt/models/model_listing.py::_filter_aliases_by_backend"]+param = "aliases"+rationale = "Verb-object: the alias mapping being filtered; backend context stays keyword."++["pipelex/cogt/models/model_listing.py::_filter_presets_by_backend"]+param = "presets_list"+rationale = "Verb-object: the preset list being filtered; backend context stays keyword."++["pipelex/cogt/models/model_listing.py::_filter_waterfalls_by_backend"]+param = "waterfalls"+rationale = "Verb-object: the waterfall mapping being filtered; backend context stays keyword."++["pipelex/cogt/models/model_listing.py::_should_include"]+param = "category"+rationale = "Predicate on the candidate category; the filter list stays keyword."++["pipelex/cogt/models/model_listing.py::format_models_markdown"]+param = "result"+rationale = "Verb-object: formats the list_models result dict; single operand."+["pipelex/cogt/models/model_manager.py::ModelManager._collect_candidates"]param = "ref"rationale = "Operates on the ref; single operand (qualifiers keyword-only)."@@ -3016,10 +2928,6 @@ rationale = "Single-operand conversion of the composite content."param = "content"rationale = "Single-operand conversion of the content."-["pipelex/core/memory/working_memory_factory.py::WorkingMemoryFactory._get_mockable_class"]-param = "structure_class"-rationale = "Derivation from the structure class; single operand."-["pipelex/core/memory/working_memory_factory.py::WorkingMemoryFactory.convert_stuff_spec_to_typed_named"]param = "stuff_spec"rationale = "Conversion: transforms the stuff spec; context stays keyword."@@ -4100,14 +4008,6 @@ rationale = "Predicate on the file path; single operand."param = "bundle_path"rationale = "Factory from source: parses the bundle at the path; options stay keyword."-["pipelex/mthds_parsing/pipe_sorter.py::sort_pipes_by_dependencies"]-param = "pipes"-rationale = "Verb-object: sorts the pipes; single operand."--["pipelex/mthds_parsing/pipe_sorter.py::sort_pipes_by_dependencies.visit"]-param = "pipe_code"-rationale = "Nested DFS visitor on the pipe code; single operand."-["pipelex/mthds_parsing/pipelex_bundle_blueprint.py::PipelexBundleBlueprint._collect_local_refs_from_concept"]param = "concept_code"rationale = "Verb-object: collects refs from the concept named; context stays keyword."@@ -7248,14 +7148,6 @@ rationale = "Inspects the file_path; single operand."param = "file_path"rationale = "Inspects the file_path; single operand."-["pipelex/tools/typing/pydantic_utils.py::_serialize_context"]-param = "ctx"-rationale = "Transforms the ctx; single operand."--["pipelex/tools/typing/pydantic_utils.py::_serialize_input_value"]-param = "value"-rationale = "Transforms the value; single operand."-["pipelex/tools/typing/pydantic_utils.py::_truncated_rich_repr_from_items"]param = "rich_repr_items"rationale = "Transforms the rich_repr_items; single operand."@@ -7284,10 +7176,6 @@ rationale = "Factory from source: builds the result from the _; single operand."param = "exc"rationale = "Validates/checks the exc; single operand."-["pipelex/tools/typing/pydantic_utils.py::format_pydantic_validation_error_for_agent"]-param = "exc"-rationale = "Validates/checks the exc; single operand."-["pipelex/tools/typing/pydantic_utils.py::make_truncated_wrapper"]param = "model"rationale = "Factory from source: builds the result from the model; single operand."diff --git a/tests/CLAUDE.md b/tests/CLAUDE.mdindex b00412264..fa7321da4 100644--- a/tests/CLAUDE.md+++ b/tests/CLAUDE.md@@ -17,7 +17,6 @@ Replace `<paths>` with the test directories from the mapping below. Concatenate| Changed source | Test paths to run ||---|---|-| `pipelex/builder/` | `tests/unit/pipelex/builder/ tests/integration/pipelex/builder/` || `pipelex/cli/` | `tests/unit/pipelex/cli/ tests/integration/pipelex/cli/ tests/e2e/pipelex/cli/` || `pipelex/codegen/` | `tests/unit/pipelex/codegen/ tests/integration/pipelex/codegen/` || `pipelex/cogt/` | `tests/unit/pipelex/cogt/ tests/integration/pipelex/cogt/` |@@ -46,7 +45,7 @@ Note: `pipe_controllers/`, `pipe_operators/`, and `pipe_run/` share integrationAdd these to any targeted run when applicable:- **Config TOML changes** (`pipelex/pipelex.toml`, `pipelex/kit/configs/`): also run `make tb` (boot test)-- **`.mthds` file changes**: also add `tests/unit/pipelex/builder/ tests/integration/pipelex/builder/ tests/integration/pipelex/pipes/`+- **`.mthds` file changes**: also add `tests/integration/pipelex/pipes/`- **Test fixtures changed** (`tests/data/`, `tests/cases/`): also run tests that import from those fixtures## When to run full `make agent-test`diff --git a/tests/data/errors/error_identity.txt b/tests/data/errors/error_identity.txtindex 006482da5..86c3af55c 100644--- a/tests/data/errors/error_identity.txt+++ b/tests/data/errors/error_identity.txt@@ -34,7 +34,6 @@ ConceptLibraryError | Concept library | https://docs.pipelex.com/latest/errors/cConceptLoadingError | Concept loading | https://docs.pipelex.com/latest/errors/concept-loading-error/ConceptRefAmbiguousError | Concept ref ambiguous | https://docs.pipelex.com/latest/errors/concept-ref-ambiguous-error/ConceptRefineError | Concept refine | https://docs.pipelex.com/latest/errors/concept-refine-error/-ConceptSpecError | Concept spec | https://docs.pipelex.com/latest/errors/concept-spec-error/ConceptStringError | Concept string | https://docs.pipelex.com/latest/errors/concept-string-error/ConceptStructureGeneratorError | Concept structure generator | https://docs.pipelex.com/latest/errors/concept-structure-generator-error/ConceptStructureValidationError | Concept structure validation | https://docs.pipelex.com/latest/errors/concept-structure-validation-error/@@ -265,10 +264,8 @@ PipeSearchError | Pipe search | https://docs.pipelex.com/latest/errors/pipe-searPipeSearchFactoryError | Pipe search factory | https://docs.pipelex.com/latest/errors/pipe-search-factory-error/PipeSequenceFactoryError | Pipe sequence factory | https://docs.pipelex.com/latest/errors/pipe-sequence-factory-error/PipeSignatureNotExecutableError | Pipe signature not executable | https://docs.pipelex.com/latest/errors/pipe-signature-not-executable-error/-PipeSpecError | Pipe spec | https://docs.pipelex.com/latest/errors/pipe-spec-error/PipeStackOverflowError | Pipe stack overflow | https://docs.pipelex.com/latest/errors/pipe-stack-overflow-error/PipelexBridgeDispatchError | Pipelex bridge dispatch | https://docs.pipelex.com/latest/errors/pipelex-bridge-dispatch-error/-PipelexBundleSpecBlueprintError | Pipelex bundle spec blueprint | https://docs.pipelex.com/latest/errors/pipelex-bundle-spec-blueprint-error/PipelexCLIError | Pipelex CLI | https://docs.pipelex.com/latest/errors/pipelex-cli-error/PipelexConfigError | Pipelex config | https://docs.pipelex.com/latest/errors/pipelex-config-error/PipelexError | Pipelex error | https://docs.pipelex.com/latest/errors/pipelex-error/diff --git a/tests/integration/pipelex/builder/concept/integration_test_data.py b/tests/integration/pipelex/builder/concept/integration_test_data.pydeleted file mode 100644index dc9b7c9b5..000000000--- a/tests/integration/pipelex/builder/concept/integration_test_data.py+++ /dev/null@@ -1,123 +0,0 @@-from typing import ClassVar---class ConceptSpecGenerationTestCases:- """Test cases for LLM-based ConceptSpec generation."""-- # Test case: Simple concept without structure or refines- SIMPLE_CONCEPT_PROMPT = """-Generate a concept specification for a "BlogPost" concept.--Requirements:-- concept_code: BlogPost-- description: A blog post with title, content, and publication date-- structure: None (leave empty)-- refines: None (leave empty)-"""-- # Test case: Concept that refines a native concept- REFINES_TEXT_PROMPT = """-Generate a concept specification for a "ProductDescription" concept.--Requirements:-- concept_code: ProductDescription-- description: A detailed description of a product for e-commerce-- refines: Text (this concept refines the native Text concept)-- structure: None (leave empty because we're using refines)-"""-- # Test case: Concept with simple structure- SIMPLE_STRUCTURE_PROMPT = """-Generate a concept specification for a "Person" concept with a simple structure.--Requirements:-- concept_code: Person-- description: A person with basic information-- structure: A dictionary with these fields:- - name: (type: text, description: "The person's full name", required: true)- - age: (type: integer, description: "The person's age", required: true)-- refines: None (leave empty)-"""-- # Test case: Concept with complex structure- COMPLEX_STRUCTURE_PROMPT = """-Generate a concept specification for a "Product" concept with a detailed structure.--Requirements:-- concept_code: Product-- description: A product in an e-commerce system-- structure: A dictionary with these fields:- - name: (type: text, description: "Product name", required: true)- - description: (type: text, description: "Product description", required: true)- - price: (type: number, description: "Product price in dollars", required: true)- - stock_quantity: (type: integer, description: "Number of items in stock", required: false, default_value: 0)- - is_available: (type: boolean, description: "Whether the product is currently available", required: false, default_value: true)-- refines: None (leave empty)-"""-- # Test case: Concept with optional fields and defaults- OPTIONAL_FIELDS_PROMPT = """-Generate a concept specification for a "UserProfile" concept.--Requirements:-- concept_code: UserProfile-- description: A user profile with optional settings-- structure: A dictionary with these fields:- - username: (type: text, description: "User's username", required: true)- - email: (type: text, description: "User's email address", required: true)- - bio: (type: text, description: "User biography", required: false, default_value: "")- - notification_enabled: (type: boolean, description: "Whether notifications are enabled", required: false, default_value: true)- - login_count: (type: integer, description: "Number of times user has logged in", required: false, default_value: 0)-- refines: None (leave empty)-"""-- # Test case: Concept with snake_case code (tests conversion)- SNAKE_CASE_CONCEPT_PROMPT = """-Generate a concept specification for a "customer_order" concept.--Requirements:-- concept_code: customer_order-- description: An order placed by a customer-- structure: A dictionary with these fields:- - order_number: (type: text, description: "Unique order identifier", required: true)- - total_amount: (type: number, description: "Total order amount", required: true)- - is_paid: (type: boolean, description: "Payment status", required: false, default_value: false)-- refines: None (leave empty)-"""-- # Test case: Concept refining Image- REFINES_IMAGE_PROMPT = """-Generate a concept specification for a "ProductPhoto" concept.--Requirements:-- concept_code: ProductPhoto-- description: A photograph of a product for display in catalog-- refines: Image (this concept refines the native Image concept)-- structure: None (leave empty because we're using refines)-"""-- # Test case: Concept with date field- DATE_FIELD_PROMPT = """-Generate a concept specification for an "Event" concept with a date field.--Requirements:-- concept_code: Event-- description: An event with scheduling information-- structure: A dictionary with these fields:- - title: (type: text, description: "Event title", required: true)- - description: (type: text, description: "Event description", required: true)- - start_date: (type: date, description: "Event start date and time", required: true)- - is_public: (type: boolean, description: "Whether the event is public", required: false, default_value: true)-- refines: None (leave empty)-"""-- TEST_CASES: ClassVar[list[tuple[str, str]]] = [- # ("simple_concept", SIMPLE_CONCEPT_PROMPT),- # ("refines_text", REFINES_TEXT_PROMPT),- # ("simple_structure", SIMPLE_STRUCTURE_PROMPT),- # ("complex_structure", COMPLEX_STRUCTURE_PROMPT),- # ("optional_fields", OPTIONAL_FIELDS_PROMPT),- ("snake_case_concept", SNAKE_CASE_CONCEPT_PROMPT),- # ("refines_image", REFINES_IMAGE_PROMPT),- # ("date_field", DATE_FIELD_PROMPT),- ]diff --git a/tests/integration/pipelex/builder/concept/test_concept_spec_generation.py b/tests/integration/pipelex/builder/concept/test_concept_spec_generation.pydeleted file mode 100644index f1b0f4584..000000000--- a/tests/integration/pipelex/builder/concept/test_concept_spec_generation.py+++ /dev/null@@ -1,70 +0,0 @@-import pytest--from pipelex import log, pretty_print-from pipelex.builder.concept.concept_spec import ConceptSpec-from pipelex.cogt.llm.llm_job_components import LLMJobConfig, LLMJobParams-from pipelex.cogt.llm.llm_job_factory import LLMJobFactory-from pipelex.cogt.llm.llm_prompt import LLMPrompt-from pipelex.runtime_hub import get_llm_worker-from pipelex.system.job_metadata import JobMetadata-from tests.integration.pipelex.builder.concept.integration_test_data import ConceptSpecGenerationTestCases-from tests.integration.pipelex.fixtures.model_combo import ModelCombo--[email protected](loop_scope="class")-class TestConceptSpecGeneration:- """Integration tests for generating ConceptSpec objects using LLM.-- These tests verify that LLMs can generate valid ConceptSpec objects- from natural language prompts describing various concept shapes.- """-- @pytest.mark.parametrize(("topic", "user_prompt"), ConceptSpecGenerationTestCases.TEST_CASES)- async def test_generate_concept_spec(- self,- job_metadata: JobMetadata,- llm_job_params: LLMJobParams,- llm_combo: ModelCombo,- topic: str,- user_prompt: str,- ):- log.info(f"Testing {topic} with llm_handle '{llm_combo.handle}'")-- # Get the LLM worker- llm_worker = get_llm_worker(llm_handle=llm_combo.handle)-- # Skip if object generation is not supported- if not llm_worker.is_gen_object_supported:- pytest.skip(f"LLM worker '{llm_worker.desc}' does not support object generation")-- log.info(f"Using llm_worker: {llm_worker.desc}")-- # Create the LLM job with the prompt- llm_job = LLMJobFactory.make_llm_job(- llm_prompt=LLMPrompt(- system_text="You are an expert at generating concept specifications for a data modeling system.",- user_text=user_prompt,- ),- job_metadata=job_metadata,- llm_job_config=LLMJobConfig(- schema_reask_max_attempts=3,- ),- llm_job_params=llm_job_params,- )-- # Generate the ConceptSpec object- generated_concept_spec = await llm_worker.gen_object(llm_job=llm_job, schema=ConceptSpec)-- # Display the result- pretty_print(generated_concept_spec, title=f"Generated ConceptSpec for '{topic}' using {llm_combo.handle}")-- # Basic validation: if we got here without exceptions, the ConceptSpec was created successfully- # The Pydantic validation and field validators have already run- assert generated_concept_spec is not None- assert isinstance(generated_concept_spec, ConceptSpec)- assert generated_concept_spec.concept_code- assert generated_concept_spec.description-- log.info(f"✓ Successfully generated ConceptSpec for '{topic}': {generated_concept_spec.concept_code}")diff --git a/tests/integration/pipelex/builder/operations/test_runner_code_ops_library_lifecycle.py b/tests/integration/pipelex/builder/operations/test_runner_code_ops_library_lifecycle.pydeleted file mode 100644index da5cdb309..000000000--- a/tests/integration/pipelex/builder/operations/test_runner_code_ops_library_lifecycle.py+++ /dev/null@@ -1,58 +0,0 @@-"""Failure-path library-lifecycle guarantee for ``runner_code_ops.build_runner_code_for_pipe``.--On SUCCESS the function intentionally leaves the library open + current — the D6 loaded-on-success-contract, pinned by ``test_validate_bundle_loaded_on_success`` (the caller resolves + generates code-against the still-open library, then tears it down). On FAILURE this caller owns cleanup: a raise-after the temporary library is opened + current (e.g. an unknown ``pipe_code`` →-``PipeNotFoundError`` from ``get_required_pipe``, after the bundle itself validates) must restore the-caller's outer current-library and tear the temporary library down, or a long-lived builder/API-process leaks one library per failed request.--Fully dry (no inference).-"""--import pytest-from pytest_mock import MockerFixture--from pipelex.builder.operations.runner_code_ops import build_runner_code_for_pipe-from pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, set_current_library-from pipelex.libraries.pipe.exceptions import PipeNotFoundError--_RC_DOMAIN = "runner_code_lifecycle"-_RC_MTHDS = f"""-domain = "{_RC_DOMAIN}"-description = "Bundle for runner_code_ops failure-path lifecycle test"--[concept.Doc]-description = "A document"--[pipe.summarize_doc]-type = "PipeLLM"-description = "Summarize a document"-inputs = {{ doc = "Doc" }}-output = "Text"-prompt = "Summarize $doc"-"""--[email protected](loop_scope="class")-class TestRunnerCodeOpsLibraryLifecycle:- async def test_failure_restores_outer_and_tears_down_temp(self, mocker: MockerFixture) -> None:- # The bundle validates fine, but the requested pipe_code is absent -> get_required_pipe raises- # PipeNotFoundError AFTER the temporary library was opened + made current. That failure must not- # leak the library nor leave it current.- library_manager = get_library_manager()- outer_library_id, _ = library_manager.open_library()- set_current_library(library_id=outer_library_id)- open_spy = mocker.spy(library_manager, "open_library")- teardown_spy = mocker.spy(library_manager, "teardown")- try:- with pytest.raises(PipeNotFoundError):- await build_runner_code_for_pipe(mthds_contents=[_RC_MTHDS], pipe_code="does_not_exist")- temp_library_id, _ = open_spy.spy_return- assert temp_library_id != outer_library_id- teardown_spy.assert_any_call(library_id=temp_library_id)- assert get_current_library_id_or_none() == outer_library_id- finally:- clear_current_library()- library_manager.teardown(library_id=outer_library_id)diff --git a/tests/integration/pipelex/builder/operations/test_validate_pipe_library_lifecycle.py b/tests/integration/pipelex/builder/operations/test_validate_pipe_library_lifecycle.pydeleted file mode 100644index 4f53f60f5..000000000--- a/tests/integration/pipelex/builder/operations/test_validate_pipe_library_lifecycle.py+++ /dev/null@@ -1,84 +0,0 @@-"""Library-lifecycle guarantee for ``validate_ops.validate_pipe``.--``validate_pipe`` opens a fresh temporary library, makes it current, and drives-``BundleValidator.validate_pipes`` — the D6 inner sweep that NEVER tears the library down. So-``validate_pipe`` owns the full lifecycle: on BOTH the success and failure paths it must tear the-temporary library down and restore the caller's outer current-library. Otherwise a long-lived-builder/API process accumulates libraries and leaves the current-library ContextVar pointing at a-stale validation library (later operations resolve pipes against the wrong scope).--Fully dry (no inference).-"""--import tempfile-from pathlib import Path--import pytest-from pytest_mock import MockerFixture--from pipelex.builder.operations.validate_ops import validate_pipe-from pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, set_current_library-from pipelex.libraries.pipe.exceptions import PipeNotFoundError--_LIFECYCLE_DOMAIN = "validate_pipe_lifecycle"-_LIFECYCLE_MTHDS = f"""-domain = "{_LIFECYCLE_DOMAIN}"-description = "Bundle for validate_pipe library-lifecycle tests"--[concept.Doc]-description = "A document"--[pipe.summarize_doc]-type = "PipeLLM"-description = "Summarize a document"-inputs = {{ doc = "Doc" }}-output = "Text"-prompt = "Summarize $doc"-"""--[email protected](loop_scope="class")-class TestValidatePipeLibraryLifecycle:- async def test_failure_restores_outer_and_tears_down_temp(self, mocker: MockerFixture) -> None:- # An unknown pipe_code raises PipeNotFoundError after the temporary library was opened + made- # current. That failure must tear the temporary library down and restore the outer binding.- library_manager = get_library_manager()- outer_library_id, _ = library_manager.open_library()- set_current_library(library_id=outer_library_id)- open_spy = mocker.spy(library_manager, "open_library")- teardown_spy = mocker.spy(library_manager, "teardown")- try:- with pytest.raises(PipeNotFoundError):- await validate_pipe(pipe_code="does_not_exist")- temp_library_id, _ = open_spy.spy_return- assert temp_library_id != outer_library_id- teardown_spy.assert_any_call(library_id=temp_library_id)- assert get_current_library_id_or_none() == outer_library_id- finally:- clear_current_library()- library_manager.teardown(library_id=outer_library_id)-- async def test_success_restores_outer_and_tears_down_temp(self, mocker: MockerFixture) -> None:- # validate_pipe returns a results dict and does not need the library afterward, so a SUCCESSFUL- # validation must also tear the temporary library down and restore the outer binding (unlike the- # loaded-on-success runner_code_ops caller).- library_manager = get_library_manager()- outer_library_id, _ = library_manager.open_library()- set_current_library(library_id=outer_library_id)- try:- with tempfile.TemporaryDirectory() as tmp_dir:- (Path(tmp_dir) / "bundle.mthds").write_text(_LIFECYCLE_MTHDS, encoding="utf-8")- open_spy = mocker.spy(library_manager, "open_library")- teardown_spy = mocker.spy(library_manager, "teardown")- result = await validate_pipe(- pipe_code=f"{_LIFECYCLE_DOMAIN}.summarize_doc",- library_dirs=[Path(tmp_dir)],- )- assert result["success"] is True- temp_library_id, _ = open_spy.spy_return- assert temp_library_id != outer_library_id- teardown_spy.assert_any_call(library_id=temp_library_id)- assert get_current_library_id_or_none() == outer_library_id- finally:- clear_current_library()- library_manager.teardown(library_id=outer_library_id)diff --git a/tests/integration/pipelex/cli/commands/test_build_runner_flow.py b/tests/integration/pipelex/cli/commands/test_build_runner_flow.pydeleted file mode 100644index 910aff555..000000000--- a/tests/integration/pipelex/cli/commands/test_build_runner_flow.py+++ /dev/null@@ -1,83 +0,0 @@-"""Integration: `pipelex build runner` core flow over a real bundle (validate -> emit -> script).--Pins the D9 re-point: the runner scaffold's structures/ output comes from the codegen engine (one-stamped structures.py + codegen.lock), and the generated script spells custom classes the way the-emitted module defines them (bare-when-unique), importing them from `structures.structures`.-"""--import ast-import tempfile-from pathlib import Path--import pytest--from pipelex.cli.commands.build.runner._runner_core import (- _prepare_runner_core, # pyright: ignore[reportPrivateUsage]-)-from pipelex.codegen.lock import CODEGEN_LOCK_FILENAME-from pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager--_BUNDLE_MTHDS = """\-domain = "runnerflow"-description = "Runner-flow test domain"-main_pipe = "answer_query"--[concept.Query]-description = "A user query"-structure.question = { description = "the question", type = "text", required = true }--[concept.Report]-description = "A report"-structure.summary = { description = "the summary", type = "text", required = true }--[pipe.answer_query]-type = "PipeLLM"-description = "Answer a query with a report"-inputs = { query = "Query" }-output = "Report"-model = "$quick-reasoning"-prompt = "Answer $query"-"""--[email protected](loop_scope="class")-class TestBuildRunnerFlow:- async def test_runner_and_structures_projection_agree_on_names(self):- """The emitted structures.py defines bare-when-unique classes and the runner script imports- and instantiates exactly those spellings (no runtime-qualified names leak into the script).- """- with tempfile.TemporaryDirectory() as tmp_dir:- bundle_dir = Path(tmp_dir)- bundle_path = bundle_dir / "bundle.mthds"- bundle_path.write_text(_BUNDLE_MTHDS, encoding="utf-8")-- try:- await _prepare_runner_core(pipe_code=None, bundle_path=bundle_path, library_dirs=[bundle_dir])- finally:- # validate_bundle leaves its library open and current (loaded-on-success); the CLI- # wrapper tears the whole Pipelex down, so the test cleans up the library itself.- library_id = get_current_library_id_or_none()- if library_id is not None:- clear_current_library()- get_library_manager().teardown(library_id=library_id)-- structures_file = bundle_dir / "structures" / "structures.py"- assert structures_file.is_file()- assert (bundle_dir / "structures" / CODEGEN_LOCK_FILENAME).is_file()- structures_code = structures_file.read_text(encoding="utf-8")- assert "class Query(StructuredContent):" in structures_code- assert "class Report(StructuredContent):" in structures_code-- runner_file = bundle_dir / "run_answer_query.py"- assert runner_file.is_file()- runner_code = runner_file.read_text(encoding="utf-8")- ast.parse(runner_code)-- # Imports come from the single emitted module, spelled bare-when-unique.- assert "from structures.structures import Query" in runner_code- assert "from structures.structures import Report" in runner_code- # The example input instantiates the emitted class; the output cast uses it too.- assert "Query(question=" in runner_code- assert "pipe_output.main_stuff_as(content_type=Report)" in runner_code- # No runtime-qualified spelling leaks into the script.- assert "runnerflow__" not in runner_codediff --git a/tests/integration/pipelex/cli/test_advisory_warning_channels.py b/tests/integration/pipelex/cli/test_advisory_warning_channels.pyindex b7064d83f..65ac04dc8 100644--- a/tests/integration/pipelex/cli/test_advisory_warning_channels.py+++ b/tests/integration/pipelex/cli/test_advisory_warning_channels.py@@ -1,20 +1,18 @@"""Every whole-bundle validate channel carries the same advisory-warning families.The `warnings` array used to be assembled site by site, and the sites disagreed: the protocol path-emitted the optionality and hint lints, the agent CLI, the builder ops and the bare CLI emitted the-optionality lint alone. One composition point (`pipelex.pipeline.advisory_warnings`) now builds them-all, and these pin that the channels agree — the agent-CLI JSON envelope, its markdown rendering,-the builder-ops envelopes, and the bare CLI's yellow echo.+emitted the optionality and hint lints, the agent CLI and the bare CLI emitted the optionality lint+alone. One composition point (`pipelex.pipeline.advisory_warnings`) now builds them all, and these pin+that the channels agree — the agent-CLI JSON envelope, its markdown rendering, and the bare CLI's+yellow echo.`validate all` is the channel that reaches for the *library manager's* accumulated blueprints toknow which pipes are entry pipes (it holds no `ValidateBundleResult` of its own), so its case heredoubles as the proof that the `acquire_library` load path really does accumulate them.-Two surfaces are deliberately absent. The builder's `validate_all` carries no `warnings` key at all-and never did (L-260930-3f3167). And the bare CLI's single-pipe `validate-<PIPE_CODE>` echoes none of them: it makes no bundle-wide claim, and neither lint has anything to say-about one pipe in isolation (the vacuous lint is scoped to entry pipes, the optionality lint-aggregates across flows).+One surface is deliberately absent: the bare CLI's single-pipe `validate <PIPE_CODE>` echoes none of+them. It makes no bundle-wide claim, and neither lint has anything to say about one pipe in isolation+(the vacuous lint is scoped to entry pipes, the optionality lint aggregates across flows)."""from __future__ import annotations@@ -27,7 +25,6 @@ from typing import TYPE_CHECKING, Anyimport pytestimport typer-from pipelex.builder.operations import validate_opsfrom pipelex.cli.agent_cli.commands.validate._validate_core import validate_all_core, validate_bundle_corefrom pipelex.cli.commands.validate._validate_core import (_validate_pipe_or_bundle, # pyright: ignore[reportPrivateUsage]@@ -202,12 +199,6 @@ class TestAdvisoryWarningChannels:# reserved for a reference that did not resolve, spelled as the author wrote it.assert "concept_code" not in vacuous[0]- def test_builder_validate_bundle_content_twin(self) -> None:- result = asyncio.run(validate_ops.validate_bundle_content(mthds_contents=[_VACUOUS_MTHDS]))-- assert result["is_valid"] is True- assert PipeValidationErrorType.INPUT_PRESENCE_VACUOUS in _error_types(result["warnings"])-def test_agent_cli_markdown_renders_the_warning_under_its_heading(self, vacuous_bundle_dir: Path) -> None:"""The markdown stream is the one an agent actually reads on `--format markdown` (the default)."""result = asyncio.run(validate_bundle_core(bundle_path=vacuous_bundle_dir / "bundle.mthds", library_dirs=[vacuous_bundle_dir]))@@ -228,17 +219,6 @@ class TestAdvisoryWarningChannels:HintLintErrorType.HINT_UNKNOWN_KEY,]- def test_builder_bundle_file_envelope_carries_all_three_families(self, all_families_bundle_dir: Path) -> None:- result = asyncio.run(- validate_ops.validate_bundle_file(bundle_path=all_families_bundle_dir / "bundle.mthds", library_dirs=[all_families_bundle_dir])- )-- assert _error_types(result["warnings"]) == [- PipeValidationErrorType.OPTIONAL_FORCE_REDUNDANT,- PipeValidationErrorType.INPUT_PRESENCE_VACUOUS,- HintLintErrorType.HINT_UNKNOWN_KEY,- ]-def test_agent_cli_markdown_lists_all_three_families_in_the_same_order(self, all_families_bundle_dir: Path) -> None:result = asyncio.run(validate_bundle_core(bundle_path=all_families_bundle_dir / "bundle.mthds", library_dirs=[all_families_bundle_dir]))diff --git a/tests/integration/pipelex/cli/test_agent_validate_pipe_core_library_lifecycle.py b/tests/integration/pipelex/cli/test_agent_validate_pipe_core_library_lifecycle.pyindex b5b4010ce..880ea9a7a 100644--- a/tests/integration/pipelex/cli/test_agent_validate_pipe_core_library_lifecycle.py+++ b/tests/integration/pipelex/cli/test_agent_validate_pipe_core_library_lifecycle.py@@ -6,8 +6,7 @@temporary library down and restore the caller's outer current-library. Otherwise a long-lived hostthat imports it (e.g. the build-assistant sandbox) accumulates libraries and leaves thecurrent-library ContextVar pointing at a stale validation library (later operations resolve pipes-against the wrong scope). This mirrors the builder twin's guarantee-(``test_validate_pipe_library_lifecycle.py``), which the agent-CLI core previously lacked.+against the wrong scope).Fully dry (no inference)."""diff --git a/tests/integration/pipelex/cogt/content_generation/test_leaf_dry_object_mocks.py b/tests/integration/pipelex/cogt/content_generation/test_leaf_dry_object_mocks.pyindex 1f219bd61..89f452540 100644--- a/tests/integration/pipelex/cogt/content_generation/test_leaf_dry_object_mocks.py+++ b/tests/integration/pipelex/cogt/content_generation/test_leaf_dry_object_mocks.py@@ -80,13 +80,6 @@ class NormalizedAnswer(StructuredContent):return f"INV-{value}"-class SpecWithPipeCode(StructuredContent):- """Pipe-spec-shaped item: carries the ``pipe_code`` field the mock_main coordination targets."""-- pipe_code: str- description: str--def _dry_object_assignment(object_class: type[StructuredContent], nb_items: int | None = None) -> ObjectAssignment:llm_assignment = LLMAssignment(job_metadata=JobMetadata(@@ -118,34 +111,6 @@ class TestLeafDryObjectMocks:assert len(mocks) == nb_items- async def test_dry_object_list_stamps_mock_main_coordination(self) -> None:- """The dry leaf stamps the first pipe-spec-shaped item with pipe_code='mock_main' (D3).-- This is what keeps builder-bundle dry-validation working through the leaf mock: the mocked- ``BundleHeaderSpec.main_pipe`` (``examples=["mock_main"]``) must name an existing pipe.- """- mocks = dry_llm_gen_object_list(_dry_object_assignment(SpecWithPipeCode, nb_items=3))-- first_item_pipe_code = getattr(mocks[0], "pipe_code", None)- assert first_item_pipe_code == "mock_main"-- async def test_dry_object_list_stamps_regardless_of_mock_usage(self) -> None:- """The stamp is unconditional on the is_mock_usage sub-flag — it only changes reporting (D3)."""- llm_assignment = LLMAssignment(- job_metadata=JobMetadata(- run_metadata=RunMetadata(storage_scope="test/scope", read_scope=None, user_id="u", pipeline_run_id="run_mock_usage_stamp")- ),- cogt_run_params=CogtRunParams(run_mode=PipeRunMode.DRY, is_mock_usage=True),- llm_setting=LLMSetting(model="gpt-4o", temperature=0.5),- llm_prompt=LLMPrompt(user_text="make specs"),- )- object_assignment = ObjectAssignment.make_for_class(object_class=SpecWithPipeCode, llm_assignment=llm_assignment, nb_items=3)-- mocks = dry_llm_gen_object_list(object_assignment)-- first_item_pipe_code = getattr(mocks[0], "pipe_code", None)- assert first_item_pipe_code == "mock_main"-async def test_dry_object_list_defaults_to_config_length(self) -> None:"""Without nb_items the dry list falls back to inference.dry_run.nb_list_items."""mocks = dry_llm_gen_object_list(_dry_object_assignment(RepresentativeInvoiceLine))diff --git a/tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py b/tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.pysimilarity index 64%rename from tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.pyrename to tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.pyindex 7a0100854..5c7d99e3f 100644--- a/tests/integration/pipelex/builder/operations/test_factory_refusal_verdicts.py+++ b/tests/integration/pipelex/pipeline/test_factory_refusal_verdicts.py@@ -1,26 +1,20 @@-"""Pin: a pipe factory's refusal, and a refusal raised while the builder's validate ops load libraries, is a verdict.+"""Pin: a pipe factory's refusal is a verdict.A pipe factory refuses a blueprint it cannot build, such as a ``PipeExtract`` whose input is neither animage nor a document. Its error classes declared no domain, so the validation translation did notrecognise them and they escaped every validator raw. They are now the author's input, caller-facing, so-the refusal validates to one item located on the pipe and its file, carrying the next step. The builder's-``validate_ops.validate_pipe`` and ``validate_all`` loaded libraries outside the translation, so a refusal-there escaped raw too; they now answer it with the same verdict. The agent CLI's ``validate_all_core``-translated its load only after the failed library was torn down, so its items lost their file; they keep it now.+the refusal validates to one item located on the pipe and its file, carrying the next step. The agent+CLI's ``validate_all_core`` translated its load only after the failed library was torn down, so its items+lost their file; they keep it now."""from pathlib import Pathimport pytest-from pytest_mock import MockerFixturefrom pipelex.base_exceptions import DisclosureMode, ErrorDomain, PipelexError, ValidationErrorCategory, ValidationErrorItem-from pipelex.builder.operations.validate_ops import validate_all, validate_pipefrom pipelex.cli.agent_cli.commands.validate._validate_core import validate_all_corefrom pipelex.core.pipes.exceptions import PipeLoadRefusalError-from pipelex.interpreter_hub import get_library_manager-from pipelex.libraries.exceptions import LibraryError-from pipelex.libraries.pipe.exceptions import EntryPipeAmbiguousErrorfrom pipelex.pipe_controllers.condition.exceptions import PipeConditionFactoryErrorfrom pipelex.pipe_controllers.parallel.exceptions import PipeParallelFactoryErrorfrom pipelex.pipe_operators.compose.exceptions import PipeComposeFactoryError@@ -76,21 +70,6 @@ prompt = "Write a note about this tide almanac: $almanac_text""""-def _write_named_pipe_bundle(*, directory: Path, domain_code: str) -> None:- content = f"""-domain = "{domain_code}"-description = "Write notes for the harbour board"--[pipe.write_note]-type = "PipeLLM"-description = "Write a note for the harbour board"-inputs = {{ tide_times = "Text" }}-output = "Text"-prompt = "Write a note from these tide times: $tide_times"-"""- (directory / f"{domain_code}.mthds").write_text(content, encoding="utf-8")--_NEXT_STEP = "Declare this input as an Image or a Document, or as a concept that refines one of them."_FACTORY_REFUSAL_CLASSES: list[type[PipelexError]] = [@@ -141,32 +120,6 @@ class TestFactoryRefusalVerdicts:(strict_item,) = report.to_dict(disclosure_mode=DisclosureMode.STRICT)["validation_errors"]assert _NEXT_STEP in strict_item["message"]- async def test_validate_ops_validate_pipe_answers_a_load_refusal_with_the_verdict(self, tmp_path: Path) -> None:- bundle_path = _write_bundle(directory=tmp_path)-- with pytest.raises(ValidateBundleError) as raised:- await validate_pipe("read_almanac_pages", library_dirs=[tmp_path])-- _assert_located_extract_item(items=raised.value.to_error_report().validation_errors or [], bundle_path=bundle_path)-- async def test_validate_ops_validate_all_answers_a_load_refusal_with_the_verdict(self, tmp_path: Path) -> None:- bundle_path = _write_bundle(directory=tmp_path)-- with pytest.raises(ValidateBundleError) as raised:- await validate_all(library_dirs=[tmp_path])-- _assert_located_extract_item(items=raised.value.to_error_report().validation_errors or [], bundle_path=bundle_path)-- async def test_validate_ops_validate_all_locates_a_wiring_refusal_on_its_file(self, tmp_path: Path) -> None:- bundle_path = _write_bundle(directory=tmp_path, content=_SEQUENCE_OUTPUT_MISMATCH_BUNDLE)-- with pytest.raises(ValidateBundleError) as raised:- await validate_all(library_dirs=[tmp_path])-- (item,) = raised.value.to_error_report().validation_errors or []- assert item.pipe_code == "summarize_almanac"- assert item.source == str(bundle_path)-async def test_agent_validate_all_locates_a_wiring_refusal_on_its_file(self, tmp_path: Path) -> None:bundle_path = _write_bundle(directory=tmp_path, content=_SEQUENCE_OUTPUT_MISMATCH_BUNDLE)@@ -177,30 +130,6 @@ class TestFactoryRefusalVerdicts:assert item.pipe_code == "summarize_almanac"assert item.source == str(bundle_path)- async def test_validate_ops_validate_all_lets_a_teardown_fault_propagate(self, tmp_path: Path, mocker: MockerFixture) -> None:- _write_bundle(directory=tmp_path, content=_SEQUENCE_OUTPUT_MISMATCH_BUNDLE.replace('output = "Text[]"', 'output = "Text"'))- library_manager = get_library_manager()- real_teardown = library_manager.teardown- fault = LibraryError("the library could not be torn down")-- def _teardown_then_fail(*, library_id: str) -> None:- real_teardown(library_id=library_id)- raise fault-- mocker.patch.object(library_manager, "teardown", side_effect=_teardown_then_fail)-- with pytest.raises(LibraryError) as raised:- await validate_all(library_dirs=[tmp_path])-- assert raised.value is fault-- async def test_validate_ops_validate_pipe_keeps_an_ambiguous_code_out_of_the_verdict(self, tmp_path: Path) -> None:- _write_named_pipe_bundle(directory=tmp_path, domain_code="harbour_notes")- _write_named_pipe_bundle(directory=tmp_path, domain_code="quay_notes")-- with pytest.raises(EntryPipeAmbiguousError):- await validate_pipe("write_note", library_dirs=[tmp_path])-async def test_an_inherited_system_prompt_refusal_quotes_no_token_of_it(self, tmp_path: Path) -> None:content = _INHERITED_SYSTEM_PROMPT_BUNDLE.replace("You write for {% if %} harbour users.", "You write for {% quay_ledger %} harbour users.")bundle_path = _write_bundle(directory=tmp_path, content=content)diff --git a/tests/integration/pipelex/pipeline/test_validate_bundle_loaded_on_success.py b/tests/integration/pipelex/pipeline/test_validate_bundle_loaded_on_success.pyindex c8b0c1bec..7260d67d8 100644--- a/tests/integration/pipelex/pipeline/test_validate_bundle_loaded_on_success.py+++ b/tests/integration/pipelex/pipeline/test_validate_bundle_loaded_on_success.py@@ -1,19 +1,19 @@"""Pin: a successful ``validate_bundle`` leaves the library loaded + current (D6 inner-sweep contract).-The build/inputs/output CLIs and builder operations (``inputs_ops``, ``output_ops``,-``runner_code_ops``, ``validate_pipe_in_bundle``) call ``validate_bundle`` (or ``validate_pipes``-directly) and then immediately ``get_required_entry_pipe(...)`` against the library it left open. The-migration to ``BundleValidator.validate_pipes`` — the public inner sweep, which deliberately never-tears the library down — must preserve this: a sweep that tore the library down on success would-strand every one of those callers with ``No current library set`` / ``PipeNotFoundError``.+The build inputs/output CLIs and the inputs template engine (``build_inputs_for_pipe``) call+``validate_bundle`` and then immediately ``get_required_entry_pipe(...)`` against the library it left+open. The migration to ``BundleValidator.validate_pipes`` — the public inner sweep, which+deliberately never tears the library down — must preserve this: a sweep that tore the library down on+success would strand every one of those callers with ``No current library set`` /+``PipeNotFoundError``."""from __future__ import annotationsimport pytest-from pipelex.builder.operations.runner_code_ops import build_runner_code_for_pipefrom pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, get_required_entry_pipe+from pipelex.pipeline.inputs_template import build_inputs_for_pipefrom pipelex.pipeline.validate_bundle import validate_bundle_LOADED_DOMAIN = "loaded_on_success"@@ -50,13 +50,14 @@ class TestValidateBundleLoadedOnSuccess:get_library_manager().teardown(library_id=library_id)clear_current_library()- async def test_runner_code_ops_resolves_pipe_after_inner_sweep(self) -> None:- # runner_code_ops is the caller that drives the inner sweep (validate_pipes) directly and then- # resolves + generates code against the still-open library — the loaded-on-success contract in action.- runner_code = await build_runner_code_for_pipe(mthds_contents=[_LOADED_MTHDS], pipe_code="summarize_doc")+ async def test_inputs_template_resolves_pipe_after_validation(self) -> None:+ # The inputs template engine validates the bundle, then resolves the pipe and renders its inputs+ # against the still-open library — the loaded-on-success contract in action.+ inputs_result = await build_inputs_for_pipe(mthds_contents=[_LOADED_MTHDS], pipe_code="summarize_doc")library_id = get_current_library_id_or_none()try:- assert "summarize_doc" in runner_code+ assert inputs_result["pipe_ref"] == f"{_LOADED_DOMAIN}.summarize_doc"+ assert "doc" in inputs_result["inputs"]finally:if library_id is not None:get_library_manager().teardown(library_id=library_id)diff --git a/tests/unit/pipelex/builder/concept/test_concept_blueprint.py b/tests/unit/pipelex/builder/concept/test_concept_blueprint.pydeleted file mode 100644index 2da86e01e..000000000--- a/tests/unit/pipelex/builder/concept/test_concept_blueprint.py+++ /dev/null@@ -1,39 +0,0 @@-import pytest--from pipelex import log-from pipelex.builder.concept.concept_spec import ConceptSpec-from pipelex.core.concepts.concept_blueprint import ConceptBlueprint-from tests.unit.pipelex.builder.concept.test_data import ConceptBlueprintTestCases, ConceptCodeValidationTestCases---class TestConceptBlueprintConversion:- @pytest.mark.parametrize(- ("topic", "concept_spec", "expected_core"),- ConceptBlueprintTestCases.TEST_CASES,- )- def test_concept_to_core_blueprint(self, topic: str, concept_spec: ConceptSpec, expected_core: ConceptBlueprint):- log.verbose(f"Testing {topic}")- result = concept_spec.to_blueprint()- assert result == expected_core---class TestConceptCodeValidation:- """Tests for concept code validation and snake_case to PascalCase conversion."""-- @pytest.mark.parametrize(- ("topic", "input_code", "expected_code"),- ConceptCodeValidationTestCases.TEST_CASES,- )- def test_concept_code_conversion(self, topic: str, input_code: str, expected_code: str):- log.verbose(f"Testing {topic}: '{input_code}' -> '{expected_code}'")-- # Create a ConceptSpec with the input code- concept_spec = ConceptSpec(- concept_code=input_code,- description="Test concept for code validation",- refines=None,- structure=None,- )-- # Verify the concept code was converted correctly- assert concept_spec.concept_code == expected_code, f"Expected concept code to be '{expected_code}', but got '{concept_spec.concept_code}'"diff --git a/tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.py b/tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.pydeleted file mode 100644index 4298dd66b..000000000--- a/tests/unit/pipelex/builder/concept/test_concept_structure_spec_choices.py+++ /dev/null@@ -1,71 +0,0 @@-from typing import Any--import pytest-from pydantic import ValidationError--from pipelex import log-from pipelex.builder.concept.concept_spec import ConceptStructureSpec, ConceptStructureSpecFieldType-from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprintFieldType-from tests.unit.pipelex.builder.concept.test_data import ConceptStructureSpecChoicesTestCases---class TestConceptStructureSpecChoices:- """Tests for choices field behavior in ConceptStructureSpec."""-- @pytest.mark.parametrize(- ("topic", "spec_data", "expected_type", "expected_choices"),- ConceptStructureSpecChoicesTestCases.VALID_CASES,- )- def test_valid_choices(- self,- topic: str,- spec_data: dict[str, Any],- expected_type: ConceptStructureSpecFieldType,- expected_choices: list[str],- ) -> None:- """Choices with compatible types should be accepted, defaulting to TEXT when type is omitted."""- spec = ConceptStructureSpec.model_validate(spec_data)- assert spec.type == expected_type- assert spec.choices == expected_choices- log.verbose(f"[{topic}] spec.type={spec.type}, spec.choices={spec.choices}")-- def test_choices_without_type_converts_to_blueprint(self) -> None:- """Choices without explicit type should default to TEXT and convert to blueprint correctly."""- spec = ConceptStructureSpec.model_validate(- {- "the_field_name": "status",- "description": "Order status",- "choices": ["pending", "processing", "completed"],- "required": True,- }- )- blueprint = spec.to_blueprint()- assert blueprint.type == ConceptStructureBlueprintFieldType.TEXT- assert blueprint.choices == ["pending", "processing", "completed"]- log.verbose(f"Blueprint: type={blueprint.type}, choices={blueprint.choices}")-- def test_no_type_no_choices_fails_validation(self) -> None:- """Missing type without choices should still fail validation."""- with pytest.raises(ValidationError):- ConceptStructureSpec.model_validate(- {- "the_field_name": "name",- "description": "A name field",- }- )-- @pytest.mark.parametrize(- ("topic", "spec_data"),- ConceptStructureSpecChoicesTestCases.INCOMPATIBLE_CASES,- )- def test_incompatible_type_with_choices(- self,- topic: str,- spec_data: dict[str, Any],- ) -> None:- """Choices with incompatible types (boolean, date, concept, list) should raise validation errors."""- with pytest.raises(ValidationError) as exc_info:- ConceptStructureSpec.model_validate(spec_data)- error_str = str(exc_info.value)- assert "choices" in error_str.lower()- log.verbose(f"[{topic}] Validation error: {error_str}")diff --git a/tests/unit/pipelex/builder/concept/test_concept_structure_spec_validation.py b/tests/unit/pipelex/builder/concept/test_concept_structure_spec_validation.pydeleted file mode 100644index fbb6bb208..000000000--- a/tests/unit/pipelex/builder/concept/test_concept_structure_spec_validation.py+++ /dev/null@@ -1,117 +0,0 @@-from datetime import date, datetime--import pytest-from pydantic import ValidationError--from pipelex import log-from pipelex.builder.concept.concept_spec import ConceptStructureSpec, ConceptStructureSpecFieldType-from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprintFieldType---class TestConceptStructureSpecValidation:- """Tests for validation of ConceptStructureSpec with CONCEPT field type."""-- def test_concept_type_requires_concept_ref(self):- """CONCEPT type must have concept_ref set."""- with pytest.raises(ValidationError) as exc_info:- ConceptStructureSpec(- the_field_name="customer",- description="The customer",- type=ConceptStructureSpecFieldType.CONCEPT,- required=True,- )- assert "concept_ref must be set" in str(exc_info.value)-- def test_concept_type_with_concept_ref_valid(self):- """CONCEPT type with concept_ref is valid."""- spec = ConceptStructureSpec(- the_field_name="customer",- description="The customer",- type=ConceptStructureSpecFieldType.CONCEPT,- concept_ref="myapp.Customer",- required=True,- )- assert spec.type == ConceptStructureSpecFieldType.CONCEPT- assert spec.concept_ref == "myapp.Customer"-- def test_required_with_default_is_rejected_at_spec_level(self):- """The E3 pair is rejected on the authoring surface itself, with the same two-remedies- message as the blueprint — a builder agent must not validate green and then die on its- own emitted TOML.- """- with pytest.raises(ValidationError) as exc_info:- ConceptStructureSpec(- the_field_name="title",- description="A title",- type=ConceptStructureSpecFieldType.TEXT,- required=True,- default_value="Untitled",- )- error_str = str(exc_info.value)- assert "required" in error_str- assert "default_value" in error_str-- def test_concept_type_cannot_have_default_value(self):- """CONCEPT type cannot have default_value set."""- with pytest.raises(ValidationError) as exc_info:- ConceptStructureSpec(- the_field_name="customer",- description="The customer",- type=ConceptStructureSpecFieldType.CONCEPT,- concept_ref="myapp.Customer",- default_value={"name": "test"},- )- assert "cannot be set for concept type" in str(exc_info.value)-- def test_concept_ref_only_allowed_for_concept_type(self):- """concept_ref can only be set when type is CONCEPT."""- with pytest.raises(ValidationError) as exc_info:- ConceptStructureSpec(- the_field_name="name",- description="The name",- type=ConceptStructureSpecFieldType.TEXT,- concept_ref="myapp.Customer",- )- error_str = str(exc_info.value)- assert "concept_ref" in error_str- assert "type is 'concept'" in error_str-- def test_date_spec_accepts_date_rejects_datetime(self):- """A spec `date` field accepts a calendar date and rejects a datetime (mirrors the blueprint layer)."""- spec = ConceptStructureSpec(- the_field_name="issued_on", description="Issue date", type=ConceptStructureSpecFieldType.DATE, default_value=date(2026, 7, 7)- )- assert spec.to_blueprint().type == ConceptStructureBlueprintFieldType.DATE-- with pytest.raises(ValidationError, match="default_value type mismatch: expected date"):- ConceptStructureSpec(- the_field_name="issued_on",- description="Issue date",- type=ConceptStructureSpecFieldType.DATE,- default_value=datetime(2026, 7, 7, 15, 40),- )-- def test_datetime_spec_type_and_to_blueprint(self):- """A spec `datetime` field accepts a timestamp default and maps to the blueprint DATETIME type."""- spec = ConceptStructureSpec(- the_field_name="recorded_at",- description="Record timestamp",- type=ConceptStructureSpecFieldType.DATETIME,- default_value=datetime(2026, 7, 7, 15, 40),- )- assert spec.to_blueprint().type == ConceptStructureBlueprintFieldType.DATETIME-- def test_to_blueprint_concept_type(self):- """Test to_blueprint() conversion for CONCEPT type."""- spec = ConceptStructureSpec(- the_field_name="customer",- description="The customer",- type=ConceptStructureSpecFieldType.CONCEPT,- concept_ref="myapp.Customer",- required=True,- )- blueprint = spec.to_blueprint()- assert blueprint.type is not None- assert blueprint.type == ConceptStructureBlueprintFieldType.CONCEPT- assert blueprint.concept_ref == "myapp.Customer"- log.verbose(f"Blueprint: {blueprint}")diff --git a/tests/unit/pipelex/builder/concept/test_data.py b/tests/unit/pipelex/builder/concept/test_data.pydeleted file mode 100644index 9ec2abbc5..000000000--- a/tests/unit/pipelex/builder/concept/test_data.py+++ /dev/null@@ -1,405 +0,0 @@-from typing import Any, ClassVar--from pipelex.builder.concept.concept_spec import ConceptSpec, ConceptStructureSpec, ConceptStructureSpecFieldType-from pipelex.core.concepts.concept_blueprint import ConceptBlueprint, ConceptStructureBlueprint-from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprintFieldType---class ConceptBlueprintTestCases:- SIMPLE_CONCEPT = (- "simple_concept",- ConceptSpec(- concept_code="ConceptCode",- description="A simple test concept",- refines=None,- structure=None,- ),- ConceptBlueprint(- description="A simple test concept",- refines=None,- structure=None,- ),- )-- CONCEPT_WITH_REFINES = (- "concept_with_refines",- ConceptSpec(- concept_code="ConceptCode",- description="An enhanced text concept",- refines="Text",- structure=None,- ),- ConceptBlueprint(- description="An enhanced text concept",- refines="Text",- structure=None,- ),- )-- CONCEPT_WITH_TEXT_FIELD = (- "concept_with_text_field",- ConceptSpec(- concept_code="ConceptCode",- description="Entity with text field",- structure={- "name": ConceptStructureSpec(- the_field_name="name",- description="The name field",- type=ConceptStructureSpecFieldType.TEXT,- required=True,- ),- },- ),- ConceptBlueprint(- description="Entity with text field",- refines=None,- structure={- "name": ConceptStructureBlueprint(- description="The name field",- type=ConceptStructureBlueprintFieldType.TEXT,- required=True,- default_value=None,- ),- },- ),- )-- CONCEPT_WITH_INTEGER_FIELD = (- "concept_with_integer_field",- ConceptSpec(- concept_code="ConceptCode",- description="Entity with integer field",- structure={- "age": ConceptStructureSpec(- the_field_name="age",- description="The age field",- type=ConceptStructureSpecFieldType.INTEGER,- required=False,- default_value=0,- ),- },- ),- ConceptBlueprint(- description="Entity with integer field",- refines=None,- structure={- "age": ConceptStructureBlueprint(- description="The age field",- type=ConceptStructureBlueprintFieldType.INTEGER,- required=False,- default_value=0,- ),- },- ),- )-- CONCEPT_WITH_MULTIPLE_FIELDS = (- "concept_with_multiple_fields",- ConceptSpec(- concept_code="ConceptCode",- description="Entity with multiple fields",- structure={- "name": ConceptStructureSpec(- the_field_name="name",- description="Name",- type=ConceptStructureSpecFieldType.TEXT,- required=True,- ),- "age": ConceptStructureSpec(- the_field_name="age",- description="Age",- type=ConceptStructureSpecFieldType.INTEGER,- required=True,- ),- "active": ConceptStructureSpec(- the_field_name="active",- description="Active status",- type=ConceptStructureSpecFieldType.BOOLEAN,- required=False,- default_value=True,- ),- },- ),- ConceptBlueprint(- description="Entity with multiple fields",- refines=None,- structure={- "name": ConceptStructureBlueprint(- description="Name",- type=ConceptStructureBlueprintFieldType.TEXT,- required=True,- default_value=None,- ),- "age": ConceptStructureBlueprint(- description="Age",- type=ConceptStructureBlueprintFieldType.INTEGER,- required=True,- ),- "active": ConceptStructureBlueprint(- description="Active status",- type=ConceptStructureBlueprintFieldType.BOOLEAN,- required=False,- default_value=True,- ),- },- ),- )-- CONCEPT_WITH_CONCEPT_REF = (- "concept_with_concept_ref",- ConceptSpec(- concept_code="Invoice",- description="An invoice with a customer reference",- structure={- "invoice_number": ConceptStructureSpec(- the_field_name="invoice_number",- description="The invoice number",- type=ConceptStructureSpecFieldType.TEXT,- required=True,- ),- "customer": ConceptStructureSpec(- the_field_name="customer",- description="The customer for this invoice",- type=ConceptStructureSpecFieldType.CONCEPT,- concept_ref="myapp.Customer",- required=True,- ),- },- ),- ConceptBlueprint(- description="An invoice with a customer reference",- refines=None,- structure={- "invoice_number": ConceptStructureBlueprint(- description="The invoice number",- type=ConceptStructureBlueprintFieldType.TEXT,- required=True,- default_value=None,- ),- "customer": ConceptStructureBlueprint(- description="The customer for this invoice",- type=ConceptStructureBlueprintFieldType.CONCEPT,- concept_ref="myapp.Customer",- required=True,- default_value=None,- ),- },- ),- )-- TEST_CASES: ClassVar[list[tuple[str, ConceptSpec, ConceptBlueprint]]] = [- SIMPLE_CONCEPT,- CONCEPT_WITH_REFINES,- CONCEPT_WITH_TEXT_FIELD,- CONCEPT_WITH_INTEGER_FIELD,- CONCEPT_WITH_MULTIPLE_FIELDS,- CONCEPT_WITH_CONCEPT_REF,- ]---class ConceptStructureSpecChoicesTestCases:- """Test cases for choices field behavior in ConceptStructureSpec."""-- # choices without type -> defaults to text- CHOICES_NO_TYPE = (- "choices_no_type",- {- "the_field_name": "status",- "description": "Order status",- "choices": ["pending", "processing", "completed"],- "required": True,- },- ConceptStructureSpecFieldType.TEXT,- ["pending", "processing", "completed"],- )-- # choices with explicit text type- CHOICES_TEXT_TYPE = (- "choices_text_type",- {- "the_field_name": "priority",- "description": "Priority level",- "type": "text",- "choices": ["low", "medium", "high"],- },- ConceptStructureSpecFieldType.TEXT,- ["low", "medium", "high"],- )-- # choices with integer type- CHOICES_INTEGER_TYPE = (- "choices_integer_type",- {- "the_field_name": "rating",- "description": "Star rating",- "type": "integer",- "choices": ["1", "2", "3", "4", "5"],- },- ConceptStructureSpecFieldType.INTEGER,- ["1", "2", "3", "4", "5"],- )-- # choices with number type- CHOICES_NUMBER_TYPE = (- "choices_number_type",- {- "the_field_name": "score",- "description": "Score on a half-point scale",- "type": "number",- "choices": ["0", "0.5", "1", "1.5", "2"],- },- ConceptStructureSpecFieldType.NUMBER,- ["0", "0.5", "1", "1.5", "2"],- )-- VALID_CASES: ClassVar[list[tuple[str, dict[str, Any], ConceptStructureSpecFieldType, list[str]]]] = [- CHOICES_NO_TYPE,- CHOICES_TEXT_TYPE,- CHOICES_INTEGER_TYPE,- CHOICES_NUMBER_TYPE,- ]-- # Incompatible types for choices- CHOICES_BOOLEAN_TYPE = (- "choices_boolean_type",- {- "the_field_name": "flag",- "description": "A flag",- "type": "boolean",- "choices": ["true", "false"],- },- )-- CHOICES_DATE_TYPE = (- "choices_date_type",- {- "the_field_name": "date_field",- "description": "A date",- "type": "date",- "choices": ["2024-01-01", "2024-06-01"],- },- )-- CHOICES_CONCEPT_TYPE = (- "choices_concept_type",- {- "the_field_name": "ref_field",- "description": "A reference",- "type": "concept",- "concept_ref": "myapp.Customer",- "choices": ["a", "b"],- },- )-- CHOICES_LIST_TYPE = (- "choices_list_type",- {- "the_field_name": "list_field",- "description": "A list",- "type": "list",- "item_type": "text",- "choices": ["a", "b"],- },- )-- INCOMPATIBLE_CASES: ClassVar[list[tuple[str, dict[str, Any]]]] = [- CHOICES_BOOLEAN_TYPE,- CHOICES_DATE_TYPE,- CHOICES_CONCEPT_TYPE,- CHOICES_LIST_TYPE,- ]---class ConceptCodeValidationTestCases:- """Test cases for concept code validation and snake_case to PascalCase conversion."""-- # Test case: snake_case without domain -> PascalCase- SNAKE_CASE_NO_DOMAIN = (- "snake_case_no_domain",- "concept_name",- "ConceptName",- )-- # Test case: PascalCase without domain -> unchanged- PASCAL_CASE_NO_DOMAIN = (- "pascal_case_no_domain",- "ConceptName",- "ConceptName",- )-- # Test case: snake_case with domain -> domain.PascalCase- SNAKE_CASE_WITH_DOMAIN = (- "snake_case_with_domain",- "my_domain.concept_name",- "my_domain.ConceptName",- )-- # Test case: PascalCase with domain -> unchanged- PASCAL_CASE_WITH_DOMAIN = (- "pascal_case_with_domain",- "my_domain.ConceptName",- "my_domain.ConceptName",- )-- # Test case: mixed case with domain -> domain.PascalCase- MIXED_CASE_WITH_DOMAIN = (- "mixed_case_with_domain",- "my_domain.some_complex_concept_name",- "my_domain.SomeComplexConceptName",- )-- # Test case: single word snake_case -> PascalCase- SINGLE_WORD_SNAKE = (- "single_word_snake",- "concept",- "Concept",- )-- # Test case: multiple underscores -> PascalCase- MULTIPLE_UNDERSCORES = (- "multiple_underscores",- "my_super_long_concept_name",- "MySuperLongConceptName",- )-- # Test case: with numbers in snake_case- WITH_NUMBERS_SNAKE = (- "with_numbers_snake",- "concept_v2_name",- "ConceptV2Name",- )-- # Test case: with numbers in domain.snake_case- WITH_NUMBERS_DOMAIN_SNAKE = (- "with_numbers_domain_snake",- "domain_v1.concept_name_v2",- "domain_v1.ConceptNameV2",- )-- # Test case: multi-segment domain path -> splits on last dot- MULTI_SEGMENT_DOMAIN = (- "multi_segment_domain",- "legal.contracts.Invoice",- "legal.contracts.Invoice",- )-- # Test case: multi-segment domain with snake_case concept -> PascalCase- MULTI_SEGMENT_DOMAIN_SNAKE = (- "multi_segment_domain_snake",- "legal.contracts.non_compete_clause",- "legal.contracts.NonCompeteClause",- )-- TEST_CASES: ClassVar[list[tuple[str, str, str]]] = [- SNAKE_CASE_NO_DOMAIN,- PASCAL_CASE_NO_DOMAIN,- SNAKE_CASE_WITH_DOMAIN,- PASCAL_CASE_WITH_DOMAIN,- MIXED_CASE_WITH_DOMAIN,- SINGLE_WORD_SNAKE,- MULTIPLE_UNDERSCORES,- WITH_NUMBERS_SNAKE,- WITH_NUMBERS_DOMAIN_SNAKE,- MULTI_SEGMENT_DOMAIN,- MULTI_SEGMENT_DOMAIN_SNAKE,- ]diff --git a/tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py b/tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.pydeleted file mode 100644index 688777d14..000000000--- a/tests/unit/pipelex/builder/operations/test_concept_spec_to_toml.py+++ /dev/null@@ -1,257 +0,0 @@-"""Unit tests for concept_spec_to_toml and structure_field_to_dict from concept_ops."""--from __future__ import annotations--import json-import tomllib-from typing import Any--from pipelex.builder.concept.concept_spec import ConceptStructureSpec, ConceptStructureSpecFieldType-from pipelex.builder.operations.concept_ops import (- concept_spec_to_toml,- parse_concept_spec,- structure_field_to_dict,-)-from pipelex.core.concepts.concept_blueprint import ConceptBlueprint-from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprint---class TestConceptSpecToToml:- """Tests for structure_field_to_dict and concept_spec_to_toml covering all field types and modes."""-- # -- structure_field_to_dict -------------------------------------------- def test_text_field_description_only(self) -> None:- """Text field with only description should produce minimal dict."""- field_spec = ConceptStructureSpec(- the_field_name="name",- description="The person's name",- type=ConceptStructureSpecFieldType.TEXT,- )- result = structure_field_to_dict(field_spec)- assert result == {"description": "The person's name"}- assert "type" not in result-- def test_text_field_with_required(self) -> None:- field_spec = ConceptStructureSpec(- the_field_name="name",- description="The person's name",- type=ConceptStructureSpecFieldType.TEXT,- required=True,- )- result = structure_field_to_dict(field_spec)- assert result["type"] == ConceptStructureSpecFieldType.TEXT- assert result["required"] is True-- def test_integer_field(self) -> None:- field_spec = ConceptStructureSpec(- the_field_name="age",- description="Age in years",- type=ConceptStructureSpecFieldType.INTEGER,- )- result = structure_field_to_dict(field_spec)- assert result["type"] == ConceptStructureSpecFieldType.INTEGER- assert result["description"] == "Age in years"-- def test_field_with_default_value(self) -> None:- field_spec = ConceptStructureSpec(- the_field_name="count",- description="Number of items",- type=ConceptStructureSpecFieldType.INTEGER,- default_value=0,- )- result = structure_field_to_dict(field_spec)- assert result["default_value"] == 0, "The language key is default_value — `default` evaporates on re-load (E8)"-- def test_concept_field_with_concept_ref(self) -> None:- field_spec = ConceptStructureSpec(- the_field_name="customer",- description="The customer",- type=ConceptStructureSpecFieldType.CONCEPT,- concept_ref="myapp.Customer",- )- result = structure_field_to_dict(field_spec)- assert result["concept_ref"] == "myapp.Customer"-- def test_field_with_choices(self) -> None:- field_spec = ConceptStructureSpec(- the_field_name="status",- description="Current status",- type=ConceptStructureSpecFieldType.TEXT,- choices=["pending", "in_progress", "complete"],- )- result = structure_field_to_dict(field_spec)- assert result["choices"] == ["pending", "in_progress", "complete"]-- def test_field_with_choices_and_required(self) -> None:- field_spec = ConceptStructureSpec(- the_field_name="priority",- description="Task priority",- type=ConceptStructureSpecFieldType.TEXT,- choices=["low", "medium", "high"],- required=True,- )- result = structure_field_to_dict(field_spec)- assert result["choices"] == ["low", "medium", "high"]- assert result["required"] is True-- def test_field_with_choices_and_default(self) -> None:- field_spec = ConceptStructureSpec(- the_field_name="status",- description="Current status",- type=ConceptStructureSpecFieldType.TEXT,- choices=["active", "inactive", "pending"],- default_value="pending",- )- result = structure_field_to_dict(field_spec)- assert result["choices"] == ["active", "inactive", "pending"]- assert result["default_value"] == "pending"-- # -- concept_spec_to_toml ----------------------------------------------- def test_simple_refines_concept(self) -> None:- spec_data: dict[str, Any] = {- "concept_code": "Invoice",- "description": "A commercial invoice",- "refines": "Text",- }- concept_spec = parse_concept_spec(spec_data)- toml_output = concept_spec_to_toml(concept_spec)- assert "[concept.Invoice]" in toml_output- assert 'description = "A commercial invoice"' in toml_output- assert 'refines = "Text"' in toml_output-- def test_structured_concept_with_multiple_fields(self) -> None:- spec_data: dict[str, Any] = {- "concept_code": "Order",- "description": "A customer order",- "structure": {- "order_id": {"type": "text", "description": "Order identifier", "required": True},- "quantity": {"type": "integer", "description": "Number of items"},- "status": {- "type": "text",- "description": "Order status",- "choices": ["pending", "shipped", "delivered"],- },- },- }- concept_spec = parse_concept_spec(spec_data)- toml_output = concept_spec_to_toml(concept_spec)- assert "[concept.Order]" in toml_output- assert "order_id" in toml_output- assert "required = true" in toml_output- assert "quantity" in toml_output- assert "choices" in toml_output-- def test_toml_includes_choices(self) -> None:- """Regression: choices must appear in TOML output."""- spec_data: dict[str, Any] = {- "concept_code": "TaskStatus",- "description": "A task with status tracking",- "structure": {- "status": {- "type": "text",- "description": "Current status",- "choices": ["pending", "in_progress", "complete"],- }- },- }- concept_spec = parse_concept_spec(spec_data)- toml_output = concept_spec_to_toml(concept_spec)- assert 'choices = ["pending", "in_progress", "complete"]' in toml_output-- def test_choices_none_by_default(self) -> None:- field_spec = ConceptStructureSpec(- the_field_name="name",- description="A name",- type=ConceptStructureSpecFieldType.TEXT,- )- assert field_spec.choices is None-- def test_choices_passed_to_blueprint(self) -> None:- field_spec = ConceptStructureSpec(- the_field_name="status",- description="Current status",- type=ConceptStructureSpecFieldType.TEXT,- choices=["pending", "complete"],- )- blueprint = field_spec.to_blueprint()- assert blueprint.choices == ["pending", "complete"]-- def test_roundtrip_json_to_toml_preserves_choices(self) -> None:- """Full roundtrip from JSON input to TOML output should preserve choices."""- input_json = json.dumps(- {- "concept_code": "WorkItem",- "description": "A work item",- "structure": {- "priority": {- "type": "text",- "description": "Priority level",- "choices": ["low", "medium", "high", "critical"],- "required": True,- }- },- }- )- spec_data = json.loads(input_json)- concept_spec = parse_concept_spec(spec_data)- toml_output = concept_spec_to_toml(concept_spec)- assert 'choices = ["low", "medium", "high", "critical"]' in toml_output- assert "required = true" in toml_output-- def test_description_only_field_uses_string_format(self) -> None:- """A field with only a description should serialize as a simple string in TOML."""- spec_data: dict[str, Any] = {- "concept_code": "Simple",- "description": "A concept with simple fields",- "structure": {"title": "The title"},- }- concept_spec = parse_concept_spec(spec_data)- toml_output = concept_spec_to_toml(concept_spec)- assert 'title = "The title"' in toml_output-- def test_no_structure_omits_structure_section(self) -> None:- spec_data: dict[str, Any] = {- "concept_code": "Plain",- "description": "A plain concept",- "refines": "Text",- }- concept_spec = parse_concept_spec(spec_data)- toml_output = concept_spec_to_toml(concept_spec)- assert "structure" not in toml_output-- def test_builder_toml_roundtrips_through_blueprint_with_default(self) -> None:- """Write-then-validate round trip (E8): a builder-authored default must survive re-load as a- blueprint — the builder once wrote the key `default`, which the language does not read, so- the fact evaporated silently. E7's forbid now turns any recurrence into a hard failure.- """- spec_data: dict[str, Any] = {- "concept_code": "Counter",- "description": "A counter with a default",- "structure": {- "count": {"type": "integer", "description": "Number of items", "default_value": 7},- "label": {"type": "text", "description": "A label", "required": True},- },- }- concept_spec = parse_concept_spec(spec_data)- toml_output = concept_spec_to_toml(concept_spec)- reloaded = tomllib.loads(toml_output)- blueprint = ConceptBlueprint.model_validate(reloaded["concept"]["Counter"])- assert isinstance(blueprint.structure, dict)- count_field = blueprint.structure["count"]- assert isinstance(count_field, ConceptStructureBlueprint)- assert count_field.default_value == 7, "The authored default must survive the write-then-validate loop"- label_field = blueprint.structure["label"]- assert isinstance(label_field, ConceptStructureBlueprint)- assert label_field.required is True-- def test_no_refines_omits_refines(self) -> None:- spec_data: dict[str, Any] = {- "concept_code": "Standalone",- "description": "A standalone concept",- "structure": {"name": "The name"},- }- concept_spec = parse_concept_spec(spec_data)- toml_output = concept_spec_to_toml(concept_spec)- assert "refines" not in toml_outputdiff --git a/tests/unit/pipelex/builder/operations/test_data.py b/tests/unit/pipelex/builder/operations/test_data.pydeleted file mode 100644index e90d99bd6..000000000--- a/tests/unit/pipelex/builder/operations/test_data.py+++ /dev/null@@ -1,14 +0,0 @@-"""Shared test data for pipelex.builder.operations tests."""--from typing import Any, ClassVar---class PipeOpsTestData:- BASE_LLM_SPEC: ClassVar[dict[str, Any]] = {- "pipe_code": "test_pipe",- "description": "Test LLM pipe",- "model": "$writing-creative",- "inputs": {"text": "Text"},- "output": "Text",- "prompt": "Write about $text",- }diff --git a/tests/unit/pipelex/builder/operations/test_parse_concept_spec.py b/tests/unit/pipelex/builder/operations/test_parse_concept_spec.pydeleted file mode 100644index 6427714ae..000000000--- a/tests/unit/pipelex/builder/operations/test_parse_concept_spec.py+++ /dev/null@@ -1,209 +0,0 @@-"""Unit tests for parse_concept_spec from pipelex.builder.operations.concept_ops."""--from __future__ import annotations--from types import MappingProxyType-from typing import Any, ClassVar--import pytest-from pydantic import ValidationError--from pipelex.base_exceptions import error_domain_is_input-from pipelex.builder.concept.concept_spec import ConceptStructureSpecFieldType-from pipelex.builder.concept.exceptions import ConceptSpecError-from pipelex.builder.operations.concept_ops import parse_concept_spec---class TestParseConceptSpec:- """Comprehensive tests for parse_concept_spec: validation, aliases, structure conversion."""-- _BASE: ClassVar[dict[str, Any]] = {- "description": "A test concept",- "refines": "Text",- }-- # -- concept_code aliases ----------------------------------------------- def test_canonical_concept_code(self) -> None:- spec = {**self._BASE, "concept_code": "Invoice"}- result = parse_concept_spec(spec)- assert result.concept_code == "Invoice"-- @pytest.mark.parametrize("alias", ["the_concept_code", "code", "name", "concept_name", "concept_ref"])- def test_concept_code_alias_accepted(self, alias: str) -> None:- spec = {**self._BASE, alias: "Invoice"}- result = parse_concept_spec(spec)- assert result.concept_code == "Invoice"-- def test_canonical_ignores_alias(self) -> None:- """When concept_code is present, alias keys are removed."""- spec = {**self._BASE, "concept_code": "Canonical", "name": "Alias"}- result = parse_concept_spec(spec)- assert result.concept_code == "Canonical"-- def test_multiple_aliases_all_cleaned_up(self) -> None:- spec = {**self._BASE, "concept_code": "Invoice", "name": "Alt", "code": "Alt2"}- result = parse_concept_spec(spec)- assert result.concept_code == "Invoice"-- def test_missing_concept_code_raises(self) -> None:- """Spec with no concept_code and no alias should raise ValidationError."""- spec: dict[str, Any] = {**self._BASE}- with pytest.raises(ValidationError):- parse_concept_spec(spec)-- # -- does not mutate caller's dict -------------------------------------- def test_original_dict_unchanged(self) -> None:- original: dict[str, Any] = {**self._BASE, "code": "Invoice"}- snapshot = dict(original)- parse_concept_spec(original)- assert original == snapshot-- # -- structure field conversion ----------------------------------------- def test_string_field_becomes_text(self) -> None:- """A bare string in structure should be treated as a text field."""- spec: dict[str, Any] = {- "concept_code": "Simple",- "description": "A simple concept",- "structure": {"title": "The title of the item"},- }- result = parse_concept_spec(spec)- assert result.structure is not None- assert result.structure["title"].type == ConceptStructureSpecFieldType.TEXT- assert result.structure["title"].description == "The title of the item"-- def test_dict_field_without_type_defaults_to_text(self) -> None:- """When agent provides a dict field spec but omits 'type', it should default to text."""- spec: dict[str, Any] = {- "concept_code": "MatchAnalysis",- "description": "Analysis of CV-job match",- "structure": {- "matching_strengths": {"description": "Key areas where CV aligns", "required": True},- "gaps": {"description": "Areas where CV falls short", "required": True},- "summary": {"description": "Brief overall assessment"},- },- }- result = parse_concept_spec(spec)- assert result.structure is not None- for field_name in ("matching_strengths", "gaps", "summary"):- assert result.structure[field_name].type == ConceptStructureSpecFieldType.TEXT- assert result.structure["matching_strengths"].required is True- assert result.structure["summary"].required is False-- def test_mixed_string_and_dict_fields(self) -> None:- spec: dict[str, Any] = {- "concept_code": "Mixed",- "description": "A mixed concept",- "structure": {- "name": "The person's name",- "age": {"type": "integer", "description": "Age in years"},- },- }- result = parse_concept_spec(spec)- assert result.structure is not None- assert result.structure["name"].type == ConceptStructureSpecFieldType.TEXT- assert result.structure["age"].type == ConceptStructureSpecFieldType.INTEGER-- # -- malformed structure shape (typed, not bare AttributeError/TypeError) ---- # A present-but-falsy non-mapping (``[]`` / ``""`` / ``0`` / ``False``) must hit the- # typed guard too, not slip past a truthiness check into a bare Pydantic ValidationError.- @pytest.mark.parametrize("bad_structure", ["not_a_dict", [], "", 0, False])- def test_non_dict_structure_raises_concept_spec_error(self, bad_structure: Any) -> None:- """A non-mapping ``structure`` is a caller-input fault, not a bare AttributeError/ValidationError."""- spec: dict[str, Any] = {"concept_code": "Bad", "description": "d", "structure": bad_structure}- with pytest.raises(ConceptSpecError, match="'structure' must be a mapping"):- parse_concept_spec(spec)-- def test_none_structure_is_treated_as_absent(self) -> None:- """``structure: None`` means "no structure" (the field defaults to None), not a malformed mapping."""- spec: dict[str, Any] = {"concept_code": "NoStruct", "description": "d", "refines": "Text", "structure": None}- result = parse_concept_spec(spec)- assert result.structure is None-- @pytest.mark.parametrize("bad_field_value", [42, [1, 2], 3.14, True])- def test_non_str_non_dict_field_raises_concept_spec_error(self, bad_field_value: Any) -> None:- """A structure field that is neither a description string nor a field-spec mapping is a typed input error."""- spec: dict[str, Any] = {"concept_code": "Bad", "description": "d", "structure": {"my_field": bad_field_value}}- with pytest.raises(ConceptSpecError, match="must be a description string or a field-spec mapping"):- parse_concept_spec(spec)-- def test_malformed_structure_classifies_as_input_domain(self) -> None:- """The raised error carries the INPUT domain so HTTP consumers render it as a 422."""- spec: dict[str, Any] = {"concept_code": "Bad", "description": "d", "structure": "not_a_dict"}- with pytest.raises(ConceptSpecError) as exc_info:- parse_concept_spec(spec)- assert error_domain_is_input(exc_info.value.error_domain)-- # -- malformed top-level shape (typed, not bare TypeError/ValueError) ---- @pytest.mark.parametrize("bad_spec", ["a string", ["a", "b"], 123, 3.14, None])- def test_non_mapping_top_level_raises_concept_spec_error(self, bad_spec: Any) -> None:- """A non-mapping top-level spec leaks a bare TypeError/ValueError from dict() without the guard."""- with pytest.raises(ConceptSpecError, match="must be a mapping"):- parse_concept_spec(bad_spec)-- def test_non_mapping_top_level_classifies_as_input_domain(self) -> None:- with pytest.raises(ConceptSpecError) as exc_info:- parse_concept_spec("not a mapping")- assert error_domain_is_input(exc_info.value.error_domain)-- def test_non_dict_mapping_top_level_is_accepted(self) -> None:- """A non-``dict`` mapping (here a read-only ``MappingProxyType``) is a mapping and must parse, not be rejected."""- spec = MappingProxyType(- {- "concept_code": "Person",- "description": "A person record",- "structure": MappingProxyType({"name": "The person's name"}),- }- )- result = parse_concept_spec(spec)- assert result.concept_code == "Person"- assert result.structure is not None- assert "name" in result.structure-- # -- full parsing scenarios --------------------------------------------- def test_simple_concept_with_refines(self) -> None:- spec_data: dict[str, Any] = {- "concept_code": "Invoice",- "description": "A commercial invoice",- "refines": "Text",- }- result = parse_concept_spec(spec_data)- assert result.concept_code == "Invoice"- assert result.description == "A commercial invoice"- assert result.refines == "Text"-- def test_structured_concept(self) -> None:- spec_data: dict[str, Any] = {- "concept_code": "Person",- "description": "A person record",- "structure": {- "name": "The person's name",- "age": {"type": "integer", "description": "Age in years"},- },- }- result = parse_concept_spec(spec_data)- assert result.concept_code == "Person"- assert result.structure is not None- assert "name" in result.structure- assert "age" in result.structure-- def test_concept_with_choices_in_structure(self) -> None:- spec_data: dict[str, Any] = {- "concept_code": "Task",- "description": "A task with status",- "structure": {- "status": {- "type": "text",- "description": "Current status",- "choices": ["pending", "in_progress", "complete"],- }- },- }- result = parse_concept_spec(spec_data)- assert result.structure is not None- assert result.structure["status"].choices == ["pending", "in_progress", "complete"]diff --git a/tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py b/tests/unit/pipelex/builder/operations/test_parse_pipe_spec.pydeleted file mode 100644index c30fbadc0..000000000--- a/tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py+++ /dev/null@@ -1,522 +0,0 @@-"""Unit tests for parse_pipe_spec from pipelex.builder.operations.pipe_ops."""--from __future__ import annotations--from typing import Any, ClassVar--import pytest-from pydantic import ValidationError--from pipelex.base_exceptions import error_domain_is_input-from pipelex.builder.operations.pipe_ops import parse_pipe_spec-from pipelex.builder.pipe.exceptions import PipeSpecError-from pipelex.builder.pipe.pipe_batch_spec import PipeBatchSpec-from pipelex.builder.pipe.pipe_condition_spec import PipeConditionSpec-from pipelex.builder.pipe.pipe_extract_spec import PipeExtractSpec-from pipelex.builder.pipe.pipe_func_spec import PipeFuncSpec-from pipelex.builder.pipe.pipe_img_gen_spec import PipeImgGenSpec-from pipelex.builder.pipe.pipe_judge_spec import PipeJudgeSpec-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpec-from pipelex.builder.pipe.pipe_search_spec import PipeSearchSpec-from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.builder.pipe.pipe_signature_spec import PipeSignatureSpec-from pipelex.pipe_machinery.pipe_blueprint import PipeType-from tests.unit.pipelex.builder.operations.test_data import PipeOpsTestData--_BASE_LLM = PipeOpsTestData.BASE_LLM_SPEC---class TestParsePipeSpec:- """Comprehensive tests for parse_pipe_spec: validation, aliases, tolerance, and dispatch."""-- # -- invalid pipe type -------------------------------------------------- def test_unknown_type_raises(self) -> None:- with pytest.raises(ValueError, match="Invalid pipe type"):- parse_pipe_spec({"pipe_code": "x", "description": "x"}, pipe_type="PipeNonExistent")-- def test_error_lists_valid_types(self) -> None:- with pytest.raises(ValueError, match="PipeLLM"):- parse_pipe_spec({"pipe_code": "x", "description": "x"}, pipe_type="PipeBogus")-- # -- typeless signature (no type) --------------------------------------- def test_typeless_spec_becomes_signature(self) -> None:- """A typeless contract-only spec (pipe_type=None) routes to PipeSignatureSpec — omitting the- type IS the signature.- """- result = parse_pipe_spec(- {"pipe_code": "summarize_doc", "description": "Summarize a doc.", "inputs": {"doc": "Document"}, "output": "Text"},- pipe_type=None,- )- assert isinstance(result, PipeSignatureSpec)- assert result.to_blueprint().is_signature is True-- def test_typeless_spec_preserves_signature_for_hint(self) -> None:- result = parse_pipe_spec(- {"pipe_code": "x", "description": "d", "inputs": {"doc": "Text"}, "output": "Text", "signature_for": "PipeLLM"},- pipe_type=None,- )- assert isinstance(result, PipeSignatureSpec)- assert result.signature_for is PipeType.PIPE_LLM-- def test_explicit_signature_tag_rejected_with_migration_error(self) -> None:- """`PipeSignature` is no longer a selectable type: passing it is a migration error (never a- generic 'Invalid pipe type', and never routed through the spec-class map).- """- with pytest.raises(ValueError, match="is no longer a pipe type") as exc_info:- parse_pipe_spec(- {"pipe_code": "x", "description": "d", "inputs": {"doc": "Text"}, "output": "Text"},- pipe_type="PipeSignature",- )- assert "Invalid pipe type" not in str(exc_info.value)-- def test_typeless_spec_with_stray_field_raises_teaching_error(self) -> None:- with pytest.raises(ValueError, match="has no `type` but declares `prompt`"):- parse_pipe_spec(- {"pipe_code": "x", "description": "d", "inputs": {"doc": "Text"}, "output": "Text", "prompt": "do it"},- pipe_type=None,- )-- @pytest.mark.parametrize("alias", ["output_concept", "output_type"])- def test_typeless_spec_accepts_output_alias(self, alias: str) -> None:- """Output aliases are canonicalized before the typeless-signature contract check, so a signature- authored with `output_concept` / `output_type` is accepted — parity with typed pipes.- """- result = parse_pipe_spec(- {"pipe_code": "x", "description": "d", "inputs": {"doc": "Document"}, alias: "Article"},- pipe_type=None,- )- assert isinstance(result, PipeSignatureSpec)- assert result.output == "Article"-- def test_typeless_spec_accepts_dict_output(self) -> None:- """A dict-shaped output (`{"type": ...}`) is flattened before the contract check for a signature."""- result = parse_pipe_spec(- {"pipe_code": "x", "description": "d", "inputs": {"doc": "Document"}, "output": {"type": "Article"}},- pipe_type=None,- )- assert isinstance(result, PipeSignatureSpec)- assert result.output == "Article"-- def test_typeless_spec_stray_impl_field_still_rejected_after_output_normalization(self) -> None:- """Output normalization must not weaken the teaching error: a genuine implementation field on a- typeless spec still raises, naming the field.- """- with pytest.raises(ValueError, match="has no `type` but declares `model`"):- parse_pipe_spec(- {"pipe_code": "x", "description": "d", "inputs": {"doc": "Document"}, "output": "Article", "model": "gpt"},- pipe_type=None,- )-- # -- pipe_code aliases -------------------------------------------------- def test_canonical_pipe_code(self) -> None:- result = parse_pipe_spec({**_BASE_LLM}, pipe_type="PipeLLM")- assert result.pipe_code == "test_pipe"-- @pytest.mark.parametrize("alias", ["the_pipe_code", "code", "name", "pipe_name", "pipe_ref"])- def test_pipe_code_alias_accepted(self, alias: str) -> None:- spec = {key: val for key, val in _BASE_LLM.items() if key != "pipe_code"}- spec[alias] = "via_alias"- result = parse_pipe_spec(spec, pipe_type="PipeLLM")- assert result.pipe_code == "via_alias"-- def test_canonical_pipe_code_takes_precedence_over_alias(self) -> None:- """When pipe_code is present, aliases are ignored and cleaned up."""- spec = {**_BASE_LLM, "code": "alias_value", "name": "another_alias"}- result = parse_pipe_spec(spec, pipe_type="PipeLLM")- assert result.pipe_code == "test_pipe"-- def test_first_alias_wins_when_no_canonical(self) -> None:- """When multiple aliases are present without pipe_code, iteration order wins (the_pipe_code first)."""- spec = {key: val for key, val in _BASE_LLM.items() if key != "pipe_code"}- spec["code"] = "second"- spec["the_pipe_code"] = "first"- spec["name"] = "third"- result = parse_pipe_spec(spec, pipe_type="PipeLLM")- assert result.pipe_code == "first"-- # -- output dict tolerance ---------------------------------------------- def test_output_as_string(self) -> None:- result = parse_pipe_spec({**_BASE_LLM, "output": "Article"}, pipe_type="PipeLLM")- assert result.output == "Article"-- def test_output_dict_with_type_key(self) -> None:- result = parse_pipe_spec({**_BASE_LLM, "output": {"type": "Article"}}, pipe_type="PipeLLM")- assert result.output == "Article"-- def test_output_single_item_dict(self) -> None:- """A single-item dict is unambiguous — extract the value."""- result = parse_pipe_spec({**_BASE_LLM, "output": {"result": "Article"}}, pipe_type="PipeLLM")- assert result.output == "Article"-- def test_output_multi_item_dict_raises(self) -> None:- """A multi-item dict is ambiguous — validation fails."""- with pytest.raises(ValidationError):- parse_pipe_spec({**_BASE_LLM, "output": {"a": "Text", "b": "Image"}}, pipe_type="PipeLLM")-- def test_output_type_key_takes_precedence_in_dict(self) -> None:- """When 'type' key is present in output dict, it wins even if other keys exist."""- result = parse_pipe_spec({**_BASE_LLM, "output": {"type": "Article", "extra": "ignored"}}, pipe_type="PipeLLM")- assert result.output == "Article"-- # -- output field aliases ------------------------------------------------- @pytest.mark.parametrize("alias", ["output_concept", "output_type"])- def test_output_alias_accepted(self, alias: str) -> None:- """Each output alias resolves to the correct output value."""- spec = {key: val for key, val in _BASE_LLM.items() if key != "output"}- spec[alias] = "Article"- result = parse_pipe_spec(spec, pipe_type="PipeLLM")- assert result.output == "Article"-- @pytest.mark.parametrize("alias", ["output_concept", "output_type"])- def test_output_alias_tried_first_when_canonical_present(self, alias: str) -> None:- """When both output and an alias exist, alias value is tried first."""- spec = {**_BASE_LLM, alias: "AliasValue"}- result = parse_pipe_spec(spec, pipe_type="PipeLLM")- assert result.output == "AliasValue"-- def test_first_output_alias_wins(self) -> None:- """When multiple output aliases present without canonical, first in tuple order wins."""- spec = {key: val for key, val in _BASE_LLM.items() if key != "output"}- spec["output_type"] = "SecondAlias"- spec["output_concept"] = "FirstAlias"- result = parse_pipe_spec(spec, pipe_type="PipeLLM")- assert result.output == "FirstAlias"-- # -- prompt aliases ----------------------------------------------------- def test_prompt_template_alias_for_llm(self) -> None:- """`prompt_template` alone is promoted to `prompt` for PipeLLM."""- spec = {key: val for key, val in _BASE_LLM.items() if key != "prompt"}- spec["prompt_template"] = "Write about $text"- result = parse_pipe_spec(spec, pipe_type="PipeLLM")- assert isinstance(result, PipeLLMSpec)- assert result.prompt == "Write about $text"-- def test_canonical_prompt_takes_precedence_over_alias(self) -> None:- """When both `prompt` and `prompt_template` are present, canonical wins and alias is dropped."""- spec = {**_BASE_LLM, "prompt_template": "alias_value"}- result = parse_pipe_spec(spec, pipe_type="PipeLLM")- assert isinstance(result, PipeLLMSpec)- assert result.prompt == _BASE_LLM["prompt"]-- def test_prompt_template_alias_for_img_gen(self) -> None:- """`prompt_template` alias also works for PipeImgGen."""- spec: dict[str, Any] = {- "pipe_code": "my_img",- "description": "Generate image",- "inputs": {"prompt_text": "Text"},- "output": "Image",- "prompt_template": "Generate: $prompt_text",- }- result = parse_pipe_spec(spec, pipe_type="PipeImgGen")- assert isinstance(result, PipeImgGenSpec)- assert result.prompt == "Generate: $prompt_text"-- # -- steps/branches 'pipe' → 'pipe_code' alias ------------------------- def test_sequence_steps_canonical_pipe_code(self) -> None:- spec: dict[str, Any] = {- "pipe_code": "my_seq",- "description": "A sequence",- "inputs": {"doc": "Document"},- "output": "Text",- "steps": [{"pipe_code": "step_one", "result": "intermediate"}],- }- result = parse_pipe_spec(spec, pipe_type="PipeSequence")- assert isinstance(result, PipeSequenceSpec)- assert result.steps[0].pipe_code == "step_one"-- @pytest.mark.parametrize("alias", ["pipe", "pipe_ref", "the_pipe_code", "code", "name", "pipe_name"])- def test_sequence_steps_all_aliases(self, alias: str) -> None:- """All pipe_code aliases must work inside step dicts."""- spec: dict[str, Any] = {- "pipe_code": "my_seq",- "description": "A sequence",- "inputs": {"doc": "Document"},- "output": "Text",- "steps": [- {alias: "step_one", "result": "intermediate"},- {alias: "step_two", "result": "final"},- ],- }- result = parse_pipe_spec(spec, pipe_type="PipeSequence")- assert isinstance(result, PipeSequenceSpec)- assert result.steps[0].pipe_code == "step_one"- assert result.steps[1].pipe_code == "step_two"-- @pytest.mark.parametrize("alias", ["pipe", "pipe_ref", "the_pipe_code", "code", "name", "pipe_name"])- def test_parallel_branches_all_aliases(self, alias: str) -> None:- """All pipe_code aliases must work inside branch dicts."""- spec: dict[str, Any] = {- "pipe_code": "my_par",- "description": "Parallel branches",- "inputs": {"doc": "Document"},- "output": "Text",- "add_each_output": True,- "branches": [- {alias: "branch_a", "result": "result_a"},- {alias: "branch_b", "result": "result_b"},- ],- }- result = parse_pipe_spec(spec, pipe_type="PipeParallel")- assert isinstance(result, PipeParallelSpec)- assert result.branches[0].pipe_code == "branch_a"- assert result.branches[1].pipe_code == "branch_b"-- # -- extraneous "inputs" in steps/branches silently dropped ------------- def test_sequence_steps_extraneous_inputs_dropped(self) -> None:- """Agents sometimes add 'inputs' to individual steps; these should be silently ignored."""- spec: dict[str, Any] = {- "pipe_code": "interview_prep",- "description": "Analyze CV-job match",- "inputs": {"cv": "Document", "job_offer": "Document"},- "output": "Text",- "steps": [- {"pipe": "extract_cv", "inputs": {"cv": "cv"}, "result": "cv_pages"},- {"pipe": "extract_job_offer", "inputs": {"job_offer": "job_offer"}, "result": "job_offer_pages"},- {"pipe": "analyze_match", "result": "match_analysis"},- ],- }- result = parse_pipe_spec(spec, pipe_type="PipeSequence")- assert isinstance(result, PipeSequenceSpec)- assert result.steps[0].pipe_code == "extract_cv"- assert result.steps[1].pipe_code == "extract_job_offer"-- def test_parallel_branches_extraneous_inputs_dropped(self) -> None:- spec: dict[str, Any] = {- "pipe_code": "my_par",- "description": "Parallel branches",- "inputs": {"doc": "Document"},- "output": "Text",- "add_each_output": True,- "branches": [- {"pipe": "branch_a", "inputs": {"doc": "doc"}, "result": "result_a"},- ],- }- result = parse_pipe_spec(spec, pipe_type="PipeParallel")- assert isinstance(result, PipeParallelSpec)- assert result.branches[0].pipe_code == "branch_a"-- # -- malformed steps/branches shape (typed, not bare TypeError/ValueError) ---- @pytest.mark.parametrize("bad_steps", ["notalist", 42, {"a": "b"}])- def test_non_list_steps_raises_pipe_spec_error(self, bad_steps: Any) -> None:- """A non-list ``steps`` is a caller-input fault, surfaced as a typed PipeSpecError."""- spec: dict[str, Any] = {"pipe_code": "my_seq", "description": "d", "output": "Text", "steps": bad_steps}- with pytest.raises(PipeSpecError, match="'steps' must be a list of step mappings"):- parse_pipe_spec(spec, pipe_type="PipeSequence")-- @pytest.mark.parametrize("bad_entry", [42, "astring", [1, 2]])- def test_non_mapping_step_entry_raises_pipe_spec_error(self, bad_entry: Any) -> None:- """A step entry that is not a mapping is a typed input error, not a bare TypeError."""- spec: dict[str, Any] = {"pipe_code": "my_seq", "description": "d", "output": "Text", "steps": [bad_entry]}- with pytest.raises(PipeSpecError, match="entry in pipe spec 'steps' must be a mapping"):- parse_pipe_spec(spec, pipe_type="PipeSequence")-- @pytest.mark.parametrize("bad_branches", ["notalist", 42, {"a": "b"}])- def test_non_list_branches_raises_pipe_spec_error(self, bad_branches: Any) -> None:- spec: dict[str, Any] = {"pipe_code": "my_par", "description": "d", "output": "Text", "branches": bad_branches}- with pytest.raises(PipeSpecError, match="'branches' must be a list of step mappings"):- parse_pipe_spec(spec, pipe_type="PipeParallel")-- @pytest.mark.parametrize("bad_entry", [42, "astring", [1, 2]])- def test_non_mapping_branch_entry_raises_pipe_spec_error(self, bad_entry: Any) -> None:- spec: dict[str, Any] = {"pipe_code": "my_par", "description": "d", "output": "Text", "branches": [bad_entry]}- with pytest.raises(PipeSpecError, match="entry in pipe spec 'branches' must be a mapping"):- parse_pipe_spec(spec, pipe_type="PipeParallel")-- def test_malformed_steps_classifies_as_input_domain(self) -> None:- """The raised error carries the INPUT domain so HTTP consumers render it as a 422."""- spec: dict[str, Any] = {"pipe_code": "my_seq", "description": "d", "output": "Text", "steps": "notalist"}- with pytest.raises(PipeSpecError) as exc_info:- parse_pipe_spec(spec, pipe_type="PipeSequence")- assert error_domain_is_input(exc_info.value.error_domain)-- # -- malformed top-level shape (typed, not bare TypeError/ValueError) ---- @pytest.mark.parametrize("bad_spec", ["a string", ["a", "b"], 123, 3.14, None])- def test_non_mapping_top_level_raises_pipe_spec_error(self, bad_spec: Any) -> None:- """A non-mapping top-level spec leaks a bare TypeError/ValueError from dict() without the guard."""- with pytest.raises(PipeSpecError, match="must be a mapping"):- parse_pipe_spec(bad_spec, pipe_type="PipeLLM")-- def test_non_mapping_top_level_classifies_as_input_domain(self) -> None:- with pytest.raises(PipeSpecError) as exc_info:- parse_pipe_spec("not a mapping", pipe_type="PipeLLM")- assert error_domain_is_input(exc_info.value.error_domain)-- # -- PipeCondition expression alias ------------------------------------- _BASE_CONDITION: ClassVar[dict[str, Any]] = {- "pipe_code": "my_cond",- "description": "Route by status",- "inputs": {"status": "Text"},- "output": "Text",- "outcomes": {"high": "handle_high", "low": "handle_low"},- "default_outcome": "handle_default",- }-- def test_condition_expression_alias(self) -> None:- spec = {**self._BASE_CONDITION, "expression": "{{ status }}"}- result = parse_pipe_spec(spec, pipe_type="PipeCondition")- assert isinstance(result, PipeConditionSpec)- assert result.jinja2_expression_template == "{{ status }}"-- def test_condition_canonical_jinja2_field(self) -> None:- spec = {**self._BASE_CONDITION, "jinja2_expression_template": "{{ status }}"}- result = parse_pipe_spec(spec, pipe_type="PipeCondition")- assert isinstance(result, PipeConditionSpec)- assert result.jinja2_expression_template == "{{ status }}"-- def test_condition_canonical_takes_precedence(self) -> None:- spec = {**self._BASE_CONDITION, "jinja2_expression_template": "{{ canonical }}", "expression": "{{ alias }}"}- result = parse_pipe_spec(spec, pipe_type="PipeCondition")- assert isinstance(result, PipeConditionSpec)- assert result.jinja2_expression_template == "{{ canonical }}"-- # -- does not mutate caller's dict -------------------------------------- def test_original_dict_unchanged(self) -> None:- original: dict[str, Any] = {- "code": "my_pipe",- "description": "Test",- "model": "$writing-creative",- "inputs": {"text": "Text"},- "output": "Text",- "prompt": "Write about $text",- }- snapshot = dict(original)- parse_pipe_spec(original, pipe_type="PipeLLM")- assert original == snapshot-- def test_nested_step_dicts_not_mutated(self) -> None:- step = {"pipe": "step_one", "result": "intermediate"}- spec: dict[str, Any] = {- "pipe_code": "my_seq",- "description": "A sequence",- "inputs": {"doc": "Document"},- "output": "Text",- "steps": [step],- }- step_snapshot = dict(step)- parse_pipe_spec(spec, pipe_type="PipeSequence")- assert step == step_snapshot-- # -- returns correct subclass ------------------------------------------- @pytest.mark.parametrize(- ("pipe_type", "spec_data", "expected_class"),- [- (- "PipeLLM",- {**_BASE_LLM},- PipeLLMSpec,- ),- (- "PipeFunc",- {"pipe_code": "my_func", "description": "A function", "inputs": {"data": "Text"}, "output": "Text", "function_name": "process_data"},- PipeFuncSpec,- ),- (- "PipeImgGen",- {- "pipe_code": "my_img",- "description": "Generate image",- "inputs": {"prompt_text": "Text"},- "output": "Image",- "prompt": "Generate: $prompt_text",- },- PipeImgGenSpec,- ),- (- "PipeExtract",- {"pipe_code": "my_extract", "description": "Extract text", "inputs": {"doc": "Document"}, "output": "Page[]"},- PipeExtractSpec,- ),- (- "PipeSearch",- {- "pipe_code": "my_search",- "description": "Search the web",- "inputs": {"query_text": "Text"},- "output": "Text",- "prompt": "Search for $query_text",- },- PipeSearchSpec,- ),- (- "PipeJudge",- {- "pipe_code": "is_urgent",- "description": "Judge urgency",- "inputs": {"message": "Text"},- "output": "YesNo",- "prompt": "Is the message urgent?",- },- PipeJudgeSpec,- ),- (- "PipeBatch",- {- "pipe_code": "my_batch",- "description": "Batch process",- "inputs": {"items": "Text[]"},- "output": "Text[]",- "branch_pipe_code": "process_one",- "input_list_name": "items",- "input_item_name": "item",- },- PipeBatchSpec,- ),- ],- )- def test_correct_subclass(self, pipe_type: str, spec_data: dict[str, Any], expected_class: type) -> None:- result = parse_pipe_spec(spec_data, pipe_type=pipe_type)- assert isinstance(result, expected_class)-- @pytest.mark.parametrize("question_key", ["question", "prompt"])- def test_judge_reads_prompt_as_question(self, question_key: str) -> None:- spec = parse_pipe_spec(- {"pipe_code": "is_urgent", "description": "Judge", "inputs": {"message": "Text"}, "output": "YesNo", question_key: "Is it urgent?"},- pipe_type="PipeJudge",- )- assert isinstance(spec, PipeJudgeSpec)- assert spec.question == "Is it urgent?"-- def test_judge_refuses_both_spellings_and_leaves_the_callers_dict_alone(self) -> None:- spec_data: dict[str, Any] = {- "pipe_code": "is_urgent",- "description": "Judge",- "inputs": {"message": "Text"},- "output": "YesNo",- "question": "Is it urgent?",- "prompt": "Is it urgent now?",- }- with pytest.raises(ValidationError, match="but not both"):- PipeJudgeSpec.model_validate(spec_data)- assert spec_data["prompt"] == "Is it urgent now?"-- def test_judge_reading_the_synonym_leaves_the_callers_dict_alone(self) -> None:- spec_data: dict[str, Any] = {- "pipe_code": "is_urgent",- "description": "Judge",- "inputs": {"message": "Text"},- "output": "YesNo",- "prompt": "Is it urgent?",- }- spec = PipeJudgeSpec.model_validate(spec_data)- assert spec.question == "Is it urgent?"- assert spec_data == {- "pipe_code": "is_urgent",- "description": "Judge",- "inputs": {"message": "Text"},- "output": "YesNo",- "prompt": "Is it urgent?",- }diff --git a/tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py b/tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.pydeleted file mode 100644index ab1e92465..000000000--- a/tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py+++ /dev/null@@ -1,587 +0,0 @@-"""Unit tests for pipe_spec_to_toml from pipelex.builder.operations.pipe_ops."""--from __future__ import annotations--from pipelex.builder.operations.pipe_ops import parse_pipe_spec, pipe_spec_to_toml-from tests.unit.pipelex.builder.operations.test_data import PipeOpsTestData--_BASE_LLM = PipeOpsTestData.BASE_LLM_SPEC---class TestPipeSpecToToml:- """Comprehensive tests for pipe_spec_to_toml covering all pipe types."""-- # -- PipeSignature (typeless) ------------------------------------------- def test_signature_toml_has_no_type_line(self) -> None:- """A signature renders as a typeless `[pipe.x]` section — no `type` line, since omitting the- type IS the signature — so it re-parses as a signature (an explicit `type = "PipeSignature"`- would now be rejected).- """- spec = parse_pipe_spec(- {"pipe_code": "summarize_doc", "description": "Summarize a doc.", "inputs": {"doc": "Document"}, "output": "Text"},- pipe_type=None,- )- toml = pipe_spec_to_toml(spec)- assert "[pipe.summarize_doc]" in toml- assert "type =" not in toml- assert 'description = "Summarize a doc."' in toml- assert 'output = "Text"' in toml-- def test_signature_toml_preserves_signature_for_hint(self) -> None:- """The optional `signature_for` hint round-trips (guards against renderer drift with the- agent-CLI `_pipe_spec_to_toml`, which also emits it).- """- spec = parse_pipe_spec(- {"pipe_code": "x", "description": "d", "inputs": {"doc": "Text"}, "output": "Text", "signature_for": "PipeLLM"},- pipe_type=None,- )- toml = pipe_spec_to_toml(spec)- assert "type =" not in toml- assert 'signature_for = "PipeLLM"' in toml-- # -- PipeLLM ------------------------------------------------------------ def test_llm_basic_structure(self) -> None:- spec = parse_pipe_spec({**_BASE_LLM}, pipe_type="PipeLLM")- toml = pipe_spec_to_toml(spec)- assert "[pipe.test_pipe]" in toml- assert 'type = "PipeLLM"' in toml- assert 'description = "Test LLM pipe"' in toml- assert 'output = "Text"' in toml-- def test_llm_inputs_as_inline_table(self) -> None:- spec = parse_pipe_spec({**_BASE_LLM}, pipe_type="PipeLLM")- toml = pipe_spec_to_toml(spec)- assert 'inputs = {text = "Text"}' in toml-- def test_llm_model_in_toml(self) -> None:- spec = parse_pipe_spec({**_BASE_LLM}, pipe_type="PipeLLM")- toml = pipe_spec_to_toml(spec)- assert 'model = "$writing-creative"' in toml-- def test_llm_no_model_omits_field(self) -> None:- data = {key: val for key, val in _BASE_LLM.items() if key != "model"}- spec = parse_pipe_spec(data, pipe_type="PipeLLM")- toml = pipe_spec_to_toml(spec)- assert "model" not in toml-- def test_llm_system_prompt_in_toml(self) -> None:- spec = parse_pipe_spec({**_BASE_LLM, "system_prompt": "You are a helpful writer."}, pipe_type="PipeLLM")- toml = pipe_spec_to_toml(spec)- assert "system_prompt" in toml- assert "You are a helpful writer." in toml-- def test_llm_prompt_in_toml(self) -> None:- spec = parse_pipe_spec({**_BASE_LLM}, pipe_type="PipeLLM")- toml = pipe_spec_to_toml(spec)- assert "prompt" in toml- assert "Write about $text" in toml-- def test_llm_no_inputs_omits_inputs(self) -> None:- empty_inputs: dict[str, str] = {}- data = {**_BASE_LLM, "inputs": empty_inputs}- spec = parse_pipe_spec(data, pipe_type="PipeLLM")- toml = pipe_spec_to_toml(spec)- assert "inputs" not in toml-- def test_llm_multiple_inputs(self) -> None:- data = {**_BASE_LLM, "inputs": {"text": "Text", "context": "Document"}}- spec = parse_pipe_spec(data, pipe_type="PipeLLM")- toml = pipe_spec_to_toml(spec)- assert 'text = "Text"' in toml- assert 'context = "Document"' in toml-- def test_llm_structuring_method_preliminary_text_in_toml(self) -> None:- spec = parse_pipe_spec({**_BASE_LLM, "structuring_method": "preliminary_text"}, pipe_type="PipeLLM")- toml = pipe_spec_to_toml(spec)- assert 'structuring_method = "preliminary_text"' in toml-- def test_llm_structuring_method_direct_in_toml(self) -> None:- spec = parse_pipe_spec({**_BASE_LLM, "structuring_method": "direct"}, pipe_type="PipeLLM")- toml = pipe_spec_to_toml(spec)- assert 'structuring_method = "direct"' in toml-- def test_llm_no_structuring_method_omits_field(self) -> None:- spec = parse_pipe_spec({**_BASE_LLM}, pipe_type="PipeLLM")- toml = pipe_spec_to_toml(spec)- assert "structuring_method" not in toml-- # -- PipeStructure ------------------------------------------------------ def test_structure_basic_structure(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "structure_review",- "description": "Structure a review",- "inputs": {"draft_text": "Text"},- "output": "RestaurantReview",- },- pipe_type="PipeStructure",- )- toml = pipe_spec_to_toml(spec)- assert "[pipe.structure_review]" in toml- assert 'type = "PipeStructure"' in toml- assert 'description = "Structure a review"' in toml- assert 'output = "RestaurantReview"' in toml-- def test_structure_model_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "structure_review",- "description": "Structure a review",- "inputs": {"draft_text": "Text"},- "output": "RestaurantReview",- "model": "$structuring-fast",- },- pipe_type="PipeStructure",- )- toml = pipe_spec_to_toml(spec)- assert 'model = "$structuring-fast"' in toml-- def test_structure_no_model_omits_field(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "structure_review",- "description": "Structure a review",- "inputs": {"draft_text": "Text"},- "output": "RestaurantReview",- },- pipe_type="PipeStructure",- )- toml = pipe_spec_to_toml(spec)- assert "model" not in toml- assert 'type = "PipeStructure"' in toml-- # -- PipeFunc ----------------------------------------------------------- def test_func_function_name_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "my_func",- "description": "Run a function",- "inputs": {"data": "Text"},- "output": "Text",- "function_name": "process_data",- },- pipe_type="PipeFunc",- )- toml = pipe_spec_to_toml(spec)- assert 'function_name = "process_data"' in toml- assert 'type = "PipeFunc"' in toml-- # -- PipeImgGen --------------------------------------------------------- def test_img_gen_model_and_prompt_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "gen_image",- "description": "Generate image",- "inputs": {"prompt_text": "Text"},- "output": "Image",- "model": "$gen-image",- "prompt": "Generate: $prompt_text",- },- pipe_type="PipeImgGen",- )- toml = pipe_spec_to_toml(spec)- assert 'model = "$gen-image"' in toml- assert "Generate: $prompt_text" in toml-- def test_img_gen_no_model_omits_field(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "gen_image",- "description": "Generate image",- "inputs": {"prompt_text": "Text"},- "output": "Image",- "prompt": "Generate: $prompt_text",- },- pipe_type="PipeImgGen",- )- toml = pipe_spec_to_toml(spec)- assert "model" not in toml-- # -- PipeDocGen --------------------------------------------------------- def test_doc_gen_model_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "print_invoice",- "description": "Print the invoice",- "inputs": {"invoice": "Invoice"},- "output": "Document",- "format": "docx",- "model": "pipelex-docx",- "template_file": "invoice.docx",- "filename": "invoice.docx",- },- pipe_type="PipeDocGen",- )- toml = pipe_spec_to_toml(spec)- assert 'format = "docx"' in toml- assert 'model = "pipelex-docx"' in toml- assert 'template_file = "invoice.docx"' in toml- assert 'filename = "invoice.docx"' in toml-- def test_doc_gen_no_model_omits_field(self) -> None:- spec = parse_pipe_spec(- {"pipe_code": "print_report", "description": "Print the report", "inputs": {"report": "Markdown"}, "output": "Document", "format": "pdf"},- pipe_type="PipeDocGen",- )- toml = pipe_spec_to_toml(spec)- assert "model" not in toml-- # -- PipeExtract -------------------------------------------------------- def test_extract_model_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "my_extract",- "description": "Extract text",- "inputs": {"doc": "Document"},- "output": "Page[]",- "model": "@default-extract-document",- },- pipe_type="PipeExtract",- )- toml = pipe_spec_to_toml(spec)- assert 'model = "@default-extract-document"' in toml-- def test_extract_max_page_images_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "my_extract",- "description": "Extract text",- "inputs": {"doc": "Document"},- "output": "Page[]",- "max_page_images": 5,- },- pipe_type="PipeExtract",- )- toml = pipe_spec_to_toml(spec)- assert "max_page_images = 5" in toml-- def test_extract_page_views_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "my_extract",- "description": "Extract text",- "inputs": {"doc": "Document"},- "output": "Page[]",- "page_views": True,- },- pipe_type="PipeExtract",- )- toml = pipe_spec_to_toml(spec)- assert "page_views = true" in toml-- def test_extract_no_optional_fields_omits_them(self) -> None:- spec = parse_pipe_spec(- {"pipe_code": "my_extract", "description": "Extract text", "inputs": {"doc": "Document"}, "output": "Page[]"}, pipe_type="PipeExtract"- )- toml = pipe_spec_to_toml(spec)- assert "model" not in toml- assert "max_page_images" not in toml- assert "page_views" not in toml-- # -- PipeSearch --------------------------------------------------------- def test_search_all_fields_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "web_search",- "description": "Search the web",- "inputs": {"query_text": "Text"},- "output": "Text",- "model": "$search-model",- "prompt": "Search for $query_text",- "from_date": "2024-01-01",- "to_date": "2024-12-31",- "include_domains": ["example.com", "docs.example.com"],- "exclude_domains": ["spam.com"],- "max_results": 10,- },- pipe_type="PipeSearch",- )- toml = pipe_spec_to_toml(spec)- assert 'model = "$search-model"' in toml- assert "Search for $query_text" in toml- assert 'from_date = "2024-01-01"' in toml- assert 'to_date = "2024-12-31"' in toml- assert "example.com" in toml- assert "spam.com" in toml- assert "max_results = 10" in toml-- def test_search_minimal(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "web_search",- "description": "Search",- "inputs": {"query_text": "Text"},- "output": "Text",- "prompt": "Find $query_text",- },- pipe_type="PipeSearch",- )- toml = pipe_spec_to_toml(spec)- assert "Find $query_text" in toml- assert "from_date" not in toml- assert "to_date" not in toml- assert "include_domains" not in toml- assert "exclude_domains" not in toml- assert "max_results" not in toml- assert "model" not in toml-- # -- PipeSequence ------------------------------------------------------- def test_sequence_steps_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "my_seq",- "description": "A sequence",- "inputs": {"doc": "Document"},- "output": "Text",- "steps": [- {"pipe_code": "step_one", "result": "intermediate"},- {"pipe_code": "step_two", "result": "final"},- ],- },- pipe_type="PipeSequence",- )- toml = pipe_spec_to_toml(spec)- assert 'type = "PipeSequence"' in toml- assert "step_one" in toml- assert "step_two" in toml- assert "intermediate" in toml- assert "final" in toml-- def test_sequence_step_with_batch_over(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "my_seq",- "description": "A sequence with batch",- "inputs": {"items": "Text[]"},- "output": "Text[]",- "steps": [- {"pipe_code": "process", "result": "processed", "batch_over": "items", "batch_as": "item"},- ],- },- pipe_type="PipeSequence",- )- toml = pipe_spec_to_toml(spec)- assert "batch_over" in toml- assert "batch_as" in toml- assert "items" in toml-- # -- PipeParallel ------------------------------------------------------- def test_parallel_branches_and_add_each_output(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "my_par",- "description": "Parallel branches",- "inputs": {"doc": "Document"},- "output": "Composite",- "add_each_output": True,- "branches": [- {"pipe_code": "branch_a", "result": "result_a"},- {"pipe_code": "branch_b", "result": "result_b"},- ],- },- pipe_type="PipeParallel",- )- toml = pipe_spec_to_toml(spec)- assert 'type = "PipeParallel"' in toml- assert "add_each_output = true" in toml- assert "branch_a" in toml- assert "branch_b" in toml- assert "combined_output" not in toml-- # -- PipeCondition ------------------------------------------------------ def test_condition_expression_outcomes_default(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "my_cond",- "description": "Route by status",- "inputs": {"status": "Text"},- "output": "Text",- "jinja2_expression_template": "{{ status }}",- "outcomes": {"high": "handle_high", "low": "handle_low"},- "default_outcome": "handle_default",- },- pipe_type="PipeCondition",- )- toml = pipe_spec_to_toml(spec)- assert 'type = "PipeCondition"' in toml- assert "{{ status }}" in toml- assert "handle_high" in toml- assert "handle_low" in toml- assert 'default_outcome = "handle_default"' in toml-- # -- PipeBatch ---------------------------------------------------------- def test_batch_fields_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "my_batch",- "description": "Batch process",- "inputs": {"items": "Text[]"},- "output": "Text[]",- "branch_pipe_code": "process_one",- "input_list_name": "items",- "input_item_name": "item",- },- pipe_type="PipeBatch",- )- toml = pipe_spec_to_toml(spec)- assert 'type = "PipeBatch"' in toml- assert 'branch_pipe_code = "process_one"' in toml- assert 'input_list_name = "items"' in toml- assert 'input_item_name = "item"' in toml-- # -- PipeCompose (template mode) ---------------------------------------- def test_compose_template_mode_fields(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "render_greeting",- "description": "Render a greeting",- "inputs": {"name": "native.Text"},- "output": "native.Text",- "target_format": "markdown",- "template": "Hello $name!",- },- pipe_type="PipeCompose",- )- toml = pipe_spec_to_toml(spec)- assert 'type = "PipeCompose"' in toml- assert 'target_format = "markdown"' in toml- assert 'template = "Hello $name!"' in toml-- def test_compose_no_construct_in_template_mode(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "render_greeting",- "description": "Render a greeting",- "inputs": {"name": "native.Text"},- "output": "native.Text",- "target_format": "markdown",- "template": "Hello $name!",- },- pipe_type="PipeCompose",- )- toml = pipe_spec_to_toml(spec)- assert "construct" not in toml-- # -- PipeCompose (construct mode) --------------------------------------- def test_compose_construct_with_from_mappings(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "compose_sheet",- "description": "Compose interview sheet",- "inputs": {"analysis": "MatchAnalysis", "questions": "InterviewQuestion[]"},- "output": "InterviewSheet",- "construct": {- "score": {"from": "analysis.overall_score"},- "questions": {"from": "questions"},- },- },- pipe_type="PipeCompose",- )- toml = pipe_spec_to_toml(spec)- assert "[pipe.compose_sheet.construct]" in toml- assert 'score = {from = "analysis.overall_score"}' in toml-- def test_compose_construct_with_static_values(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "compose_report",- "description": "Compose a report",- "inputs": {"title": "native.Text"},- "output": "Report",- "construct": {- "title": {"from": "title"},- "version": "1.0",- "page_count": 42,- },- },- pipe_type="PipeCompose",- )- toml = pipe_spec_to_toml(spec)- assert 'version = "1.0"' in toml- assert "page_count = 42" in toml-- def test_compose_no_template_in_construct_mode(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "compose_report",- "description": "Compose a report",- "inputs": {"title": "native.Text"},- "output": "Report",- "construct": {"title": {"from": "title"}},- },- pipe_type="PipeCompose",- )- toml = pipe_spec_to_toml(spec)- assert "target_format" not in toml- assert "template" not in toml-- # -- PipeJudge ---------------------------------------------------------- def test_judge_choice_writes_question_and_options(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "route_ticket",- "description": "Route a ticket",- "inputs": {"ticket": "Text"},- "output": "Choice",- "model": "@default-judgment",- "prompt": "Which team should handle the ticket?",- "options": {"billing": "Charges and invoices", "other": ""},- },- pipe_type="PipeJudge",- )- toml = pipe_spec_to_toml(spec)- assert 'question = "Which team should handle the ticket?"' in toml- assert "prompt" not in toml, "A tool that writes a PipeJudge writes `question`"- assert 'model = "@default-judgment"' in toml- assert 'billing = "Charges and invoices"' in toml- assert 'other = ""' in toml-- def test_judge_yes_no_writes_criteria_and_threshold(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "is_urgent",- "description": "Judge urgency",- "inputs": {"message": "Text"},- "output": "YesNo",- "question": "Is the message urgent?",- "criteria": {"yes": "Needs an answer today"},- "threshold": 0.8,- },- pipe_type="PipeJudge",- )- toml = pipe_spec_to_toml(spec)- assert 'yes = "Needs an answer today"' in toml- assert "no =" not in toml- assert "threshold = 0.8" in toml-- def test_judge_rating_writes_levels(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "rate_severity",- "description": "Rate severity",- "inputs": {"report": "Text"},- "output": "Rating",- "question": "How severe is it?",- "levels": ["Cosmetic", "A workaround exists", "Blocking"],- },- pipe_type="PipeJudge",- )- toml = pipe_spec_to_toml(spec)- assert "Cosmetic" in toml- assert "Blocking" in toml- assert "options" not in tomldiff --git a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_batch/test_data.py b/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_batch/test_data.pydeleted file mode 100644index 646080209..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_batch/test_data.py+++ /dev/null@@ -1,31 +0,0 @@-from typing import ClassVar--from pipelex.builder.pipe.pipe_batch_spec import PipeBatchSpec-from pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprint---class PipeBatchTestCases:- BATCH_WITH_NAMES = (- "batch_with_names",- PipeBatchSpec(- pipe_code="named_batch",- description="Batch with custom names",- inputs={"widgets": "Widget[]"},- output="Results",- branch_pipe_code="transform_data",- input_list_name="widgets",- input_item_name="widget",- ),- PipeBatchBlueprint(- description="Batch with custom names",- inputs={"widgets": "Widget[]"},- output="Results",- branch_pipe_code="transform_data",- input_list_name="widgets",- input_item_name="widget",- ),- )-- TEST_CASES: ClassVar[list[tuple[str, PipeBatchSpec, PipeBatchBlueprint]]] = [- BATCH_WITH_NAMES,- ]diff --git a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_batch/test_pipe_batch.py b/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_batch/test_pipe_batch.pydeleted file mode 100644index ebec38bd7..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_batch/test_pipe_batch.py+++ /dev/null@@ -1,47 +0,0 @@-import pytest-from pydantic import ValidationError--from pipelex.builder.pipe.pipe_batch_spec import PipeBatchSpec-from pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprint-from tests.unit.pipelex.builder.pipe.pipe_controller.pipe_batch.test_data import PipeBatchTestCases---class TestPipeBatchBlueprintConversion:- @pytest.mark.parametrize(- ("test_name", "pipe_spec", "expected_blueprint"),- PipeBatchTestCases.TEST_CASES,- )- def test_pipe_batch_spec_to_blueprint(- self,- test_name: str, # ruff: ignore[unused-method-argument]- pipe_spec: PipeBatchSpec,- expected_blueprint: PipeBatchBlueprint,- ):- result = pipe_spec.to_blueprint()- assert result == expected_blueprint-- def test_rejects_input_item_name_same_as_input_list_name(self):- """Spec-level validation rejects input_item_name == input_list_name."""- with pytest.raises(ValidationError, match="input_item_name"):- PipeBatchSpec(- pipe_code="batch_items",- description="Batch with collision",- inputs={"items": "Item[]"},- output="Result[]",- branch_pipe_code="process_item",- input_list_name="items",- input_item_name="items",- )-- def test_rejects_input_item_name_same_as_inputs_key(self):- """Spec-level validation rejects input_item_name that shadows an inputs key."""- with pytest.raises(ValidationError, match="input_item_name"):- PipeBatchSpec(- pipe_code="batch_items",- description="Batch with collision",- inputs={"items": "Item[]", "context": "Text"},- output="Result[]",- branch_pipe_code="process_item",- input_list_name="items",- input_item_name="context",- )diff --git a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_condition/test_data.py b/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_condition/test_data.pydeleted file mode 100644index 5a8f41e82..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_condition/test_data.py+++ /dev/null@@ -1,41 +0,0 @@-from typing import ClassVar--from pipelex.builder.pipe.pipe_condition_spec import PipeConditionSpec-from pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprint---class PipeConditionTestCases:- CONDITION_WITH_TEMPLATE = (- "condition_with_template",- PipeConditionSpec(- pipe_code="template_condition",- description="Conditional with template",- inputs={"item": "Item"},- output="native.Anything",- jinja2_expression_template="{{ item.category }}",- outcomes={- "A": "process_a",- "B": "process_b",- "C": "process_c",- },- default_outcome="process_default",- ),- PipeConditionBlueprint(- description="Conditional with template",- inputs={"item": "Item"},- output="native.Anything",- expression=None,- expression_template="{{ item.category }}",- outcomes={- "A": "process_a",- "B": "process_b",- "C": "process_c",- },- default_outcome="process_default",- add_alias_from_expression_to=None,- ),- )-- TEST_CASES: ClassVar[list[tuple[str, PipeConditionSpec, PipeConditionBlueprint]]] = [- CONDITION_WITH_TEMPLATE,- ]diff --git a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_condition/test_pipe_condition.py b/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_condition/test_pipe_condition.pydeleted file mode 100644index 82a301cf4..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_condition/test_pipe_condition.py+++ /dev/null@@ -1,20 +0,0 @@-import pytest--from pipelex.builder.pipe.pipe_condition_spec import PipeConditionSpec-from pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprint-from tests.unit.pipelex.builder.pipe.pipe_controller.pipe_condition.test_data import PipeConditionTestCases---class TestPipeConditionBlueprintConversion:- @pytest.mark.parametrize(- ("test_name", "pipe_spec", "expected_blueprint"),- PipeConditionTestCases.TEST_CASES,- )- def test_pipe_condition_spec_to_blueprint(- self,- test_name: str, # ruff: ignore[unused-method-argument]- pipe_spec: PipeConditionSpec,- expected_blueprint: PipeConditionBlueprint,- ):- result = pipe_spec.to_blueprint()- assert result == expected_blueprintdiff --git a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_parallel/test_data.py b/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_parallel/test_data.pydeleted file mode 100644index 358b972e7..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_parallel/test_data.py+++ /dev/null@@ -1,93 +0,0 @@-from typing import ClassVar--from pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpec-from pipelex.builder.pipe.sub_pipe_spec import SubPipeSpec-from pipelex.pipe_controllers.parallel.pipe_parallel_blueprint import PipeParallelBlueprint-from pipelex.pipe_controllers.sub_pipe_blueprint import SubPipeBlueprint---class PipeParallelTestCases:- PARALLEL_WITH_EACH_OUTPUT = (- "parallel_with_each_output",- PipeParallelSpec(- pipe_code="parallel_processor",- description="Run pipes in parallel",- inputs={"data": "Data"},- output="Results",- branches=[- SubPipeSpec(pipe_code="analyze_data", result="analysis"),- SubPipeSpec(pipe_code="transform_data", result="transformed"),- SubPipeSpec(pipe_code="validate_data", result="validation"),- ],- add_each_output=True,- ),- PipeParallelBlueprint(- description="Run pipes in parallel",- inputs={"data": "Data"},- output="Results",- branches=[- SubPipeBlueprint(pipe="analyze_data", result="analysis"),- SubPipeBlueprint(pipe="transform_data", result="transformed"),- SubPipeBlueprint(pipe="validate_data", result="validation"),- ],- add_each_output=True,- source="tests/unit/pipelex/libraries/pipelines/builder/pipe/pipe_controllers/pipe_parallel/test_data.py PipeParallelTestCases.PARALLEL_WITH_EACH_OUTPUT", # ruff: ignore[line-too-long]- ),- )-- PARALLEL_WITHOUT_EACH_OUTPUT = (- "parallel_without_each_output",- PipeParallelSpec(- pipe_code="combined_parallel",- description="Parallel combining into its declared output only",- inputs={"input": "Input"},- output="CombinedResult",- branches=[- SubPipeSpec(pipe_code="pipe1", result="result1"),- SubPipeSpec(pipe_code="pipe2", result="result2"),- ],- add_each_output=False,- ),- PipeParallelBlueprint(- description="Parallel combining into its declared output only",- inputs={"input": "Input"},- output="CombinedResult",- branches=[- SubPipeBlueprint(pipe="pipe1", result="result1"),- SubPipeBlueprint(pipe="pipe2", result="result2"),- ],- add_each_output=False,- source="tests/unit/pipelex/libraries/pipelines/builder/pipe/pipe_controllers/pipe_parallel/test_data.py PipeParallelTestCases.PARALLEL_WITHOUT_EACH_OUTPUT", # ruff: ignore[line-too-long]- ),- )-- PARALLEL_OMITTING_ADD_EACH_OUTPUT = (- "parallel_omitting_add_each_output",- PipeParallelSpec(- pipe_code="plain_combined_parallel",- description="Always-combine parallel omitting add_each_output entirely",- inputs={"input": "Input"},- output="CombinedResult",- branches=[- SubPipeSpec(pipe_code="pipe1", result="result1"),- SubPipeSpec(pipe_code="pipe2", result="result2"),- ],- ),- PipeParallelBlueprint(- description="Always-combine parallel omitting add_each_output entirely",- inputs={"input": "Input"},- output="CombinedResult",- branches=[- SubPipeBlueprint(pipe="pipe1", result="result1"),- SubPipeBlueprint(pipe="pipe2", result="result2"),- ],- add_each_output=False,- source="tests/unit/pipelex/libraries/pipelines/builder/pipe/pipe_controllers/pipe_parallel/test_data.py PipeParallelTestCases.PARALLEL_OMITTING_ADD_EACH_OUTPUT", # ruff: ignore[line-too-long]- ),- )-- TEST_CASES: ClassVar[list[tuple[str, PipeParallelSpec, PipeParallelBlueprint]]] = [- PARALLEL_WITH_EACH_OUTPUT,- PARALLEL_WITHOUT_EACH_OUTPUT,- PARALLEL_OMITTING_ADD_EACH_OUTPUT,- ]diff --git a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_parallel/test_pipe_parallel.py b/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_parallel/test_pipe_parallel.pydeleted file mode 100644index 23750cb39..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_parallel/test_pipe_parallel.py+++ /dev/null@@ -1,23 +0,0 @@-import pytest--from pipelex import log-from pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpec-from pipelex.pipe_controllers.parallel.pipe_parallel_blueprint import PipeParallelBlueprint-from tests.unit.pipelex.builder.pipe.pipe_controller.pipe_parallel.test_data import PipeParallelTestCases---class TestPipeParallelBlueprintConversion:- @pytest.mark.parametrize(- ("test_name", "pipe_spec", "expected_blueprint"),- PipeParallelTestCases.TEST_CASES,- )- def test_pipe_parallel_spec_to_blueprint(- self,- test_name: str,- pipe_spec: PipeParallelSpec,- expected_blueprint: PipeParallelBlueprint,- ):- log.verbose(f"Testing {test_name}")- result = pipe_spec.to_blueprint()- expected_blueprint.source = None- assert result == expected_blueprintdiff --git a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_sequence/test_data.py b/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_sequence/test_data.pydeleted file mode 100644index 9445d735d..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_sequence/test_data.py+++ /dev/null@@ -1,61 +0,0 @@-from typing import ClassVar--from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.builder.pipe.sub_pipe_spec import SubPipeSpec-from pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint-from pipelex.pipe_controllers.sub_pipe_blueprint import SubPipeBlueprint---class PipeSequenceTestCases:- SIMPLE_SEQUENCE = (- "simple_sequence",- PipeSequenceSpec(- pipe_code="sequence_processor",- description="A sequence of operations",- inputs={"input_data": "Text"},- output="ProcessedData",- steps=[- SubPipeSpec(pipe_code="step1", result="result1"),- SubPipeSpec(pipe_code="step2", result="result2"),- SubPipeSpec(pipe_code="step3", result="final_result"),- ],- ),- PipeSequenceBlueprint(- description="A sequence of operations",- inputs={"input_data": "Text"},- output="ProcessedData",- steps=[- SubPipeBlueprint(pipe="step1", result="result1"),- SubPipeBlueprint(pipe="step2", result="result2"),- SubPipeBlueprint(pipe="step3", result="final_result"),- ],- ),- )-- SEQUENCE_WITH_BATCH_STEP = (- "sequence_with_batch_step",- PipeSequenceSpec(- pipe_code="batch_sequence",- description="A sequence with a batch step",- inputs={"items": "Text[]"},- output="Summary",- steps=[- SubPipeSpec(pipe_code="process_item", result="processed_items", batch_over="items", batch_as="item"),- SubPipeSpec(pipe_code="summarize", result="summary"),- ],- ),- PipeSequenceBlueprint(- description="A sequence with a batch step",- inputs={"items": "Text[]"},- output="Summary",- steps=[- SubPipeBlueprint(pipe="process_item", result="processed_items", batch_over="items", batch_as="item"),- SubPipeBlueprint(pipe="summarize", result="summary"),- ],- ),- )-- TEST_CASES: ClassVar[list[tuple[str, PipeSequenceSpec, PipeSequenceBlueprint]]] = [- SIMPLE_SEQUENCE,- SEQUENCE_WITH_BATCH_STEP,- ]diff --git a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_sequence/test_pipe_sequence.py b/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_sequence/test_pipe_sequence.pydeleted file mode 100644index 3f80e9c2f..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_controller/pipe_sequence/test_pipe_sequence.py+++ /dev/null@@ -1,20 +0,0 @@-import pytest--from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint-from tests.unit.pipelex.builder.pipe.pipe_controller.pipe_sequence.test_data import PipeSequenceTestCases---class TestPipeSequenceBlueprintConversion:- @pytest.mark.parametrize(- ("test_name", "pipe_spec", "expected_blueprint"),- PipeSequenceTestCases.TEST_CASES,- )- def test_pipe_sequence_spec_to_blueprint(- self,- test_name: str, # ruff: ignore[unused-method-argument]- pipe_spec: PipeSequenceSpec,- expected_blueprint: PipeSequenceBlueprint,- ):- result = pipe_spec.to_blueprint()- assert result == expected_blueprintdiff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_data.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_data.pydeleted file mode 100644index a70776365..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_data.py+++ /dev/null@@ -1,69 +0,0 @@-from typing import ClassVar--from pipelex.builder.pipe.pipe_compose_spec import PipeComposeSpec-from pipelex.cogt.templating.template_blueprint import TemplateBlueprint-from pipelex.pipe_operators.compose.pipe_compose_blueprint import PipeComposeBlueprint-from pipelex.tools.jinja2.template_category import TemplateCategory-from pipelex.tools.templating.templating_style import TagStyle, TemplatingStyle-from pipelex.tools.templating.text_format import TextFormat---class PipeComposeTestCases:- SIMPLE_COMPOSE = (- "simple_compose",- PipeComposeSpec(- pipe_code="template_renderer",- description="Render a template",- inputs={"data": "Data"},- output="RenderedText",- template="Hello {{ data.name }}!",- target_format="markdown",- ),- PipeComposeBlueprint(- description="Render a template",- inputs={"data": "Data"},- output="RenderedText",- template=TemplateBlueprint(- template="Hello {{ data.name }}!",- category=TemplateCategory.MARKDOWN,- templating_style=TemplatingStyle(- tag_style=TagStyle.TICKS,- text_format=TextFormat.MARKDOWN,- ),- extra_context=None,- ),- ),- )-- CONSTRUCT_COMPOSE = (- "construct_compose",- PipeComposeSpec.model_validate(- {- "pipe_code": "compose_sheet",- "description": "Compose interview sheet",- "inputs": {"analysis": "MatchAnalysis", "questions": "InterviewQuestion[]"},- "output": "InterviewSheet",- "construct": {- "score": {"from": "analysis.overall_score"},- "questions": {"from": "questions"},- },- }- ),- # Use model_validate to create the expected blueprint via the same validation path- PipeComposeBlueprint.model_validate(- {- "description": "Compose interview sheet",- "inputs": {"analysis": "MatchAnalysis", "questions": "InterviewQuestion[]"},- "output": "InterviewSheet",- "construct": {- "score": {"from": "analysis.overall_score"},- "questions": {"from": "questions"},- },- }- ),- )-- TEST_CASES: ClassVar[list[tuple[str, PipeComposeSpec, PipeComposeBlueprint]]] = [- SIMPLE_COMPOSE,- CONSTRUCT_COMPOSE,- ]diff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose.pydeleted file mode 100644index 8af557694..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose.py+++ /dev/null@@ -1,20 +0,0 @@-import pytest--from pipelex.builder.pipe.pipe_compose_spec import PipeComposeSpec-from pipelex.pipe_operators.compose.pipe_compose_blueprint import PipeComposeBlueprint-from tests.unit.pipelex.builder.pipe.pipe_operator.pipe_compose.test_data import PipeComposeTestCases---class TestPipeComposeBlueprintConversion:- @pytest.mark.parametrize(- ("_test_name", "pipe_spec", "expected_blueprint"),- PipeComposeTestCases.TEST_CASES,- )- def test_pipe_compose_spec_to_blueprint(- self,- _test_name: str,- pipe_spec: PipeComposeSpec,- expected_blueprint: PipeComposeBlueprint,- ):- result = pipe_spec.to_blueprint()- assert result == expected_blueprintdiff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose_to_toml.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose_to_toml.pydeleted file mode 100644index cc5506006..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_compose/test_pipe_compose_to_toml.py+++ /dev/null@@ -1,111 +0,0 @@-"""Unit tests for PipeCompose TOML serialization via pipe_spec_to_toml."""--from typing import Any, ClassVar--import pytest--from pipelex.builder.operations.pipe_ops import pipe_spec_to_toml-from pipelex.builder.pipe.pipe_compose_spec import PipeComposeSpec---class _TomlTestCases:- """Test data for PipeCompose → TOML serialization."""-- CONSTRUCT_WITH_FROM_MAPPINGS: ClassVar[tuple[str, dict[str, Any]]] = (- "construct_with_from_mappings",- {- "pipe_code": "compose_sheet",- "description": "Compose interview sheet",- "inputs": {"analysis": "MatchAnalysis", "questions": "InterviewQuestion[]"},- "output": "InterviewSheet",- "construct": {- "score": {"from": "analysis.overall_score"},- "questions": {"from": "questions"},- },- },- )-- CONSTRUCT_WITH_STATIC_VALUES: ClassVar[tuple[str, dict[str, Any]]] = (- "construct_with_static_values",- {- "pipe_code": "compose_report",- "description": "Compose a report",- "inputs": {"title": "native.Text"},- "output": "Report",- "construct": {- "title": {"from": "title"},- "version": "1.0",- "page_count": 42,- },- },- )-- TEMPLATE_MODE: ClassVar[tuple[str, dict[str, Any]]] = (- "template_mode",- {- "pipe_code": "render_greeting",- "description": "Render a greeting",- "inputs": {"name": "native.Text"},- "output": "native.Text",- "target_format": "markdown",- "template": "Hello $name!",- },- )---class TestPipeComposeToToml:- """Tests for pipe_spec_to_toml with PipeCompose specs."""-- @pytest.mark.parametrize(- ("_test_name", "spec_data"),- [- _TomlTestCases.CONSTRUCT_WITH_FROM_MAPPINGS,- _TomlTestCases.CONSTRUCT_WITH_STATIC_VALUES,- _TomlTestCases.TEMPLATE_MODE,- ],- )- def test_pipe_spec_to_toml_does_not_crash(- self,- _test_name: str,- spec_data: dict[str, Any],- ) -> None:- """All PipeCompose modes should serialize to TOML without errors."""- pipe_spec = PipeComposeSpec.model_validate({**spec_data, "type": "PipeCompose"})- result = pipe_spec_to_toml(pipe_spec)- assert isinstance(result, str)- assert len(result) > 0-- def test_construct_mode_has_construct_section(self) -> None:- """Construct mode should produce a [pipe.<code>.construct] section with inline tables."""- spec_data = _TomlTestCases.CONSTRUCT_WITH_FROM_MAPPINGS[1]- pipe_spec = PipeComposeSpec.model_validate({**spec_data, "type": "PipeCompose"})- result = pipe_spec_to_toml(pipe_spec)-- assert "[pipe.compose_sheet.construct]" in result- assert 'score = {from = "analysis.overall_score"}' in result- assert 'questions = {from = "questions"}' in result- # Template mode fields should NOT appear- assert "target_format" not in result- assert "template" not in result-- def test_construct_with_static_values(self) -> None:- """Non-dict values in construct spec should be serialized directly."""- spec_data = _TomlTestCases.CONSTRUCT_WITH_STATIC_VALUES[1]- pipe_spec = PipeComposeSpec.model_validate({**spec_data, "type": "PipeCompose"})- result = pipe_spec_to_toml(pipe_spec)-- assert "[pipe.compose_report.construct]" in result- assert 'title = {from = "title"}' in result- assert 'version = "1.0"' in result- assert "page_count = 42" in result-- def test_template_mode_has_target_format_and_template(self) -> None:- """Template mode should produce target_format and template fields."""- spec_data = _TomlTestCases.TEMPLATE_MODE[1]- pipe_spec = PipeComposeSpec.model_validate({**spec_data, "type": "PipeCompose"})- result = pipe_spec_to_toml(pipe_spec)-- assert 'target_format = "markdown"' in result- assert 'template = "Hello $name!"' in result- # Construct section should NOT appear- assert "construct" not in result.split("template")[0] # no construct key before templatediff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_extract/test_data.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_extract/test_data.pydeleted file mode 100644index 5513a0037..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_extract/test_data.py+++ /dev/null@@ -1,53 +0,0 @@-from typing import ClassVar--from pipelex.builder.pipe.pipe_extract_spec import PipeExtractSpec-from pipelex.pipe_operators.extract.pipe_extract_blueprint import PipeExtractBlueprint---class PipeExtractTestCases:- SIMPLE_EXTRACT = (- "simple_extract",- PipeExtractSpec(- pipe_code="extractor",- description="Extract text from image",- inputs={"image": "Image"},- output="Page",- model="@default-text-from-pdf",- ),- PipeExtractBlueprint(- source=None,- description="Extract text from image",- inputs={"image": "Image"},- output="Page[]",- model="@default-text-from-pdf",- ),- )-- EXTRACT_WITH_OPTIONS = (- "extract_with_options",- PipeExtractSpec(- pipe_code="advanced_extract",- description="Extract with page options",- inputs={"document": "Document"},- output="Page[]",- model="@default-text-from-pdf",- max_page_images=None,- page_views=True,- ),- PipeExtractBlueprint(- source=None,- description="Extract with page options",- inputs={"document": "Document"},- output="Page[]",- model="@default-text-from-pdf",- max_page_images=None,- page_image_captions=None,- page_views=True,- page_views_dpi=None,- ),- )-- TEST_CASES: ClassVar[list[tuple[str, PipeExtractSpec, PipeExtractBlueprint]]] = [- SIMPLE_EXTRACT,- EXTRACT_WITH_OPTIONS,- ]diff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_extract/test_pipe_extract.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_extract/test_pipe_extract.pydeleted file mode 100644index 3b7b96198..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_extract/test_pipe_extract.py+++ /dev/null@@ -1,22 +0,0 @@-import pytest--from pipelex import log-from pipelex.builder.pipe.pipe_extract_spec import PipeExtractSpec-from pipelex.pipe_operators.extract.pipe_extract_blueprint import PipeExtractBlueprint-from tests.unit.pipelex.builder.pipe.pipe_operator.pipe_extract.test_data import PipeExtractTestCases---class TestPipeExtractBlueprintConversion:- @pytest.mark.parametrize(- ("test_name", "pipe_spec", "expected_blueprint"),- PipeExtractTestCases.TEST_CASES,- )- def test_pipe_extract_spec_to_blueprint(- self,- test_name: str,- pipe_spec: PipeExtractSpec,- expected_blueprint: PipeExtractBlueprint,- ):- log.verbose(f"Testing {test_name}")- result = pipe_spec.to_blueprint()- assert result == expected_blueprintdiff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_func/test_data.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_func/test_data.pydeleted file mode 100644index 55faff67f..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_func/test_data.py+++ /dev/null@@ -1,44 +0,0 @@-from typing import ClassVar--from pipelex.builder.pipe.pipe_func_spec import PipeFuncSpec-from pipelex.pipe_operators.func.pipe_func_blueprint import PipeFuncBlueprint---class PipeFuncTestCases:- SIMPLE_FUNC = (- "simple_func",- PipeFuncSpec(- pipe_code="func_processor",- description="Execute a function",- inputs={"data": "Data"},- output="ProcessedData",- function_name="process_data",- ),- PipeFuncBlueprint(- description="Execute a function",- inputs={"data": "Data"},- output="ProcessedData",- function_name="process_data",- ),- )-- FUNC_NO_INPUTS = (- "func_no_inputs",- PipeFuncSpec(- pipe_code="generator_func",- description="Generate data",- inputs={},- output="GeneratedData",- function_name="generate_data",- ),- PipeFuncBlueprint(- description="Generate data",- output="GeneratedData",- function_name="generate_data",- ),- )-- TEST_CASES: ClassVar[list[tuple[str, PipeFuncSpec, PipeFuncBlueprint]]] = [- SIMPLE_FUNC,- FUNC_NO_INPUTS,- ]diff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_func/test_pipe_func.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_func/test_pipe_func.pydeleted file mode 100644index 0efcb5745..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_func/test_pipe_func.py+++ /dev/null@@ -1,20 +0,0 @@-import pytest--from pipelex.builder.pipe.pipe_func_spec import PipeFuncSpec-from pipelex.pipe_operators.func.pipe_func_blueprint import PipeFuncBlueprint-from tests.unit.pipelex.builder.pipe.pipe_operator.pipe_func.test_data import PipeFuncTestCases---class TestPipeFuncBlueprintConversion:- @pytest.mark.parametrize(- ("test_name", "pipe_spec", "expected_blueprint"),- PipeFuncTestCases.TEST_CASES,- )- def test_pipe_func_spec_to_blueprint(- self,- test_name: str, # ruff: ignore[unused-method-argument]- pipe_spec: PipeFuncSpec,- expected_blueprint: PipeFuncBlueprint,- ):- result = pipe_spec.to_blueprint()- assert result == expected_blueprintdiff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_img_gen/test_data.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_img_gen/test_data.pydeleted file mode 100644index 118a2d569..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_img_gen/test_data.py+++ /dev/null@@ -1,59 +0,0 @@-from typing import ClassVar--from pipelex.builder.pipe.pipe_img_gen_spec import PipeImgGenSpec-from pipelex.pipe_operators.img_gen.pipe_img_gen_blueprint import PipeImgGenBlueprint---class PipeImgGenTestCases:- SIMPLE_IMG_GEN = (- "simple_img_gen",- PipeImgGenSpec(- pipe_code="img_generator",- description="Generate an image",- inputs={"my_prompt": "Text"},- output="native.Image",- model="$gen-image",- prompt="@my_prompt",- ),- PipeImgGenBlueprint(- description="Generate an image",- inputs={"my_prompt": "Text"},- output="native.Image",- prompt="@my_prompt",- model="$gen-image",- aspect_ratio=None,- background=None,- output_format=None,- is_raw=None,- seed=None,- ),- )-- IMG_GEN_WITH_OPTIONS = (- "img_gen_with_options",- PipeImgGenSpec(- pipe_code="advanced_img_gen",- description="Generate image with options",- inputs={"description": "Text"},- output="Image[3]",- prompt="@description",- model="$gen-image-fast",- ),- PipeImgGenBlueprint(- description="Generate image with options",- inputs={"description": "Text"},- output="Image[3]",- prompt="@description",- model="$gen-image-fast",- aspect_ratio=None,- background=None,- output_format=None,- is_raw=None,- seed=None,- ),- )-- TEST_CASES: ClassVar[list[tuple[str, PipeImgGenSpec, PipeImgGenBlueprint]]] = [- SIMPLE_IMG_GEN,- IMG_GEN_WITH_OPTIONS,- ]diff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_img_gen/test_pipe_img_gen.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_img_gen/test_pipe_img_gen.pydeleted file mode 100644index 4626ca9b3..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_img_gen/test_pipe_img_gen.py+++ /dev/null@@ -1,20 +0,0 @@-import pytest--from pipelex.builder.pipe.pipe_img_gen_spec import PipeImgGenSpec-from pipelex.pipe_operators.img_gen.pipe_img_gen_blueprint import PipeImgGenBlueprint-from tests.unit.pipelex.builder.pipe.pipe_operator.pipe_img_gen.test_data import PipeImgGenTestCases---class TestPipeImgGenBlueprintConversion:- @pytest.mark.parametrize(- ("test_name", "pipe_spec", "expected_blueprint"),- PipeImgGenTestCases.TEST_CASES,- )- def test_pipe_img_gen_spec_to_blueprint(- self,- test_name: str, # ruff: ignore[unused-method-argument]- pipe_spec: PipeImgGenSpec,- expected_blueprint: PipeImgGenBlueprint,- ):- result = pipe_spec.to_blueprint()- assert result == expected_blueprintdiff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_judge/test_pipe_judge_spec_rendering.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_judge/test_pipe_judge_spec_rendering.pydeleted file mode 100644index bced6e47a..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_judge/test_pipe_judge_spec_rendering.py+++ /dev/null@@ -1,21 +0,0 @@-"""PipeJudgeSpec.rendered_pretty shows what the author wrote, markup characters included."""--from rich.console import Console--from pipelex.builder.pipe.pipe_judge_spec import PipeJudgeSpec---class TestPipeJudgeSpecRendering:- def test_a_bracketed_word_in_the_question_is_shown_as_written(self) -> None:- spec = PipeJudgeSpec(- pipe_code="is_flagged",- description="Judge the flag",- inputs={"message": "Text"},- output="YesNo",- question="Is the [urgent] flag set, or the [/x] one?",- )- console = Console(record=True, width=120)-- console.print(spec.rendered_pretty())-- assert "Is the [urgent] flag set, or the [/x] one?" in console.export_text()diff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_data.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_data.pydeleted file mode 100644index 84ed642a4..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_data.py+++ /dev/null@@ -1,182 +0,0 @@-from typing import ClassVar--from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint---class PipeLLMTestCases:- SIMPLE_LLM = (- "simple_llm",- PipeLLMSpec(- pipe_code="test_pipe",- description="Generate text",- inputs={"topic": "Text"},- output="Text",- model="$writing-creative",- prompt="Write about $topic",- ),- PipeLLMBlueprint(- source=None,- type="PipeLLM",- description="Generate text",- inputs={"topic": "Text"},- output="Text",- prompt="Write about $topic",- model="$writing-creative",- ),- )-- LLM_NO_INPUTS = (- "llm_no_inputs",- PipeLLMSpec(- pipe_code="generate_pipe",- description="Generate without inputs",- inputs={},- output="Text",- model="$writing-creative",- prompt="Generate something interesting",- ),- PipeLLMBlueprint(- source=None,- type="PipeLLM",- description="Generate without inputs",- output="Text",- prompt="Generate something interesting",- model="$writing-creative",- ),- )-- LLM_WITH_VISION_INPUT = (- "llm_with_vision_input",- PipeLLMSpec(- pipe_code="analyze_image",- description="Analyze image",- inputs={"image": "Image"},- output="Text",- prompt="Analyze the image: $image",- model="$vision",- ),- PipeLLMBlueprint(- source=None,- type="PipeLLM",- description="Analyze image",- inputs={"image": "Image"},- output="Text",- prompt="Analyze the image: $image",- model="$vision",- ),- )-- LLM_WITH_PRESET = (- "llm_with_preset",- PipeLLMSpec(- pipe_code="generate",- description="Generate with preset",- inputs={},- output="Text",- prompt="Generate text",- model="$writing-creative",- ),- PipeLLMBlueprint(- source=None,- type="PipeLLM",- description="Generate with preset",- model="$writing-creative",- output="Text",- prompt="Generate text",- ),- )-- LLM_WITH_SETTINGS = (- "llm_with_settings",- PipeLLMSpec(- pipe_code="generate",- description="Generate with settings",- inputs={},- output="Text",- prompt="Generate text",- model="$retrieval",- ),- PipeLLMBlueprint(- source=None,- type="PipeLLM",- description="Generate with settings",- model="$retrieval",- output="Text",- prompt="Generate text",- ),- )-- LLM_WITH_SYSTEM_PROMPT = (- "llm_with_system_prompt",- PipeLLMSpec(- pipe_code="analyze",- description="Generate with system prompt",- inputs={"data": "Data"},- output="Analysis",- system_prompt="You are a data analyst",- prompt="Analyze: $data",- model="$retrieval",- ),- PipeLLMBlueprint(- source=None,- type="PipeLLM",- description="Generate with system prompt",- inputs={"data": "Data"},- system_prompt="You are a data analyst",- prompt="Analyze: $data",- output="Analysis",- model="$retrieval",- ),- )-- LLM_WITH_MULTIPLE_OUTPUT = (- "llm_with_multiple_output",- PipeLLMSpec(- pipe_code="generate_items",- description="Generate multiple items",- inputs={},- output="Item[]",- prompt="Generate items",- model="$writing-creative",- ),- PipeLLMBlueprint(- source=None,- type="PipeLLM",- description="Generate multiple items",- output="Item[]",- prompt="Generate items",- model="$writing-creative",- ),- )-- LLM_WITH_FIXED_OUTPUT = (- "llm_with_fixed_output",- PipeLLMSpec(- pipe_code="generate_items",- description="Generate exactly 5 items",- inputs={},- output="Item[5]",- prompt="Generate items",- model="$writing-creative",- ),- PipeLLMBlueprint(- source=None,- type="PipeLLM",- description="Generate exactly 5 items",- output="Item[5]",- prompt="Generate items",- model="$writing-creative",- ),- )-- TEST_CASES: ClassVar[list[tuple[str, PipeLLMSpec, PipeLLMBlueprint]]] = [- SIMPLE_LLM,- LLM_NO_INPUTS,- LLM_WITH_VISION_INPUT,- LLM_WITH_PRESET,- LLM_WITH_SETTINGS,- LLM_WITH_SYSTEM_PROMPT,- LLM_WITH_MULTIPLE_OUTPUT,- LLM_WITH_FIXED_OUTPUT,- ]diff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_pipe_llm.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_pipe_llm.pydeleted file mode 100644index 0f7ca09b2..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_llm/test_pipe_llm.py+++ /dev/null@@ -1,47 +0,0 @@-from typing import Callable--import pytest--from pipelex import pretty_print-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.core.concepts.concept_factory import ConceptFactory-from pipelex.interpreter_hub import get_concept_library-from pipelex.pipe_machinery.pipe_factory import PipeFactory-from pipelex.pipe_operators.llm.pipe_llm import PipeLLM-from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint-from tests.unit.pipelex.builder.pipe.pipe_operator.pipe_llm.test_data import PipeLLMTestCases---class TestPipeLLMBlueprintConversion:- @pytest.mark.parametrize(- ("test_name", "pipe_spec", "expected_blueprint"),- PipeLLMTestCases.TEST_CASES,- )- def test_pipe_llm_spec_to_blueprint(- self, test_name: str, pipe_spec: PipeLLMSpec, expected_blueprint: PipeLLMBlueprint, load_empty_library: Callable[[], str]- ):- load_empty_library()- # Built from blueprints, not `ConceptFactory.make`: the blueprint path materializes and- # registers each structure class, so the library reaches a state the loader could actually- # produce. Naming a structure class that no registry holds is not a state a real library- # can be in, and compatibility questions about it have no answer.- item_concept = ConceptFactory.make_from_blueprint(concept_code="Item", domain_code="test_domain", blueprint_or_string_description="Item")- data_concept = ConceptFactory.make_from_blueprint(concept_code="Data", domain_code="test_domain", blueprint_or_string_description="Data")- analysis_concept = ConceptFactory.make_from_blueprint(- concept_code="Analysis", domain_code="test_domain", blueprint_or_string_description="Analysis"- )- concept_library = get_concept_library()- concept_library.add_new_concept(concept=item_concept)- concept_library.add_new_concept(concept=data_concept)- concept_library.add_new_concept(concept=analysis_concept)-- blueprint = pipe_spec.to_blueprint()- assert blueprint == expected_blueprint-- pipe_llm = PipeFactory[PipeLLM].make_from_blueprint(- domain_code="test_domain",- pipe_code=f"test_pipe_{test_name}",- blueprint=blueprint,- concept_codes_from_the_same_domain=[data_concept.code, item_concept.code, analysis_concept.code],- )- pretty_print(pipe_llm, title="PipeLLM from blueprint")diff --git a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_structure/test_pipe_structure_spec.py b/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_structure/test_pipe_structure_spec.pydeleted file mode 100644index e607ccc31..000000000--- a/tests/unit/pipelex/builder/pipe/pipe_operator/pipe_structure/test_pipe_structure_spec.py+++ /dev/null@@ -1,45 +0,0 @@-import pytest--from pipelex.builder.pipe.pipe_structure_spec import PipeStructureSpec-from pipelex.pipe_operators.structure.pipe_structure_blueprint import PipeStructureBlueprint---class TestPipeStructureSpec:- def test_spec_to_blueprint_minimal(self):- spec = PipeStructureSpec(- pipe_code="extract_book_info",- pipe_category="PipeOperator",- description="Turn raw text into a Book record",- inputs={"draft_text": "Text"},- output="Book",- )- blueprint = spec.to_blueprint()- assert isinstance(blueprint, PipeStructureBlueprint)- assert blueprint.description == "Turn raw text into a Book record"- assert blueprint.inputs == {"draft_text": "Text"}- assert blueprint.output == "Book"- assert blueprint.model is None-- def test_spec_to_blueprint_with_model(self):- spec = PipeStructureSpec(- pipe_code="structure_doc",- pipe_category="PipeOperator",- description="Structure document text",- inputs={"page_text": "Text"},- output="ContactCard[]",- model="some-model-handle",- )- blueprint = spec.to_blueprint()- assert blueprint.model is not None- assert blueprint.output == "ContactCard[]"-- def test_spec_rejects_empty_model(self):- with pytest.raises(ValueError, match="Model cannot be an empty string"):- PipeStructureSpec(- pipe_code="structure_doc",- pipe_category="PipeOperator",- description="Bad",- inputs={"page_text": "Text"},- output="ContactCard",- model=" ",- )diff --git a/tests/unit/pipelex/builder/pipe/test_data_inputs.py b/tests/unit/pipelex/builder/pipe/test_data_inputs.pydeleted file mode 100644index de8d19a60..000000000--- a/tests/unit/pipelex/builder/pipe/test_data_inputs.py+++ /dev/null@@ -1,34 +0,0 @@-from typing import ClassVar---class InputRequirementTestCases:- SIMPLE_TEXT_INPUT = (- "simple_text_input",- "Text",- "Text",- )-- IMAGE_INPUT = (- "image_input",- "Image",- "Image",- )-- CUSTOM_CONCEPT_INPUT = (- "custom_concept_input",- "CustomConcept",- "CustomConcept",- )-- DOMAIN_CONCEPT_INPUT = (- "domain_concept_input",- "domain.ConceptName",- "domain.ConceptName",- )-- TEST_CASES: ClassVar[list[tuple[str, str, str]]] = [- SIMPLE_TEXT_INPUT,- IMAGE_INPUT,- CUSTOM_CONCEPT_INPUT,- DOMAIN_CONCEPT_INPUT,- ]diff --git a/tests/unit/pipelex/builder/pipe/test_data_pipe.py b/tests/unit/pipelex/builder/pipe/test_data_pipe.pydeleted file mode 100644index ff46e19f7..000000000--- a/tests/unit/pipelex/builder/pipe/test_data_pipe.py+++ /dev/null@@ -1,75 +0,0 @@-from typing import ClassVar--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.pipe_machinery.pipe_blueprint import PipeBlueprint---class PipeBlueprintTestCases:- SIMPLE_PIPE = (- "simple_pipe",- PipeSpec(- pipe_code="simple_pipe",- type="PipeLLM",- pipe_category="PipeOperator",- description="A simple pipe",- inputs={"input": "Text"},- output="ProcessedText",- ),- PipeBlueprint(- type="PipeLLM",- pipe_category="PipeOperator",- description="A simple pipe",- inputs={"input": "Text"},- output="ProcessedText",- ),- )-- PIPE_WITH_INPUT_REQUIREMENTS = (- "pipe_with_requirements",- PipeSpec(- pipe_code="pipe_with_requirements",- type="PipeFunc",- pipe_category="PipeOperator",- description="Pipe with input requirements",- inputs={- "data": "Data",- "config": "Config",- },- output="Result",- ),- PipeBlueprint(- type="PipeFunc",- pipe_category="PipeOperator",- description="Pipe with input requirements",- inputs={- "data": "Data",- "config": "Config",- },- output="Result",- ),- )-- PIPE_NO_INPUTS = (- "pipe_no_inputs",- PipeSpec(- pipe_code="pipe_no_inputs",- type="PipeFunc",- pipe_category="PipeOperator",- description="Pipe without inputs",- inputs={},- output="GeneratedData",- ),- PipeBlueprint(- type="PipeFunc",- pipe_category="PipeOperator",- description="Pipe without inputs",- inputs=None,- output="GeneratedData",- ),- )-- TEST_CASES: ClassVar[list[tuple[str, PipeSpec, PipeBlueprint]]] = [- SIMPLE_PIPE,- PIPE_WITH_INPUT_REQUIREMENTS,- PIPE_NO_INPUTS,- ]diff --git a/tests/unit/pipelex/builder/pipe/test_data_sub_pipe.py b/tests/unit/pipelex/builder/pipe/test_data_sub_pipe.pydeleted file mode 100644index c89235903..000000000--- a/tests/unit/pipelex/builder/pipe/test_data_sub_pipe.py+++ /dev/null@@ -1,23 +0,0 @@-from typing import ClassVar--from pipelex.builder.pipe.sub_pipe_spec import SubPipeSpec-from pipelex.pipe_controllers.sub_pipe_blueprint import SubPipeBlueprint---class SubPipeTestCases:- SIMPLE_SUB_PIPE = (- "simple_sub_pipe",- SubPipeSpec(pipe_code="process_data", result="processed_data"),- SubPipeBlueprint(pipe="process_data", result="processed_data"),- )-- SUB_PIPE_WITH_BATCH = (- "sub_pipe_with_batch",- SubPipeSpec(pipe_code="process_item", result="processed_items", batch_over="items", batch_as="item"),- SubPipeBlueprint(pipe="process_item", result="processed_items", batch_over="items", batch_as="item"),- )-- TEST_CASES: ClassVar[list[tuple[str, SubPipeSpec, SubPipeBlueprint]]] = [- SIMPLE_SUB_PIPE,- SUB_PIPE_WITH_BATCH,- ]diff --git a/tests/unit/pipelex/builder/pipe/test_inputs_blueprint.py b/tests/unit/pipelex/builder/pipe/test_inputs_blueprint.pydeleted file mode 100644index ad9f50692..000000000--- a/tests/unit/pipelex/builder/pipe/test_inputs_blueprint.py+++ /dev/null@@ -1,18 +0,0 @@-import pytest--from tests.unit.pipelex.builder.pipe.test_data_inputs import InputRequirementTestCases---class TestInputRequirementBlueprintConversion:- @pytest.mark.parametrize(- ("test_name", "input_spec", "expected_string"),- InputRequirementTestCases.TEST_CASES,- )- def test_input_requirement_spec_to_string(- self,- test_name: str, # ruff: ignore[unused-method-argument]- input_spec: str,- expected_string: str,- ):- # Now inputs are just strings, so we test that they match- assert input_spec == expected_stringdiff --git a/tests/unit/pipelex/builder/pipe/test_pipe_blueprint.py b/tests/unit/pipelex/builder/pipe/test_pipe_blueprint.pydeleted file mode 100644index 4028fbaca..000000000--- a/tests/unit/pipelex/builder/pipe/test_pipe_blueprint.py+++ /dev/null@@ -1,20 +0,0 @@-import pytest--from pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.pipe_machinery.pipe_blueprint import PipeBlueprint-from tests.unit.pipelex.builder.pipe.test_data_pipe import PipeBlueprintTestCases---class TestPipeBlueprintConversion:- @pytest.mark.parametrize(- ("test_name", "pipe_spec", "expected_blueprint"),- PipeBlueprintTestCases.TEST_CASES,- )- def test_pipe_blueprint_to_core(- self,- test_name: str, # ruff: ignore[unused-method-argument]- pipe_spec: PipeSpec,- expected_blueprint: PipeBlueprint,- ):- result = pipe_spec.to_blueprint()- assert result == expected_blueprintdiff --git a/tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py b/tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.pydeleted file mode 100644index 1aa2175dc..000000000--- a/tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py+++ /dev/null@@ -1,96 +0,0 @@-import pytest-from pydantic import ValidationError-from rich.console import Console--from pipelex.builder.pipe.pipe_signature_spec import PipeSignatureSpec-from pipelex.pipe_machinery.pipe_blueprint import PipeType-from pipelex.pipe_signature.pipe_signature_blueprint import PipeSignatureBlueprint---def _render_to_text(spec: PipeSignatureSpec) -> str:- console = Console(width=200, record=True)- console.print(spec.rendered_pretty())- return console.export_text()---def _make_minimal_signature(**overrides: object) -> PipeSignatureSpec:- kwargs: dict[str, object] = {- "pipe_code": "sig_pipe",- "description": "A signature.",- "inputs": {"doc": "Document"},- "output": "Summary",- }- kwargs.update(overrides)- return PipeSignatureSpec(**kwargs) # type: ignore[arg-type]---class TestPipeSignatureSpec:- def test_type_literal_is_pipe_signature(self) -> None:- sig = _make_minimal_signature()- assert sig.type == "PipeSignature"-- def test_signature_for_optional(self) -> None:- no_hint = _make_minimal_signature()- assert no_hint.signature_for is None- with_hint = _make_minimal_signature(signature_for=PipeType.PIPE_LLM)- assert with_hint.signature_for is PipeType.PIPE_LLM-- def test_signature_for_rejects_pipe_signature(self) -> None:- # Structural: `PipeSignature` is not a `PipeType`, so the string cannot coerce into the field.- with pytest.raises(ValidationError):- _make_minimal_signature(signature_for="PipeSignature")-- def test_inputs_accept_multiplicity(self) -> None:- var_list = _make_minimal_signature(inputs={"docs": "Document[]"})- assert var_list.inputs == {"docs": "Document[]"}- fixed_list = _make_minimal_signature(inputs={"images": "Image[3]"})- assert fixed_list.inputs == {"images": "Image[3]"}-- def test_inputs_reject_invalid_concept_syntax(self) -> None:- with pytest.raises(ValidationError):- _make_minimal_signature(inputs={"bad": "lowercase"})-- def test_no_result_field(self) -> None:- assert "result" not in PipeSignatureSpec.model_fields-- def test_to_blueprint_returns_signature_blueprint(self) -> None:- sig = _make_minimal_signature(signature_for=PipeType.PIPE_LLM)- blueprint = sig.to_blueprint()- assert isinstance(blueprint, PipeSignatureBlueprint)- assert blueprint.description == sig.description- assert blueprint.inputs == sig.inputs- assert blueprint.output == sig.output- assert blueprint.signature_for is PipeType.PIPE_LLM-- def test_to_blueprint_preserves_input_multiplicity(self) -> None:- sig = _make_minimal_signature(inputs={"docs": "Document[]"})- blueprint = sig.to_blueprint()- assert blueprint.inputs == {"docs": "Document[]"}-- def test_rendered_pretty_preserves_bracketed_values_single_input(self) -> None:- # Multiplicity suffixes (`Foo[]`, `Foo[3]`) and bracketed free text must survive rendering:- # interpolated unescaped into Rich markup, the brackets would be parsed as tags and dropped.- sig = _make_minimal_signature(- description="Summarize the [important] parts",- inputs={"docs": "Document[]"},- output="Summary[]",- )- text = _render_to_text(sig)- assert "[important]" in text- assert "Document[]" in text- assert "Summary[]" in text-- def test_rendered_pretty_preserves_bracketed_values_multi_input(self) -> None:- # The multi-input branch renders a table whose string cells are also markup-interpreted;- # the bracketed description exercises the free-text injection in this branch too.- sig = _make_minimal_signature(- description="Fuse the [docs] and [images]",- inputs={"docs": "Document[]", "images": "Image[3]"},- output="Summary[2]",- )- text = _render_to_text(sig)- assert "[docs]" in text- assert "[images]" in text- assert "Document[]" in text- assert "Image[3]" in text- assert "Summary[2]" in textdiff --git a/tests/unit/pipelex/builder/pipe/test_pipe_spec_code_validation.py b/tests/unit/pipelex/builder/pipe/test_pipe_spec_code_validation.pydeleted file mode 100644index 356065c8e..000000000--- a/tests/unit/pipelex/builder/pipe/test_pipe_spec_code_validation.py+++ /dev/null@@ -1,27 +0,0 @@-import pytest--from pipelex.builder.pipe.pipe_spec import PipeSpec---class TestPipeSpecCodeValidation:- """Tests for PipeSpec.validate_pipe_code_syntax namespace prefix stripping and ASCII normalization."""-- @pytest.mark.parametrize(- ("pipe_code", "expected"),- [- ("domain.my_pipe", "my_pipe"),- ("a.b.my_pipe", "my_pipe"),- ("my_pipe", "my_pipe"),- ("d\u00f6main.my_pipe", "my_pipe"),- ],- ids=["single_dot", "multi_dot", "passthrough", "unicode_with_dot"],- )- def test_validate_pipe_code_syntax_strips_namespace(self, pipe_code: str, expected: str) -> None:- """Dotted pipe codes should strip namespace first, then normalize ASCII; bare codes pass through."""- result = PipeSpec.validate_pipe_code_syntax(pipe_code)- assert result == expected-- def test_validate_pipe_code_syntax_raises_for_invalid_after_strip(self) -> None:- """A dotted code whose bare part is not snake_case should raise ValueError."""- with pytest.raises(ValueError, match="Invalid pipe code syntax"):- PipeSpec.validate_pipe_code_syntax("domain.NotSnakeCase")diff --git a/tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py b/tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.pydeleted file mode 100644index 249f20279..000000000--- a/tests/unit/pipelex/builder/pipe/test_pipe_spec_presence_markers.py+++ /dev/null@@ -1,66 +0,0 @@-import pytest-from pydantic import ValidationError--from pipelex.builder.pipe.pipe_spec import PipeSpec---def _make_spec(*, inputs: dict[str, str] | None = None, output: str = "Text") -> PipeSpec:- return PipeSpec(- pipe_code="marker_test_pipe",- type="PipeLLM",- pipe_category="PipeOperator",- description="presence marker test pipe",- inputs=inputs or {},- output=output,- )---class TestPipeSpecPresenceMarkers:- """Builder specs mirror the blueprint grammar rules for `?` and `!` (D5)."""-- @pytest.mark.parametrize("input_spec", ["Text?", "Text!", "domain.Concept?", "domain.Concept!"])- def test_singular_input_markers_accepted(self, input_spec: str):- spec = _make_spec(inputs={"the_var": input_spec})- assert spec.inputs == {"the_var": input_spec}-- @pytest.mark.parametrize("input_spec", ["Text[1]?", "Text[1]!", "domain.Concept[1]?"])- def test_marker_on_count_of_one_input_accepted(self, input_spec: str):- """`[1]` is the single form with its count written out, so it takes a marker like a bare ref."""- spec = _make_spec(inputs={"the_var": input_spec})- assert spec.inputs == {"the_var": input_spec}-- @pytest.mark.parametrize("output_spec", ["Text?", "domain.Concept?"])- def test_optional_output_accepted(self, output_spec: str):- spec = _make_spec(output=output_spec)- assert spec.output == output_spec-- def test_to_blueprint_passes_markers_through(self):- spec = _make_spec(inputs={"maybe_var": "Text?", "must_var": "Text!"}, output="Text?")- blueprint = spec.to_blueprint()- assert blueprint.inputs == {"maybe_var": "Text?", "must_var": "Text!"}- assert blueprint.output == "Text?"-- @pytest.mark.parametrize("input_spec", ["Text[]?", "Text[3]?", "Text[]!"])- def test_marker_on_plural_input_rejected(self, input_spec: str):- with pytest.raises(ValidationError, match="cannot be combined with multiplicity"):- _make_spec(inputs={"the_var": input_spec})-- @pytest.mark.parametrize("output_spec", ["Text[]?", "Text[3]?"])- def test_optional_marker_on_plural_output_rejected(self, output_spec: str):- with pytest.raises(ValidationError, match="cannot be combined with multiplicity"):- _make_spec(output=output_spec)-- @pytest.mark.parametrize("output_spec", ["Text!", "domain.Concept!"])- def test_force_marker_on_output_rejected(self, output_spec: str):- with pytest.raises(ValidationError, match="not allowed on outputs"):- _make_spec(output=output_spec)-- @pytest.mark.parametrize("input_spec", ["Text[0]", "Text[0]?", "Text[0]!", "domain.Concept[0]"])- def test_zero_count_input_rejected(self, input_spec: str):- with pytest.raises(ValidationError, match="at least 1"):- _make_spec(inputs={"the_var": input_spec})-- @pytest.mark.parametrize("input_spec", ["Text??", "Text?[]"])- def test_malformed_marker_input_syntax_rejected(self, input_spec: str):- with pytest.raises(ValidationError, match="Invalid input syntax"):- _make_spec(inputs={"the_var": input_spec})diff --git a/tests/unit/pipelex/builder/pipe/test_pipe_spec_union_signature.py b/tests/unit/pipelex/builder/pipe/test_pipe_spec_union_signature.pydeleted file mode 100644index 443f1009b..000000000--- a/tests/unit/pipelex/builder/pipe/test_pipe_spec_union_signature.py+++ /dev/null@@ -1,36 +0,0 @@-from pydantic import TypeAdapter--from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.builder.pipe.pipe_signature_spec import PipeSignatureSpec-from pipelex.builder.pipe.pipe_spec_union import PipeSpecUnion---class TestPipeSpecUnionDispatch:- def test_union_dispatches_pipe_signature(self) -> None:- adapter: TypeAdapter[PipeSpecUnion] = TypeAdapter(PipeSpecUnion)- result = adapter.validate_python(- {- "type": "PipeSignature",- "pipe_category": "PipeSignature",- "pipe_code": "sig_dispatch",- "description": "A signature in the union.",- "inputs": {"doc": "Document"},- "output": "Summary",- }- )- assert isinstance(result, PipeSignatureSpec)-- def test_union_dispatches_pipe_llm_unchanged(self) -> None:- adapter: TypeAdapter[PipeSpecUnion] = TypeAdapter(PipeSpecUnion)- result = adapter.validate_python(- {- "type": "PipeLLM",- "pipe_category": "PipeOperator",- "pipe_code": "llm_pipe",- "description": "An LLM pipe in the union.",- "inputs": {"text": "Text"},- "output": "Text",- "prompt": "Echo $text",- }- )- assert isinstance(result, PipeLLMSpec)diff --git a/tests/unit/pipelex/builder/pipe/test_sub_pipe_blueprint.py b/tests/unit/pipelex/builder/pipe/test_sub_pipe_blueprint.pydeleted file mode 100644index f4d5b2e31..000000000--- a/tests/unit/pipelex/builder/pipe/test_sub_pipe_blueprint.py+++ /dev/null@@ -1,15 +0,0 @@-import pytest--from pipelex.builder.pipe.sub_pipe_spec import SubPipeSpec-from pipelex.pipe_controllers.sub_pipe_blueprint import SubPipeBlueprint-from tests.unit.pipelex.builder.pipe.test_data_sub_pipe import SubPipeTestCases---class TestSubPipeBlueprintConversion:- @pytest.mark.parametrize(- ("test_name", "sub_pipe_spec", "expected_blueprint"),- SubPipeTestCases.TEST_CASES,- )- def test_sub_pipe_to_core(self, test_name: str, sub_pipe_spec: SubPipeSpec, expected_blueprint: SubPipeBlueprint): # ruff: ignore[unused-method-argument]- result = sub_pipe_spec.to_blueprint()- assert result == expected_blueprintdiff --git a/tests/unit/pipelex/builder/test_bundle_spec_rendered_pretty.py b/tests/unit/pipelex/builder/test_bundle_spec_rendered_pretty.pydeleted file mode 100644index 93a7f2cc2..000000000--- a/tests/unit/pipelex/builder/test_bundle_spec_rendered_pretty.py+++ /dev/null@@ -1,101 +0,0 @@-"""Unit tests for PipelexBundleSpec.rendered_pretty rich rendering."""--from rich.console import Console--from pipelex.builder.bundle_spec import PipelexBundleSpec-from pipelex.builder.concept.concept_spec import ConceptSpec-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.builder.pipe.sub_pipe_spec import SubPipeSpec---def make_llm_spec(pipe_code: str) -> PipeLLMSpec:- return PipeLLMSpec(- pipe_code=pipe_code,- description=f"Generate text for {pipe_code}",- inputs={"topic": "Text"},- output="Text",- prompt="Write about $topic",- model="$writing-creative",- )---def make_full_bundle_spec() -> PipelexBundleSpec:- return PipelexBundleSpec(- domain="test_domain",- description="A bundle that writes articles",- system_prompt="You are a concise writer",- main_pipe="main_seq",- concept={- "Article": ConceptSpec(concept_code="Article", description="A written article", refines="Text"),- "Summary": "A short summary of a document",- },- pipe={- "main_seq": PipeSequenceSpec(- pipe_code="main_seq",- description="Sequence main_seq",- inputs={"topic": "Text"},- output="Text",- steps=[SubPipeSpec(pipe_code="step_one", result="step_one_result")],- ),- "step_one": make_llm_spec("step_one"),- },- )---def render_to_text(bundle_spec: PipelexBundleSpec, title: str | None = None) -> str:- console = Console(record=True, color_system=None, width=300)- console.print(bundle_spec.rendered_pretty(title=title))- return console.export_text()---class TestPipelexBundleSpecRenderedPretty:- def test_full_render_with_title(self) -> None:- """A full bundle renders title, header info, system prompt and both tables."""- rendered = render_to_text(make_full_bundle_spec(), title="Bundle Overview")-- assert "Bundle Overview" in rendered- assert "Domain: test_domain" in rendered- assert "Description: A bundle that writes articles" in rendered- assert "Main Pipe: main_seq" in rendered- assert "System Prompt: You are a concise writer" in rendered-- def test_concepts_table_renders_spec_and_string_rows(self) -> None:- """The Concepts table shows a full ConceptSpec row and a string-reference row."""- rendered = render_to_text(make_full_bundle_spec())-- assert "Concepts" in rendered- assert "Concept: Article" in rendered- assert "Refines: Text" in rendered- assert "Description: A written article" in rendered- assert "Summary: A short summary of a document" in rendered-- def test_pipes_table_lists_each_pipe(self) -> None:- """The Pipes table lists every pipe with its type, inputs and output concept codes."""- rendered = render_to_text(make_full_bundle_spec())-- assert "Pipes" in rendered- assert "Pipe: main_seq" in rendered- assert "Type: PipeSequence (PipeController)" in rendered- assert "Sequence Steps:" in rendered- assert "Pipe: step_one" in rendered- assert "Type: PipeLLM (PipeOperator)" in rendered- assert "Input: topic (Text)" in rendered- assert "Output: Text" in rendered-- def test_minimal_render_omits_optional_sections(self) -> None:- """Without title, description and system_prompt, those sections are absent from the output."""- bundle_spec = PipelexBundleSpec(- domain="test_domain",- main_pipe="step_one",- pipe={"step_one": make_llm_spec("step_one")},- )-- rendered = render_to_text(bundle_spec)-- assert "Domain: test_domain" in rendered- assert "Main Pipe: step_one" in rendered- assert "Description: A bundle" not in rendered- assert "System Prompt:" not in rendered- assert "Concepts" not in rendered- assert "Pipes" in rendereddiff --git a/tests/unit/pipelex/builder/test_bundle_spec_to_blueprint.py b/tests/unit/pipelex/builder/test_bundle_spec_to_blueprint.pydeleted file mode 100644index 1e299419f..000000000--- a/tests/unit/pipelex/builder/test_bundle_spec_to_blueprint.py+++ /dev/null@@ -1,178 +0,0 @@-"""Unit tests for PipelexBundleSpec.to_blueprint conversion: concepts, pipe ordering, and error wrapping."""--from typing import TYPE_CHECKING, Any--import pytest-from pydantic import ValidationError--from pipelex.builder.bundle_spec import PipelexBundleSpec-from pipelex.builder.concept.concept_spec import ConceptSpec, ConceptStructureSpec, ConceptStructureSpecFieldType-from pipelex.builder.exceptions import PipelexBundleSpecBlueprintError-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.builder.pipe.sub_pipe_spec import SubPipeSpec-from pipelex.core.concepts.concept_blueprint import ConceptBlueprint-from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprint, ConceptStructureBlueprintFieldType--if TYPE_CHECKING:- from pytest_mock import MockerFixture---def make_llm_spec(pipe_code: str) -> PipeLLMSpec:- return PipeLLMSpec(- pipe_code=pipe_code,- description=f"Generate text for {pipe_code}",- inputs={"topic": "Text"},- output="Text",- prompt="Write about $topic",- model="$writing-creative",- )---def make_sequence_spec(pipe_code: str, step_codes: list[str]) -> PipeSequenceSpec:- steps = [SubPipeSpec(pipe_code=step_code, result=f"{step_code}_result") for step_code in step_codes]- return PipeSequenceSpec(- pipe_code=pipe_code,- description=f"Sequence {pipe_code}",- inputs={"topic": "Text"},- output="Text",- steps=steps,- )---def make_captured_validation_error() -> ValidationError:- """Capture a real pydantic ValidationError from an intentionally invalid model construction."""- try:- ConceptBlueprint.model_validate({})- except ValidationError as exc:- return exc- pytest.fail("ConceptBlueprint.model_validate({}) should have raised a ValidationError")---class TestPipelexBundleSpecToBlueprint:- def test_concept_spec_value_converted_to_concept_blueprint(self) -> None:- """A ConceptSpec value converts to its own blueprint, preserving description, structure and refines."""- bundle_spec = PipelexBundleSpec(- domain="test_domain",- main_pipe="write_text",- concept={- "Article": ConceptSpec(concept_code="Article", description="A written article", refines="Text"),- "Person": ConceptSpec(- concept_code="Person",- description="A person",- structure={- "full_name": ConceptStructureSpec(- the_field_name="full_name",- description="Full name of the person",- type=ConceptStructureSpecFieldType.TEXT,- required=True,- ),- },- ),- },- pipe={"write_text": make_llm_spec("write_text")},- )-- blueprint = bundle_spec.to_blueprint()-- assert blueprint.concept is not None- assert blueprint.concept["Article"] == ConceptBlueprint(description="A written article", structure=None, refines="Text")- expected_field = ConceptStructureBlueprint(- description="Full name of the person",- type=ConceptStructureBlueprintFieldType.TEXT,- required=True,- )- assert blueprint.concept["Person"] == ConceptBlueprint(description="A person", structure={"full_name": expected_field}, refines=None)-- def test_string_concept_value_passes_through_as_description(self) -> None:- """A string concept value passes through to the blueprint dict unchanged, where it means the concept's description."""- bundle_spec = PipelexBundleSpec(- domain="test_domain",- main_pipe="write_text",- concept={"Summary": "A short summary of a document"},- pipe={"write_text": make_llm_spec("write_text")},- )-- blueprint = bundle_spec.to_blueprint()-- assert blueprint.concept is not None- assert blueprint.concept["Summary"] == "A short summary of a document"-- def test_string_concept_value_survives_normal_validation(self) -> None:- """model_validate on a dict payload keeps a string concept value as a plain str via the `ConceptSpec | str` union."""- bundle_spec = PipelexBundleSpec.model_validate(- {- "domain": "test_domain",- "main_pipe": "write_text",- "concept": {"Summary": "A short summary of a document"},- "pipe": {"write_text": make_llm_spec("write_text").model_dump()},- }- )-- assert bundle_spec.concept is not None- assert bundle_spec.concept["Summary"] == "A short summary of a document"-- @pytest.mark.parametrize("empty_concepts", [None, {}])- def test_no_concepts_yields_none_concept_on_blueprint(self, empty_concepts: dict[str, Any] | None) -> None:- """Concept set to None or left empty produces a blueprint with concept=None."""- bundle_spec = PipelexBundleSpec(- domain="test_domain",- main_pipe="write_text",- concept=empty_concepts,- pipe={"write_text": make_llm_spec("write_text")},- )-- blueprint = bundle_spec.to_blueprint()-- assert blueprint.concept is None-- def test_pipes_sorted_controller_first_then_step_order(self) -> None:- """Pipes fed in scrambled dict order come out controller-first, then in step order, with header fields preserved."""- bundle_spec = PipelexBundleSpec(- domain="test_domain",- description="A sequenced bundle",- system_prompt="Be precise",- main_pipe="main_seq",- pipe={- "step_two": make_llm_spec("step_two"),- "step_one": make_llm_spec("step_one"),- "main_seq": make_sequence_spec("main_seq", step_codes=["step_one", "step_two"]),- },- )-- blueprint = bundle_spec.to_blueprint()-- assert blueprint.domain == "test_domain"- assert blueprint.description == "A sequenced bundle"- assert blueprint.system_prompt == "Be precise"- assert blueprint.main_pipe == "main_seq"- assert blueprint.pipe is not None- assert list(blueprint.pipe.keys()) == ["main_seq", "step_one", "step_two"]- assert blueprint.pipe["main_seq"].type == "PipeSequence"- assert blueprint.pipe["step_one"].type == "PipeLLM"- assert blueprint.pipe["step_two"].type == "PipeLLM"-- def test_pipe_spec_validation_error_wrapped_with_pipe_code(self, mocker: "MockerFixture") -> None:- """A ValidationError from a pipe spec's to_blueprint is wrapped, naming the failing pipe code."""- captured_error = make_captured_validation_error()- mocker.patch.object(PipeLLMSpec, "to_blueprint", side_effect=captured_error)- bundle_spec = PipelexBundleSpec(- domain="test_domain",- main_pipe="write_text",- pipe={"write_text": make_llm_spec("write_text")},- )-- with pytest.raises(PipelexBundleSpecBlueprintError, match="Failed to create pipe blueprint from spec for pipe code write_text"):- bundle_spec.to_blueprint()-- def test_bundle_blueprint_construction_failure_wrapped(self) -> None:- """A spec that yields an invalid bundle blueprint (native concept shadowing) raises the wrapped error."""- bundle_spec = PipelexBundleSpec(- domain="test_domain",- main_pipe="write_text",- concept={"Text": "Shadowing a native concept"},- pipe={"write_text": make_llm_spec("write_text")},- )-- with pytest.raises(PipelexBundleSpecBlueprintError, match="Failed to create pipelex bundle blueprint"):- bundle_spec.to_blueprint()diff --git a/tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py b/tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.pydeleted file mode 100644index 2dff85571..000000000--- a/tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py+++ /dev/null@@ -1,215 +0,0 @@-"""Unit tests for typeless-signature normalization in the spec (authoring) layer.--Mirrors the blueprint-layer behavior: a `[pipe.x]` spec section with no `type` whose keys are exactly-the signature contract is normalized to a `PipeSignatureSpec`; a typeless section with any stray field-raises the teaching error; and an explicit `type = "PipeSignature"` is rejected with the migration-error (a signature has no type).-"""--from typing import Any--import pytest-from pydantic import ValidationError--from pipelex.builder.bundle_spec import PipelexBundleSpec-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.builder.pipe.pipe_signature_spec import PipeSignatureSpec-from pipelex.pipe_machinery.pipe_blueprint import PipeType-from pipelex.pipe_signature.pipe_signature_blueprint import PipeSignatureBlueprint---def _bundle_with_pipe(pipe_section: dict[str, Any], *, pipe_code: str = "summarize_doc") -> PipelexBundleSpec:- return PipelexBundleSpec.model_validate(- {- "domain": "test_domain",- "main_pipe": pipe_code,- "pipe": {pipe_code: pipe_section},- }- )---class TestPipelexBundleSpecTypelessSignature:- def test_typeless_contract_section_becomes_signature_spec(self) -> None:- """A typeless contract-only section routes to PipeSignatureSpec and round-trips to a signature blueprint."""- bundle_spec = _bundle_with_pipe(- {- "pipe_code": "summarize_doc",- "description": "Produces a summary of a document.",- "inputs": {"doc": "Document"},- "output": "Summary",- }- )- assert bundle_spec.pipe is not None- sig_spec = bundle_spec.pipe["summarize_doc"]- assert isinstance(sig_spec, PipeSignatureSpec)-- blueprint = sig_spec.to_blueprint()- assert isinstance(blueprint, PipeSignatureBlueprint)- assert blueprint.is_signature is True- assert blueprint.description == "Produces a summary of a document."- assert blueprint.inputs == {"doc": "Document"}- assert blueprint.output == "Summary"-- def test_typeless_with_signature_for_hint_becomes_signature(self) -> None:- """`signature_for` is a contract-legal optional key, so the section is still a signature."""- bundle_spec = _bundle_with_pipe(- {- "pipe_code": "summarize_doc",- "description": "Produces a summary of a document.",- "inputs": {"doc": "Document"},- "output": "Summary",- "signature_for": "PipeLLM",- }- )- assert bundle_spec.pipe is not None- sig_spec = bundle_spec.pipe["summarize_doc"]- assert isinstance(sig_spec, PipeSignatureSpec)- assert sig_spec.signature_for is PipeType.PIPE_LLM-- def test_typeless_with_stray_field_raises_teaching_error(self) -> None:- """A typeless section carrying an implementation field is a hard error that names the field and both fixes."""- with pytest.raises(ValidationError) as exc_info:- _bundle_with_pipe(- {- "pipe_code": "summarize_doc",- "description": "Produces a summary of a document.",- "inputs": {"doc": "Document"},- "output": "Summary",- "prompt": "Summarize $doc",- }- )- message = str(exc_info.value)- assert "has no `type` but declares `prompt`" in message- assert "To keep it a contract, remove `prompt`" in message-- def test_typeless_with_blueprint_only_source_field_raises_teaching_error(self) -> None:- """`source` is a blueprint-only field absent from the spec surface, so a typeless section- carrying it is a stray key (teaching error) — not injected then rejected with a raw pydantic- `extra_forbidden` message.- """- with pytest.raises(ValidationError) as exc_info:- _bundle_with_pipe(- {- "pipe_code": "summarize_doc",- "description": "Produces a summary of a document.",- "inputs": {"doc": "Document"},- "output": "Summary",- "source": "somewhere.mthds",- }- )- message = str(exc_info.value)- assert "has no `type` but declares `source`" in message- assert "Extra inputs are not permitted" not in message-- def test_stray_key_message_advertises_signature_for(self) -> None:- """The teaching message names `signature_for` as a valid contract key (it is allowed), and does- not leak the internal `source` / `pipe_code` keys the allowlists also admit.- """- with pytest.raises(ValidationError) as exc_info:- _bundle_with_pipe(- {- "pipe_code": "summarize_doc",- "description": "Produces a summary of a document.",- "output": "Summary",- "signature_for": "PipeLLM",- "model": "gpt",- }- )- message = str(exc_info.value)- assert "has no `type` but declares `model`" in message- assert "`signature_for`" in message- assert "`source`" not in message- assert "`pipe_code`" not in message-- def test_signature_spec_survives_model_dump_revalidate_round_trip(self) -> None:- """A bundle spec with a typeless signature must survive `model_dump()` → re-validate. The- internal `type` / `pipe_category` discriminators must not serialize, else re-validation trips- the explicit-tag migration error (`type`) or the stray-key teaching error (`pipe_category`).- """- bundle_spec = _bundle_with_pipe(- {- "pipe_code": "summarize_doc",- "description": "Produces a summary of a document.",- "inputs": {"doc": "Document"},- "output": "Summary",- }- )- dumped = bundle_spec.model_dump()- sig_section = dumped["pipe"]["summarize_doc"]- assert "type" not in sig_section- assert "pipe_category" not in sig_section-- reloaded = PipelexBundleSpec.model_validate(dumped)- assert reloaded.pipe is not None- assert isinstance(reloaded.pipe["summarize_doc"], PipeSignatureSpec)-- def test_invalid_pipe_dict_key_rejected_at_spec_level(self) -> None:- """A non-snake_case pipe dict key is rejected cleanly by the before-validator (mirrors the- blueprint), instead of slipping through to fail later during `to_blueprint()`.- """- with pytest.raises(ValidationError, match="Pipe code 'BadKeyPipe' is not a valid pipe code"):- PipelexBundleSpec.model_validate(- {- "domain": "test_domain",- "main_pipe": "BadKeyPipe",- "pipe": {- "BadKeyPipe": {- "type": "PipeLLM",- "pipe_code": "good_pipe",- "description": "Writes some text.",- "inputs": {"topic": "Text"},- "output": "Text",- "prompt": "Write about $topic",- }- },- }- )-- def test_explicit_signature_tag_rejected(self) -> None:- """`PipeSignature` is no longer a pipe type: writing it explicitly in a spec section is a- migration error naming the pipe and pointing at the typeless form.- """- with pytest.raises(ValidationError) as exc_info:- _bundle_with_pipe(- {- "type": "PipeSignature",- "pipe_code": "summarize_doc",- "description": "Produces a summary of a document.",- "inputs": {"doc": "Document"},- "output": "Summary",- }- )- message = str(exc_info.value)- assert "summarize_doc" in message- assert "is no longer a pipe type" in message- assert "Delete the `type` line" in message-- def test_typed_section_left_untouched(self) -> None:- """A section that names its own `type` is not normalized — it routes to its concrete spec."""- bundle_spec = _bundle_with_pipe(- {- "type": "PipeLLM",- "pipe_code": "write_text",- "description": "Writes some text.",- "inputs": {"topic": "Text"},- "output": "Text",- "prompt": "Write about $topic",- },- pipe_code="write_text",- )- assert bundle_spec.pipe is not None- assert isinstance(bundle_spec.pipe["write_text"], PipeLLMSpec)-- def test_already_built_spec_instance_passes_through(self) -> None:- """A pre-built spec instance (not a raw dict) is left untouched by the before-validator."""- llm_spec = PipeLLMSpec(- pipe_code="write_text",- description="Writes some text.",- inputs={"topic": "Text"},- output="Text",- prompt="Write about $topic",- model="$writing-creative",- )- bundle_spec = PipelexBundleSpec(domain="test_domain", main_pipe="write_text", pipe={"write_text": llm_spec})- assert bundle_spec.pipe is not None- assert bundle_spec.pipe["write_text"] is llm_specdiff --git a/tests/unit/pipelex/builder/test_bundle_spec_validation.py b/tests/unit/pipelex/builder/test_bundle_spec_validation.pydeleted file mode 100644index fe1095799..000000000--- a/tests/unit/pipelex/builder/test_bundle_spec_validation.py+++ /dev/null@@ -1,58 +0,0 @@-"""Unit tests for PipelexBundleSpec pydantic validation rules."""--from typing import Any--import pytest-from pydantic import ValidationError--from pipelex.builder.bundle_spec import PipelexBundleSpec-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec---def make_llm_spec(pipe_code: str = "write_text") -> PipeLLMSpec:- return PipeLLMSpec(- pipe_code=pipe_code,- description=f"Generate text for {pipe_code}",- inputs={"topic": "Text"},- output="Text",- prompt="Write about $topic",- model="$writing-creative",- )---class TestPipelexBundleSpecValidation:- @pytest.mark.parametrize("bad_domain", ["Bad Domain", "UpperCase", "has-dashes", "1starts_with_digit"])- def test_invalid_domain_code_rejected(self, bad_domain: str) -> None:- """An invalid domain code is rejected with an explicit error message."""- with pytest.raises(ValidationError, match="not a valid domain code"):- PipelexBundleSpec(domain=bad_domain, main_pipe="write_text", pipe={"write_text": make_llm_spec()})-- def test_main_pipe_absent_from_pipe_dict_rejected(self) -> None:- """A main_pipe that is not a key of the pipe dict is rejected."""- with pytest.raises(ValidationError, match="Main pipe 'missing_pipe' could not be found in bundle spec"):- PipelexBundleSpec(domain="test_domain", main_pipe="missing_pipe", pipe={"write_text": make_llm_spec()})-- @pytest.mark.parametrize("empty_pipes", [{}, None])- def test_main_pipe_with_no_pipes_rejected(self, empty_pipes: dict[str, Any] | None) -> None:- """A main_pipe declared while the pipe dict is empty or None is rejected."""- with pytest.raises(ValidationError, match="Main pipe 'write_text' could not be found in bundle spec"):- PipelexBundleSpec(domain="test_domain", main_pipe="write_text", pipe=empty_pipes)-- def test_valid_spec_constructs(self) -> None:- """A well-formed spec constructs and exposes its declared fields."""- bundle_spec = PipelexBundleSpec(- domain="test_domain",- description="A test bundle",- system_prompt="You are concise",- main_pipe="write_text",- pipe={"write_text": make_llm_spec()},- )-- assert bundle_spec.domain == "test_domain"- assert bundle_spec.description == "A test bundle"- assert bundle_spec.system_prompt == "You are concise"- assert bundle_spec.main_pipe == "write_text"- assert bundle_spec.pipe is not None- assert list(bundle_spec.pipe.keys()) == ["write_text"]- assert bundle_spec.pipe["write_text"].description == "Generate text for write_text"- assert bundle_spec.concept == {}diff --git a/tests/unit/pipelex/builder/test_runner_generator.py b/tests/unit/pipelex/builder/test_runner_generator.pydeleted file mode 100644index 42bbf4539..000000000--- a/tests/unit/pipelex/builder/test_runner_generator.py+++ /dev/null@@ -1,362 +0,0 @@-"""Unit tests for runner_code module."""--from __future__ import annotations--import json-from typing import TYPE_CHECKING, Any, cast--import pytest--from pipelex.builder.runner_code import generate_runner_code-from pipelex.core.concepts.concept_factory import ConceptFactory-from pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormat-from pipelex.core.concepts.native.concept_native import NativeConceptCode-from pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecs-from pipelex.core.pipes.stuff_spec.stuff_spec import StuffSpec-from pipelex.libraries.concept.concept_library import ConceptLibrary--if TYPE_CHECKING:- from pytest_mock import MockerFixture, MockType---class TestConceptGenerateInputRepresentationJson:- """Test Concept.render_concept_representation for JSON format."""-- def test_native_text_json(self) -> None:- """Test JSON representation for native Text concept."""- concept = ConceptFactory.make_native_concept(NativeConceptCode.TEXT)- result, _ = concept.render_concept_representation(- structure_class=ConceptLibrary.make_empty().get_structure_class(concept=concept), output_format=ConceptRepresentationFormat.JSON- )- assert result["concept"] == "native.Text"- assert "content" in result- assert "text" in result["content"]-- def test_native_image_json(self) -> None:- """Test JSON representation for native Image concept."""- concept = ConceptFactory.make_native_concept(NativeConceptCode.IMAGE)- result, _ = concept.render_concept_representation(- structure_class=ConceptLibrary.make_empty().get_structure_class(concept=concept), output_format=ConceptRepresentationFormat.JSON- )- assert result["concept"] == "native.Image"- assert "content" in result- assert "url" in result["content"]-- def test_native_number_json(self) -> None:- """Test JSON representation for native Number concept."""- concept = ConceptFactory.make_native_concept(NativeConceptCode.NUMBER)- result, _ = concept.render_concept_representation(- structure_class=ConceptLibrary.make_empty().get_structure_class(concept=concept), output_format=ConceptRepresentationFormat.JSON- )- assert result["concept"] == "native.Number"- assert "content" in result- assert "number" in result["content"]-- def test_native_document_json_with_multiplicity(self) -> None:- """Test JSON representation for Document with multiplicity - content should be a list."""- concept = ConceptFactory.make_native_concept(NativeConceptCode.DOCUMENT)- result, _ = concept.render_concept_representation(- structure_class=ConceptLibrary.make_empty().get_structure_class(concept=concept),- output_format=ConceptRepresentationFormat.JSON,- multiplicity=True,- )- assert result["concept"] == "native.Document"- assert "content" in result- # Content should be a list- content = cast("list[dict[str, Any]]", result["content"])- assert isinstance(content, list)- assert len(content) == 1- assert "url" in content[0]---class TestConceptGenerateInputRepresentationPython:- """Test Concept.render_concept_representation for Python format."""-- def test_native_text_python(self) -> None:- """Test Python representation for native Text concept."""- concept = ConceptFactory.make_native_concept(NativeConceptCode.TEXT)- result, imports = concept.render_concept_representation(- structure_class=ConceptLibrary.make_empty().get_structure_class(concept=concept), output_format=ConceptRepresentationFormat.PYTHON- )- assert result["concept"] == "native.Text"- assert "TextContent" in result["content"]- assert "TextContent" in imports-- def test_native_image_python(self) -> None:- """Test Python representation for native Image concept."""- concept = ConceptFactory.make_native_concept(NativeConceptCode.IMAGE)- result, imports = concept.render_concept_representation(- structure_class=ConceptLibrary.make_empty().get_structure_class(concept=concept), output_format=ConceptRepresentationFormat.PYTHON- )- assert result["concept"] == "native.Image"- assert "ImageContent" in result["content"]- assert "ImageContent" in imports-- def test_refined_text_python(self) -> None:- """Test Python representation for a concept that refines Text."""- concept = ConceptFactory.make(- domain_code="test_domain",- concept_code="Question",- description="A question",- structure_class_name="TextContent",- refines="native.Text",- )- result, imports = concept.render_concept_representation(- structure_class=ConceptLibrary.make_empty().get_structure_class(concept=concept), output_format=ConceptRepresentationFormat.PYTHON- )- assert result["concept"] == "test_domain.Question"- assert "TextContent" in result["content"]- assert "TextContent" in imports-- def test_native_document_python_with_multiplicity(self) -> None:- """Test Python representation for Document with multiplicity - for Python format, wrapping is handled by caller."""- concept = ConceptFactory.make_native_concept(NativeConceptCode.DOCUMENT)- result, imports = concept.render_concept_representation(- structure_class=ConceptLibrary.make_empty().get_structure_class(concept=concept),- output_format=ConceptRepresentationFormat.PYTHON,- multiplicity=True,- )- # For Python format, a multiple multiplicity doesn't wrap content (caller handles it)- assert result["concept"] == "native.Document"- assert "DocumentContent" in result["content"]- assert "DocumentContent" in imports---class TestInputStuffSpecsRenderInputsRepresentation:- """Test InputStuffSpecs.render_inputs method."""-- def test_empty_inputs(self) -> None:- """Test JSON generation with no inputs."""- inputs = InputStuffSpecs(root={})- result = json.loads(inputs.render_inputs(concept_provider=ConceptLibrary.make_empty()))- assert result == {}-- def test_single_input(self) -> None:- """Test JSON generation with a single input."""- concept = ConceptFactory.make_native_concept(NativeConceptCode.TEXT)- inputs = InputStuffSpecs(root={"message": StuffSpec(concept=concept)})- result = json.loads(inputs.render_inputs(concept_provider=ConceptLibrary.make_empty()))- assert "message" in result- assert result["message"]["concept"] == "native.Text"-- def test_multiple_inputs(self) -> None:- """Test JSON generation with multiple inputs."""- text_concept = ConceptFactory.make_native_concept(NativeConceptCode.TEXT)- image_concept = ConceptFactory.make_native_concept(NativeConceptCode.IMAGE)- inputs = InputStuffSpecs(- root={- "text_input": StuffSpec(concept=text_concept),- "image_input": StuffSpec(concept=image_concept),- }- )- result = json.loads(inputs.render_inputs(concept_provider=ConceptLibrary.make_empty()))- assert "text_input" in result- assert "image_input" in result- assert result["text_input"]["concept"] == "native.Text"- assert result["image_input"]["concept"] == "native.Image"---class TestInputStuffSpecsRenderWithMultiplicity:- """Test InputStuffSpecs.render_inputs with multiplicity - content is wrapped in list."""-- def test_single_item_no_multiplicity(self) -> None:- """Test that single item (no multiplicity) has content as dict, not list."""- concept = ConceptFactory.make_native_concept(NativeConceptCode.DOCUMENT)- inputs = InputStuffSpecs(root={"document": StuffSpec(concept=concept, multiplicity=None)})- result = json.loads(inputs.render_inputs(concept_provider=ConceptLibrary.make_empty()))- assert "document" in result- # concept should be present- assert result["document"]["concept"] == "native.Document"- # content should NOT be a list- content = result["document"]["content"]- assert isinstance(content, dict)- assert "url" in content-- def test_multiple_items_true_multiplicity(self) -> None:- """Test that multiplicity=True wraps content in list."""- concept = ConceptFactory.make_native_concept(NativeConceptCode.DOCUMENT)- inputs = InputStuffSpecs(root={"documents": StuffSpec(concept=concept, multiplicity=True)})- result = json.loads(inputs.render_inputs(concept_provider=ConceptLibrary.make_empty()))- assert "documents" in result- # concept should be at the top level- assert result["documents"]["concept"] == "native.Document"- # content should be a list- content = cast("list[dict[str, Any]]", result["documents"]["content"])- assert isinstance(content, list)- assert len(content) == 1- assert "url" in content[0]-- def test_multiple_items_int_multiplicity(self) -> None:- """Test that multiplicity=N (int > 1) wraps content in list."""- concept = ConceptFactory.make_native_concept(NativeConceptCode.IMAGE)- inputs = InputStuffSpecs(root={"images": StuffSpec(concept=concept, multiplicity=3)})- result = json.loads(inputs.render_inputs(concept_provider=ConceptLibrary.make_empty()))- assert "images" in result- # concept should be at the top level- assert result["images"]["concept"] == "native.Image"- # content should be a list- content = cast("list[dict[str, Any]]", result["images"]["content"])- assert isinstance(content, list)- assert len(content) == 1- assert "url" in content[0]-- def test_mixed_multiplicity(self) -> None:- """Test mixed single and multiple inputs."""- document_concept = ConceptFactory.make_native_concept(NativeConceptCode.DOCUMENT)- inputs = InputStuffSpecs(- root={- "single_document": StuffSpec(concept=document_concept, multiplicity=None),- "multiple_documents": StuffSpec(concept=document_concept, multiplicity=True),- }- )- result = json.loads(inputs.render_inputs(concept_provider=ConceptLibrary.make_empty()))- # single_document content should be a dict- assert isinstance(result["single_document"]["content"], dict)- # multiple_documents content should be a list- assert isinstance(result["multiple_documents"]["content"], list)---class TestGenerateRunnerCode:- """Test generate_runner_code function."""-- @pytest.fixture(autouse=True)- def stub_concept_library(self, mocker: MockerFixture) -> None:- """The generator resolves structure classes through the loaded method's library.-- These tests drive it with mock pipes rather than a loaded method, so an empty- `ConceptLibrary` stands in: it holds no concepts but resolves any class the process- registry already has, which is all the code generation needs.- """- mocker.patch("pipelex.builder.runner_code.get_concept_library", return_value=ConceptLibrary.make_empty())-- @pytest.fixture- def mock_pipe_single_output(self, mocker: MockerFixture) -> MockType:- """Create a mock pipe with a single output."""- text_concept = ConceptFactory.make_native_concept(NativeConceptCode.TEXT)- document_concept = ConceptFactory.make_native_concept(NativeConceptCode.DOCUMENT)-- mock_pipe: MockType = mocker.MagicMock()- mock_pipe.code = "test_pipe"- mock_pipe.output = StuffSpec(concept=text_concept)- mock_pipe.inputs = InputStuffSpecs(root={"document": StuffSpec(concept=document_concept)})- return mock_pipe-- @pytest.fixture- def mock_pipe_list_output(self, mocker: MockerFixture) -> MockType:- """Create a mock pipe with a list output."""- text_concept = ConceptFactory.make_native_concept(NativeConceptCode.TEXT)- document_concept = ConceptFactory.make_native_concept(NativeConceptCode.DOCUMENT)-- mock_pipe: MockType = mocker.MagicMock()- mock_pipe.code = "test_pipe_list"- mock_pipe.output = StuffSpec(concept=text_concept)- mock_pipe.inputs = InputStuffSpecs(root={"documents": StuffSpec(concept=document_concept, multiplicity=True)})- return mock_pipe-- def test_runner_code_includes_imports(self, mock_pipe_single_output: MockType) -> None:- """Test that generated runner code includes necessary imports."""- runner_code = generate_runner_code(mock_pipe_single_output)- assert "import asyncio" in runner_code- assert "from pipelex.pipelex import Pipelex" in runner_code- assert "from pipelex.pipeline.runner import PipelexMTHDSProtocol" in runner_code-- def test_runner_code_includes_structure_imports(self, mock_pipe_single_output: MockType) -> None:- """Test that generated runner code includes structure class imports."""- runner_code = generate_runner_code(mock_pipe_single_output)- assert "from pipelex.core.stuffs.document_content import DocumentContent" in runner_code- assert "from pipelex.core.stuffs.text_content import TextContent" in runner_code-- def test_runner_code_single_output_return_type(self, mock_pipe_single_output: MockType) -> None:- """Test that generated runner code has correct return type for single output."""- runner_code = generate_runner_code(mock_pipe_single_output, output_multiplicity=False)- assert "async def run_test_pipe() -> TextContent:" in runner_code- assert "pipe_output.main_stuff_as(content_type=TextContent)" in runner_code-- def test_runner_code_list_output_return_type(self, mock_pipe_list_output: MockType) -> None:- """Test that generated runner code has correct return type for list output."""- runner_code = generate_runner_code(mock_pipe_list_output, output_multiplicity=True)- assert "async def run_test_pipe_list() -> list[TextContent]:" in runner_code- assert "pipe_output.main_stuff_as_items(item_type=TextContent)" in runner_code-- def test_runner_code_includes_inputs(self, mock_pipe_single_output: MockType) -> None:- """Test that generated runner code includes input values."""- runner_code = generate_runner_code(mock_pipe_single_output)- assert '"document":' in runner_code- assert '"concept": "native.Document"' in runner_code- assert "DocumentContent(" in runner_code-- def test_runner_code_includes_main_block(self, mock_pipe_single_output: MockType) -> None:- """Test that generated runner code includes main block."""- runner_code = generate_runner_code(mock_pipe_single_output)- assert 'if __name__ == "__main__":' in runner_code- assert "Pipelex.make()" in runner_code- assert "asyncio.run(run_test_pipe())" in runner_code-- def test_runner_code_multiplicity_input(self, mock_pipe_list_output: MockType) -> None:- """Test that generated runner code handles input multiplicity correctly."""- runner_code = generate_runner_code(mock_pipe_list_output)- # Should have list-wrapped content for multiplicity input- assert "[DocumentContent(" in runner_code-- def test_runner_code_custom_class_import_format(self, mocker: MockerFixture) -> None:- """Custom classes import from the single-module types projection (structures/structures.py)."""- # Create a custom concept (non-native)- custom_concept = ConceptFactory.make(- domain_code="test_domain",- concept_code="CustomOutput",- description="A custom output",- structure_class_name="CustomOutput",- )- document_concept = ConceptFactory.make_native_concept(NativeConceptCode.DOCUMENT)-- mock_pipe = mocker.MagicMock()- mock_pipe.code = "custom_pipe"- mock_pipe.output = StuffSpec(concept=custom_concept)- mock_pipe.inputs = InputStuffSpecs(root={"document": StuffSpec(concept=document_concept)})-- runner_code = generate_runner_code(mock_pipe)- # Custom imports come from the emitted single module; NOT a relative import (standalone script)- assert "from structures.structures import CustomOutput" in runner_code- assert "from .structures" not in runner_code-- def test_runner_code_class_name_overrides_spell_emitted_names(self, mocker: MockerFixture) -> None:- """The overrides map re-spells runtime-qualified class names to the emitted (bare) names."""- custom_concept = ConceptFactory.make(- domain_code="test_domain",- concept_code="CustomOutput",- description="A custom output",- structure_class_name="test_domain__CustomOutput",- )- text_concept = ConceptFactory.make_native_concept(NativeConceptCode.TEXT)-- mock_pipe = mocker.MagicMock()- mock_pipe.code = "custom_pipe"- mock_pipe.output = StuffSpec(concept=custom_concept)- mock_pipe.inputs = InputStuffSpecs(root={"message": StuffSpec(concept=text_concept)})-- runner_code = generate_runner_code(mock_pipe, class_name_overrides={"test_domain__CustomOutput": "CustomOutput"})- assert "from structures.structures import CustomOutput" in runner_code- assert "async def run_custom_pipe() -> CustomOutput:" in runner_code- assert "pipe_output.main_stuff_as(content_type=CustomOutput)" in runner_code- assert "test_domain__CustomOutput" not in runner_code-- def test_runner_code_anything_output_uses_any_return_type(self, mocker: MockerFixture) -> None:- """Test that Anything output concept uses Any return type and main_stuff instead of main_stuff_as."""- anything_concept = ConceptFactory.make_native_concept(NativeConceptCode.ANYTHING)- text_concept = ConceptFactory.make_native_concept(NativeConceptCode.TEXT)-- mock_pipe = mocker.MagicMock()- mock_pipe.code = "anything_output_pipe"- mock_pipe.output = StuffSpec(concept=anything_concept)- mock_pipe.inputs = InputStuffSpecs(root={"message": StuffSpec(concept=text_concept)})-- runner_code = generate_runner_code(mock_pipe)- # Should use Any as return type, not AnythingContent- assert "async def run_anything_output_pipe() -> Any:" in runner_code- # Should use main_stuff, not main_stuff_as- assert "pipe_output.main_stuff" in runner_code- assert "main_stuff_as(content_type=" not in runner_code- # Should NOT import AnythingContent (it doesn't exist)- assert "AnythingContent" not in runner_code- # Should import Any from typing- assert "from typing import Any" in runner_codediff --git a/tests/unit/pipelex/cli/agent_cli/commands/test_bundle_path_resolver.py b/tests/unit/pipelex/cli/agent_cli/commands/test_bundle_path_resolver.pyindex 5a0409b3e..37ad72ec2 100644--- a/tests/unit/pipelex/cli/agent_cli/commands/test_bundle_path_resolver.py+++ b/tests/unit/pipelex/cli/agent_cli/commands/test_bundle_path_resolver.py@@ -10,9 +10,9 @@ from pathlib import Pathimport pytestimport typer-from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, set_agent_cli_error_formatfrom pipelex.cli.agent_cli.commands.bundle_path_resolver import resolve_bundle_target+from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAMEclass TestResolveBundleTarget:diff --git a/tests/unit/pipelex/cli/commands/build/test_runner_core.py b/tests/unit/pipelex/cli/commands/build/test_runner_core.pydeleted file mode 100644index 6745e28e6..000000000--- a/tests/unit/pipelex/cli/commands/build/test_runner_core.py+++ /dev/null@@ -1,142 +0,0 @@-"""Unit tests for the `pipelex build runner` core logic (_prepare_runner_core).--The library plumbing and the codegen engine seams are mocked at the module namespace, so these-tests pin the runner-core wiring (pipe selection, output paths, the structures projection hand-off,-and the exit codes), not the engine itself (covered by the codegen unit tests).-"""--from __future__ import annotations--import asyncio-from types import SimpleNamespace-from typing import TYPE_CHECKING, Any--import pytest-import typer--from pipelex.cli.commands.build.runner._runner_core import (- _prepare_runner_core, # pyright: ignore[reportPrivateUsage]-)-from pipelex.pipeline.exceptions import ValidateBundleError--if TYPE_CHECKING:- from pathlib import Path-- from pytest_mock import MockerFixture--MODULE = "pipelex.cli.commands.build.runner._runner_core"---class TestPrepareRunnerCore:- @pytest.fixture- def core_mocks(self, mocker: MockerFixture) -> dict[str, Any]:- """Stub library plumbing, the codegen engine seams, and runner codegen."""- library_manager = mocker.MagicMock()- library_manager.get_crate.return_value = None # default: no crate -> no structures projection- mocker.patch(f"{MODULE}.get_library_manager", return_value=library_manager)- mocker.patch(f"{MODULE}.get_current_library_id_or_none", return_value="lib_id")- blueprint = SimpleNamespace(main_pipe="bundle_main", pipe=None)- validate_result = SimpleNamespace(blueprints=[blueprint])- return {- "library_manager": library_manager,- "validate_bundle": mocker.patch(f"{MODULE}.validate_bundle", new=mocker.AsyncMock(return_value=validate_result)),- "get_required_entry_pipe": mocker.patch(f"{MODULE}.get_required_entry_pipe", return_value=SimpleNamespace(code="bundle_main")),- "normalize_crate": mocker.patch(f"{MODULE}.normalize_crate"),- "emit_types": mocker.patch(f"{MODULE}.emit_types", return_value=[]),- "write_stamped_projection": mocker.patch(- f"{MODULE}.write_stamped_projection",- return_value=SimpleNamespace(written=["structures.py"], unchanged=[], removed=[]),- ),- "resolve_concepts": mocker.patch(f"{MODULE}.resolve_concepts_from_crate"),- "runtime_to_emitted": mocker.patch(f"{MODULE}.runtime_to_emitted_class_names", return_value={"demo__Invoice": "Invoice"}),- "generate_runner_code": mocker.patch(f"{MODULE}.generate_runner_code", return_value="# runner code\n"),- }-- def test_bundle_main_pipe_writes_runner_next_to_bundle(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:- """Without --pipe, the bundle's main_pipe names the default run_<pipe>.py file."""- asyncio.run(_prepare_runner_core(pipe_code=None, bundle_path=tmp_path / "demo.mthds"))-- core_mocks["get_required_entry_pipe"].assert_called_once_with(pipe_code="bundle_main")- runner_file = tmp_path / "run_bundle_main.py"- assert runner_file.read_text(encoding="utf-8") == "# runner code\n"- codegen_kwargs = core_mocks["generate_runner_code"].call_args.kwargs- assert codegen_kwargs["output_multiplicity"] is False- assert codegen_kwargs["library_dir"] == str(tmp_path.resolve())-- def test_structures_projection_emitted_into_structures_dir(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:- """With a crate available, the types projection is written into structures/ next to the- runner and the emitted-name mapping is handed to the runner-code generator.- """- core_mocks["library_manager"].get_crate.return_value = SimpleNamespace()-- asyncio.run(_prepare_runner_core(pipe_code=None, bundle_path=tmp_path / "demo.mthds"))-- write_kwargs = core_mocks["write_stamped_projection"].call_args.kwargs- assert write_kwargs["output_dir"] == tmp_path / "structures"- codegen_kwargs = core_mocks["generate_runner_code"].call_args.kwargs- assert codegen_kwargs["class_name_overrides"] == {"demo__Invoice": "Invoice"}-- def test_no_crate_skips_structures_projection(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:- """Without a crate (nothing loaded), the runner is still generated with no overrides."""- asyncio.run(_prepare_runner_core(pipe_code=None, bundle_path=tmp_path / "demo.mthds"))-- core_mocks["write_stamped_projection"].assert_not_called()- codegen_kwargs = core_mocks["generate_runner_code"].call_args.kwargs- assert codegen_kwargs["class_name_overrides"] == {}-- @pytest.mark.usefixtures("core_mocks")- def test_explicit_output_path_wins(self, tmp_path: Path) -> None:- """An explicit output path is used verbatim for the runner file."""- target_path = tmp_path / "generated" / "my_runner.py"-- asyncio.run(_prepare_runner_core(pipe_code="my_pipe", bundle_path=tmp_path / "demo.mthds", output_path=target_path))-- assert target_path.read_text(encoding="utf-8") == "# runner code\n"-- def test_output_multiplicity_detected_from_pipe_blueprint(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:- """A pipe whose output declares a multiplicity generates a list-aware runner."""- blueprint = SimpleNamespace(- main_pipe="bundle_main",- pipe={"bundle_main": SimpleNamespace(output="Invoice[]")},- )- core_mocks["validate_bundle"].return_value = SimpleNamespace(blueprints=[blueprint])-- asyncio.run(_prepare_runner_core(pipe_code=None, bundle_path=tmp_path / "demo.mthds"))-- codegen_kwargs = core_mocks["generate_runner_code"].call_args.kwargs- assert codegen_kwargs["output_multiplicity"] is True-- @pytest.mark.usefixtures("core_mocks")- def test_no_bundle_exits(self) -> None:- """The runner build requires a bundle file."""- with pytest.raises(typer.Exit) as exc_info:- asyncio.run(_prepare_runner_core(pipe_code="my_pipe", bundle_path=None))-- assert exc_info.value.exit_code == 1-- def test_bundle_without_main_pipe_exits(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:- """A bundle without main_pipe and no --pipe is an error."""- core_mocks["validate_bundle"].return_value = SimpleNamespace(blueprints=[SimpleNamespace(main_pipe=None, pipe=None)])-- with pytest.raises(typer.Exit) as exc_info:- asyncio.run(_prepare_runner_core(pipe_code=None, bundle_path=tmp_path / "demo.mthds"))-- assert exc_info.value.exit_code == 1-- def test_validate_bundle_error_exits(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:- """A bundle validation failure exits 1."""- core_mocks["validate_bundle"].side_effect = ValidateBundleError("broken bundle")-- with pytest.raises(typer.Exit) as exc_info:- asyncio.run(_prepare_runner_core(pipe_code=None, bundle_path=tmp_path / "demo.mthds"))-- assert exc_info.value.exit_code == 1-- def test_runner_codegen_failure_exits(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:- """A failure while generating runner code exits 1."""- core_mocks["generate_runner_code"].side_effect = RuntimeError("codegen exploded")-- with pytest.raises(typer.Exit) as exc_info:- asyncio.run(_prepare_runner_core(pipe_code=None, bundle_path=tmp_path / "demo.mthds"))-- assert exc_info.value.exit_code == 1diff --git a/tests/unit/pipelex/cli/commands/test_bundle_path_resolver.py b/tests/unit/pipelex/cli/commands/test_bundle_path_resolver.pyindex 55545087b..dba23a369 100644--- a/tests/unit/pipelex/cli/commands/test_bundle_path_resolver.py+++ b/tests/unit/pipelex/cli/commands/test_bundle_path_resolver.py@@ -12,8 +12,8 @@ from typing import TYPE_CHECKINGimport pytestimport typer-from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.cli.commands.bundle_path_resolver import resolve_bundle_target+from pipelex.pipeline.default_file_names import DEFAULT_BUNDLE_FILE_NAMEif TYPE_CHECKING:from pathlib import Pathdiff --git a/tests/unit/pipelex/cli/test_agent_models_cmd.py b/tests/unit/pipelex/cli/test_agent_models_cmd.pyindex 91f45c2a8..a777ff49e 100644--- a/tests/unit/pipelex/cli/test_agent_models_cmd.py+++ b/tests/unit/pipelex/cli/test_agent_models_cmd.py@@ -9,13 +9,13 @@ if TYPE_CHECKING:import pytestfrom pytest_mock import MockerFixture-from pipelex.builder.operations.models_ops import ModelCategoryfrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormatfrom pipelex.cli.agent_cli.commands.models_cmd import agent_models_cmdfrom pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.models.model_listing import ModelCategoryCMD_MODULE_PATH = "pipelex.cli.agent_cli.commands.models_cmd"-OPS_MODULE_PATH = "pipelex.builder.operations.models_ops"+OPS_MODULE_PATH = "pipelex.cogt.models.model_listing"class _FakeSetting:diff --git a/tests/unit/pipelex/cli/test_agent_output.py b/tests/unit/pipelex/cli/test_agent_output.pyindex 863f5135e..d8a7555cd 100644--- a/tests/unit/pipelex/cli/test_agent_output.py+++ b/tests/unit/pipelex/cli/test_agent_output.py@@ -42,6 +42,8 @@ from pipelex.system.pipe_run_mode import PipeRunModeif TYPE_CHECKING:from collections.abc import Iterator+ from pytest_mock import MockerFixture+class TestAgentOutput:"""Tests for agent_error, agent_success, and extract_validation_errors."""@@ -440,21 +442,22 @@ class TestAgentOutput:parsed = json.loads(capsys.readouterr().err)assert parsed["error_domain"] == "input"- def test_app_callback_resets_error_format_to_json(self) -> None:+ def test_app_callback_resets_error_format_to_json(self, mocker: MockerFixture) -> None:"""The error-format ContextVar must be reset per invocation: a markdown command leavingit set must not leak markdown into a later JSON-only command in the same process."""# Simulate a prior markdown command having left the ContextVar set.set_agent_cli_error_format(CliOutputFormat.MARKDOWN)+ mocker.patch("pipelex.cli.agent_cli.commands.plxt_passthrough.shutil.which", return_value=None)- # `concept` is a JSON-only command with no --format / --error-format option; invoked with no spec it- # errors via agent_error(). Its error must be JSON, proving the callback reset the format.- result = CliRunner().invoke(app, ["concept"])+ # `fmt` is a JSON-only command with no --format / --error-format option; with no plxt binary on the+ # path it errors via agent_error(). Its error must be JSON, proving the callback reset the format.+ result = CliRunner().invoke(app, ["fmt", "bundle.mthds"])assert result.exit_code == 1parsed = json.loads(result.stderr)assert parsed["error"] is True- assert parsed["error_type"] == "ArgumentError"+ assert parsed["error_type"] == "BinaryNotFoundError"# -------------------------------------------------------------------------# Setup-warnings buffer tests (record_setup_warning / consume_setup_warningsdiff --git a/tests/unit/pipelex/cli/test_build_runner_method_materialization.py b/tests/unit/pipelex/cli/test_build_runner_method_materialization.pydeleted file mode 100644index c06aae5a7..000000000--- a/tests/unit/pipelex/cli/test_build_runner_method_materialization.py+++ /dev/null@@ -1,78 +0,0 @@-"""Unit tests: `build runner method` on a fetched target embeds only paths that survive process exit."""--from __future__ import annotations--from typing import TYPE_CHECKING, Any--from pipelex.cli.commands.build.runner.method_cmd import build_runner_method_cmd--if TYPE_CHECKING:- from pathlib import Path-- from pytest_mock import MockerFixture--RUNNER_METHOD_MODULE = "pipelex.cli.commands.build.runner.method_cmd"---class TestBuildRunnerMethodMaterialization:- """The generated runner embeds its library dir — for a fetched target that dir must outlive the clone."""-- def _patch_method(self, mocker: MockerFixture, *, method_dir: Path, fetched: bool) -> Any:- """Create a real method package at *method_dir*, patch resolution; return the execute_prepare_runner mock."""- method_dir.mkdir(parents=True, exist_ok=True)- bundle_file = method_dir / "core.mthds"- bundle_file.write_text("# placeholder", encoding="utf-8")-- method_mock = mocker.MagicMock()- method_mock.name = "remote_method"- method_mock.path = method_dir- method_mock.mthds_files = [bundle_file]- method_mock.provenance = mocker.MagicMock() if fetched else None- mocker.patch(- f"{RUNNER_METHOD_MODULE}.resolve_method_target",- return_value=("my_pipe", [str(method_dir)], method_mock),- )- return mocker.patch(f"{RUNNER_METHOD_MODULE}.execute_prepare_runner")-- def test_fetched_method_is_materialized_beside_the_script(self, mocker: MockerFixture, tmp_path: Path) -> None:- """A fetched target's package is copied beside the generated runner, and only the copy is referenced."""- clone_dir = tmp_path / "mthds_remote_clone"- prepare_mock = self._patch_method(mocker, method_dir=clone_dir, fetched=True)- output_file = tmp_path / "out" / "run_my_pipe.py"-- build_runner_method_cmd(name="github.com/test/remote-method", output_path=str(output_file))-- materialized_dir = output_file.parent / "remote_method"- assert (materialized_dir / "core.mthds").is_file()- kwargs = prepare_mock.call_args.kwargs- assert kwargs["bundle_path"] == materialized_dir / "core.mthds"- assert kwargs["library_dirs"] == [materialized_dir]- assert not kwargs["bundle_path"].is_relative_to(clone_dir)- assert not kwargs["library_dirs"][0].is_relative_to(clone_dir)-- def test_fetched_materialization_excludes_git_metadata(self, mocker: MockerFixture, tmp_path: Path) -> None:- """The clone's .git directory is not copied into the materialized package."""- clone_dir = tmp_path / "mthds_remote_clone"- self._patch_method(mocker, method_dir=clone_dir, fetched=True)- (clone_dir / ".git").mkdir()- (clone_dir / ".git" / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")- output_file = tmp_path / "out" / "run_my_pipe.py"-- build_runner_method_cmd(name="github.com/test/remote-method", output_path=str(output_file))-- materialized_dir = output_file.parent / "remote_method"- assert (materialized_dir / "core.mthds").is_file()- assert not (materialized_dir / ".git").exists()-- def test_installed_method_is_not_copied(self, mocker: MockerFixture, tmp_path: Path) -> None:- """An installed method (no provenance) is referenced in place — no copy is made."""- method_dir = tmp_path / "installed-method"- prepare_mock = self._patch_method(mocker, method_dir=method_dir, fetched=False)- output_file = tmp_path / "out" / "run_my_pipe.py"-- build_runner_method_cmd(name="my-method", output_path=str(output_file))-- kwargs = prepare_mock.call_args.kwargs- assert kwargs["bundle_path"] == method_dir / "core.mthds"- assert kwargs["library_dirs"] == [method_dir]- assert not (output_file.parent / "remote_method").exists()diff --git a/tests/unit/pipelex/cli/test_check_model_cmd.py b/tests/unit/pipelex/cli/test_check_model_cmd.pyindex 897adb24d..b2455d2fd 100644--- a/tests/unit/pipelex/cli/test_check_model_cmd.py+++ b/tests/unit/pipelex/cli/test_check_model_cmd.py@@ -9,10 +9,10 @@ if TYPE_CHECKING:import pytestfrom pytest_mock import MockerFixture-from pipelex.builder.operations.models_ops import ModelCategoryfrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormatfrom pipelex.cli.agent_cli.commands.check_model_cmd import agent_check_model_cmdfrom pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.models.model_listing import ModelCategoryMODULE_PATH = "pipelex.cli.agent_cli.commands.check_model_cmd"diff --git a/tests/unit/pipelex/cli/test_format_models_markdown.py b/tests/unit/pipelex/cli/test_format_models_markdown.pyindex 681caf61d..145370796 100644--- a/tests/unit/pipelex/cli/test_format_models_markdown.py+++ b/tests/unit/pipelex/cli/test_format_models_markdown.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom typing import Any, ClassVar-from pipelex.builder.operations.models_ops import format_models_markdown+from pipelex.cogt.models.model_listing import format_models_markdownclass TestFormatModelsMarkdown:diff --git a/tests/unit/pipelex/cli/test_pipe_cmd.py b/tests/unit/pipelex/cli/test_pipe_cmd.pydeleted file mode 100644index 181e545a8..000000000--- a/tests/unit/pipelex/cli/test_pipe_cmd.py+++ /dev/null@@ -1,293 +0,0 @@-"""Unit tests for the agent CLI pipe command — CLI-specific behavior.--parse_pipe_spec tolerance tests (aliases, output dict, etc.) live in-tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py.-pipe_spec_to_toml tests live in tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py.-This file tests CLI-layer concerns: TOML serialization (_pipe_spec_to_toml which uses format_toml_string)-and integration of parse_pipe_spec with the CLI output path.-"""--from __future__ import annotations--import json-from typing import Any, ClassVar--import pytest-import typer--from pipelex.builder.operations.pipe_ops import parse_pipe_spec-from pipelex.cli.agent_cli.commands.pipe_cmd import (- _pipe_spec_to_toml, # pyright: ignore[reportPrivateUsage]- pipe_cmd,-)---class TestCliPipeCmd:- """CLI-specific tests: pipe_type extraction from JSON and CLI TOML serialization."""-- _BASE_LLM: ClassVar[dict[str, Any]] = {- "pipe_code": "my_llm_pipe",- "description": "Test LLM pipe",- "model": "$writing-creative",- "inputs": {"text": "Text"},- "output": "Text",- "prompt": "Write about $text",- }-- # -- pipe_type alias in JSON (handled by pipe_cmd, not parse_pipe_spec) ---- def test_type_extracted_from_spec(self) -> None:- """When type is in the spec dict it should be used (and popped)."""- spec: dict[str, Any] = {- "type": "PipeLLM",- "pipe_code": "test",- "description": "Test",- "model": "$writing-creative",- "inputs": {"text": "Text"},- "output": "Text",- "prompt": "Write about $text",- }- pipe_type = spec.pop("type")- result = parse_pipe_spec(spec, pipe_type=pipe_type)- assert result.pipe_code == "test"-- def test_typeless_spec_renders_signature_without_type_line(self) -> None:- """No type resolved (typeless) → a signature; the CLI TOML omits the `type` line entirely."""- spec = parse_pipe_spec(- {"pipe_code": "summarize_doc", "description": "Summarize a doc.", "inputs": {"doc": "Document"}, "output": "Text"},- pipe_type=None,- )- toml = _pipe_spec_to_toml(spec)- assert "[pipe.summarize_doc]" in toml- assert "type =" not in toml-- def test_explicit_null_type_rejected(self, capsys: pytest.CaptureFixture[str]) -> None:- """An explicit `"type": null` in the JSON spec is rejected — a signature is authored by omitting- the `type` key, not by nulling it (teaching-consistent with the explicit-tag rejection). Present- null must not silently collapse to a typeless signature.- """- spec = json.dumps({"pipe_code": "summarize_doc", "description": "d", "inputs": {"doc": "Document"}, "output": "Text", "type": None})- with pytest.raises(typer.Exit):- pipe_cmd(spec=spec)- captured = capsys.readouterr()- combined = captured.err + captured.out- assert "ArgumentError" in combined- assert "type" in combined-- def test_non_string_type_rejected_with_actionable_error(self, capsys: pytest.CaptureFixture[str]) -> None:- """A non-string JSON `type` (e.g. a list/dict — unhashable) must surface as an actionable- ArgumentError naming the valid types, never a cryptic internal `TypeError: unhashable type`- leaking from the membership test inside parse_pipe_spec.- """- spec = json.dumps({"pipe_code": "x", "description": "d", "inputs": {"doc": "Document"}, "output": "Text", "type": ["PipeCompose"]})- with pytest.raises(typer.Exit):- pipe_cmd(spec=spec)- captured = capsys.readouterr()- combined = captured.err + captured.out- assert "ArgumentError" in combined- assert "TypeError" not in combined- assert "Invalid pipe type" in combined-- # -- CLI TOML serialization (uses format_toml_string) ------------------- def test_llm_model_appears_in_toml(self) -> None:- spec = parse_pipe_spec({**self._BASE_LLM}, pipe_type="PipeLLM")- toml = _pipe_spec_to_toml(spec)- assert 'model = "$writing-creative"' in toml-- def test_llm_different_model_in_toml(self) -> None:- spec = parse_pipe_spec({**self._BASE_LLM, "model": "$engineering-structured"}, pipe_type="PipeLLM")- toml = _pipe_spec_to_toml(spec)- assert 'model = "$engineering-structured"' in toml-- def test_extract_model_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "my_extract",- "description": "Extract pipe",- "inputs": {"doc": "Document"},- "output": "Page[]",- "model": "@default-extract-document",- },- pipe_type="PipeExtract",- )- toml = _pipe_spec_to_toml(spec)- assert 'model = "@default-extract-document"' in toml-- def test_doc_gen_model_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "print_invoice",- "description": "Print the invoice",- "inputs": {"invoice": "Invoice"},- "output": "Document",- "format": "pdf",- "model": "reportlab-pdf",- "filename": "invoice.pdf",- },- pipe_type="PipeDocGen",- )- toml = _pipe_spec_to_toml(spec)- assert 'model = "reportlab-pdf"' in toml- assert 'filename = "invoice.pdf"' in toml-- def test_img_gen_model_in_toml(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "my_img_gen",- "description": "Image gen pipe",- "inputs": {"prompt_text": "Text"},- "output": "Image",- "model": "$gen-image",- "prompt": "Generate: $prompt_text",- },- pipe_type="PipeImgGen",- )- toml = _pipe_spec_to_toml(spec)- assert 'model = "$gen-image"' in toml-- def test_toml_contains_pipe_section(self) -> None:- spec = parse_pipe_spec({**self._BASE_LLM}, pipe_type="PipeLLM")- toml = _pipe_spec_to_toml(spec)- assert "[pipe.my_llm_pipe]" in toml- assert 'type = "PipeLLM"' in toml-- def test_toml_contains_prompt(self) -> None:- spec = parse_pipe_spec({**self._BASE_LLM}, pipe_type="PipeLLM")- toml = _pipe_spec_to_toml(spec)- assert 'prompt = "Write about $text"' in toml-- def test_sequence_toml_has_steps(self) -> None:- spec = parse_pipe_spec(- {- "pipe_code": "my_seq",- "description": "A sequence",- "inputs": {"doc": "Document"},- "output": "Text",- "steps": [- {"pipe": "step_one", "result": "intermediate"},- {"pipe": "step_two", "result": "final"},- ],- },- pipe_type="PipeSequence",- )- toml = _pipe_spec_to_toml(spec)- assert "step_one" in toml- assert "step_two" in toml-- def test_search_fields_appear_in_toml(self) -> None:- """PipeSearch type-specific fields (prompt, model, filters) must round-trip to TOML."""- spec = parse_pipe_spec(- {- "pipe_code": "my_search",- "description": "Search pipe",- "inputs": {"topic": "Text"},- "output": "Text",- "model": "$search-default",- "prompt": "Latest news about $topic",- "from_date": "2025-01-01",- "to_date": "2025-06-01",- "include_domains": ["reuters.com", "bbc.com"],- "exclude_domains": ["example.com"],- "max_results": 5,- },- pipe_type="PipeSearch",- )- toml = _pipe_spec_to_toml(spec)- assert 'type = "PipeSearch"' in toml- assert 'model = "$search-default"' in toml- assert 'prompt = "Latest news about $topic"' in toml- assert 'from_date = "2025-01-01"' in toml- assert 'to_date = "2025-06-01"' in toml- assert "reuters.com" in toml- assert "bbc.com" in toml- assert "example.com" in toml- assert "max_results = 5" in toml-- def test_search_optional_filters_omitted_in_toml(self) -> None:- """Unset PipeSearch filters must not appear in the TOML (only prompt is required)."""- spec = parse_pipe_spec(- {- "pipe_code": "bare_search",- "description": "Minimal search pipe",- "inputs": {"topic": "Text"},- "output": "Text",- "prompt": "About $topic",- },- pipe_type="PipeSearch",- )- toml = _pipe_spec_to_toml(spec)- assert 'prompt = "About $topic"' in toml- assert "model =" not in toml- assert "from_date" not in toml- assert "to_date" not in toml- assert "include_domains" not in toml- assert "exclude_domains" not in toml- assert "max_results" not in toml-- def test_llm_no_model_omits_model_in_toml(self) -> None:- """When model is None, no model line should appear in the TOML."""- spec = parse_pipe_spec(- {- "pipe_code": "my_pipe",- "description": "No model specified",- "inputs": {"text": "Text"},- "output": "Text",- "prompt": "Write about $text",- },- pipe_type="PipeLLM",- )- toml = _pipe_spec_to_toml(spec)- assert "model =" not in toml-- # -- End-to-end: combined tolerance through CLI layer -------------------- def test_model_with_dict_output_both_tolerated(self) -> None:- """The agent sends model preset and output as dict — both should be tolerated."""- spec: dict[str, Any] = {- "pipe_code": "generate_prompt",- "description": "Generate an image prompt from an idea",- "model": "$writing-creative",- "inputs": {"idea": "Text"},- "output": {"type": "Text"},- "prompt": "Generate a creative image prompt based on $idea",- }- result = parse_pipe_spec(spec, pipe_type="PipeLLM")- assert result.model == "$writing-creative" # type: ignore[attr-defined]- assert result.output == "Text"-- def test_toml_output_has_correct_model(self) -> None:- """The TOML should contain the model preset directly."""- spec: dict[str, Any] = {- "pipe_code": "generate_prompt",- "description": "Generate an image prompt from an idea",- "model": "$writing-creative",- "inputs": {"idea": "Text"},- "output": {"type": "Text"},- "prompt": "Generate a creative image prompt based on $idea",- }- result = parse_pipe_spec(spec, pipe_type="PipeLLM")- toml = _pipe_spec_to_toml(result)- assert 'model = "$writing-creative"' in toml- assert 'output = "Text"' in toml-- def test_judge_fields_appear_in_toml(self) -> None:- """PipeJudge type-specific fields round-trip to TOML, its template written as `question` whatever spelling came in."""- spec = parse_pipe_spec(- {- "pipe_code": "route_ticket",- "description": "Route a ticket",- "inputs": {"ticket": "Text"},- "output": "Choice",- "model": "@default-judgment",- "prompt": "Which team should handle the ticket?",- "options": {"billing": "Charges and invoices", "technical": ""},- },- pipe_type="PipeJudge",- )- toml = _pipe_spec_to_toml(spec)- assert 'type = "PipeJudge"' in toml- assert 'model = "@default-judgment"' in toml- assert 'question = "Which team should handle the ticket?"' in toml- assert "prompt" not in toml- assert 'billing = "Charges and invoices"' in tomldiff --git a/tests/unit/pipelex/codegen/test_naming.py b/tests/unit/pipelex/codegen/test_naming.pyindex 3b0a43178..e2ee9bc26 100644--- a/tests/unit/pipelex/codegen/test_naming.py+++ b/tests/unit/pipelex/codegen/test_naming.py@@ -1,27 +1,20 @@-from pipelex.codegen.emitters.naming import allocate_ts_type_names, python_class_name, runtime_to_emitted_class_names, snake_to_pascal, ts_type_name+from pipelex.codegen.emitters.naming import allocate_ts_type_names, python_class_name, snake_to_pascal, ts_type_namefrom pipelex.codegen.resolved_concepts import ResolvedConcept, ResolvedLibrary-def _resolved_concept(- *,- domain: str,- code: str,- is_native: bool = False,- needs_qualification: bool = False,- opaque_python_class: str | None = None,-) -> ResolvedConcept:+def _resolved_concept(*, domain: str, code: str, needs_qualification: bool = False) -> ResolvedConcept:return ResolvedConcept(concept_ref=f"{domain}.{code}",domain=domain,code=code,description=f"{code} concept",- is_native=is_native,+ is_native=False,needs_qualification=needs_qualification,base_ref=None,fields=[],- structureless=opaque_python_class is not None,+ structureless=False,imprecision_reason=None,- opaque_python_class=opaque_python_class,+ opaque_python_class=None,)@@ -104,23 +97,3 @@ class TestNaming:"demo.Foo": "Foo","demo.FooSchema": "FooSchema2",}-- def test_runtime_to_emitted_class_names(self):- """Runtime-qualified spellings map to the emitted names; natives and opaque classes are skipped."""- library = ResolvedLibrary(- mthds_version="0.1.0",- concepts=[- _resolved_concept(domain="pipeline", code="Report"),- _resolved_concept(domain="alpha", code="Result", needs_qualification=True),- _resolved_concept(domain="native", code="Text", is_native=True),- _resolved_concept(domain="pipeline", code="Wrapped", opaque_python_class="UserClass"),- ],- )-- mapping = runtime_to_emitted_class_names(library)-- # Unique code: runtime-qualified -> bare; collision: identity; native + opaque: absent.- assert mapping == {- "pipeline__Report": "Report",- "alpha__Result": "alpha__Result",- }diff --git a/tests/unit/pipelex/cogt/content_generation/test_dry_run_factory_main_pipe.py b/tests/unit/pipelex/cogt/content_generation/test_dry_run_factory_main_pipe.pyindex 25794d9d2..9d031f5e1 100644--- a/tests/unit/pipelex/cogt/content_generation/test_dry_run_factory_main_pipe.py+++ b/tests/unit/pipelex/cogt/content_generation/test_dry_run_factory_main_pipe.py@@ -16,7 +16,7 @@ class PipeStub(BaseModel):class BundleStub(BaseModel):- """Mirrors the real bundle shape (`PipelexBundleBlueprint` / builder `BundleSpec`).+ """Mirrors the real bundle shape (`PipelexBundleBlueprint`).The combination of a `pipe` dict and a `main_pipe` that must reference one of itskeys is exactly what makes `DryRunFactory.make_dry_run_factory` register thediff --git a/tests/unit/pipelex/mthds_parsing/test_data_pipe_sorter.py b/tests/unit/pipelex/mthds_parsing/test_data_pipe_sorter.pydeleted file mode 100644index 7732ed89c..000000000--- a/tests/unit/pipelex/mthds_parsing/test_data_pipe_sorter.py+++ /dev/null@@ -1,330 +0,0 @@-"""Test data for pipe dependency sorting."""--from typing import ClassVar--from pipelex.core.pipes.exceptions import PipeValidationError-from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipeBlueprintUnion-from pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprint-from pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprint-from pipelex.pipe_controllers.parallel.pipe_parallel_blueprint import PipeParallelBlueprint-from pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint-from pipelex.pipe_controllers.sub_pipe_blueprint import SubPipeBlueprint-from pipelex.pipe_operators.img_gen.pipe_img_gen_blueprint import PipeImgGenBlueprint-from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint---class PipeSorterTestCases:- """Test cases for pipe dependency sorting with various scenarios."""-- # Test case 1: No dependencies - all operators- NO_DEPENDENCIES_PIPES: ClassVar[dict[str, PipeBlueprintUnion]] = {- "pipe_c": PipeLLMBlueprint(description="C", inputs={}, output="Text"),- "pipe_a": PipeLLMBlueprint(description="A", inputs={}, output="Text"),- "pipe_b": PipeLLMBlueprint(description="B", inputs={}, output="Text"),- }- NO_DEPENDENCIES_EXPECTED: ClassVar[list[str]] = ["pipe_a", "pipe_b", "pipe_c"] # Alphabetical order (all are roots)-- # Test case 2: Simple chain A -> B -> C- SIMPLE_CHAIN_PIPES: ClassVar[dict[str, PipeBlueprintUnion]] = {- "pipe_c": PipeSequenceBlueprint(- description="C depends on B",- inputs={},- output="Text",- steps=[SubPipeBlueprint(pipe="pipe_b", result="result_b")],- ),- "pipe_a": PipeLLMBlueprint(description="A no deps", inputs={}, output="Text"),- "pipe_b": PipeSequenceBlueprint(- description="B depends on A",- inputs={},- output="Text",- steps=[SubPipeBlueprint(pipe="pipe_a", result="result_a")],- ),- }- SIMPLE_CHAIN_EXPECTED: ClassVar[list[str]] = ["pipe_c", "pipe_b", "pipe_a"]-- # Test case 3: Diamond pattern- # A- # / \- # B C- # \ /- # D- DIAMOND_PIPES: ClassVar[dict[str, PipeBlueprintUnion]] = {- "pipe_d": PipeParallelBlueprint(- description="D depends on B and C",- inputs={},- output="Composite",- branches=[- SubPipeBlueprint(pipe="pipe_b", result="result_b"),- SubPipeBlueprint(pipe="pipe_c", result="result_c"),- ],- add_each_output=True,- ),- "pipe_a": PipeLLMBlueprint(description="A", inputs={}, output="Text"),- "pipe_c": PipeSequenceBlueprint(- description="C depends on A",- inputs={},- output="Text",- steps=[SubPipeBlueprint(pipe="pipe_a", result="result_a")],- ),- "pipe_b": PipeSequenceBlueprint(- description="B depends on A",- inputs={},- output="Text",- steps=[SubPipeBlueprint(pipe="pipe_a", result="result_a")],- ),- }- # D is root, visits B first (alphabetically), then A (B's dependency), then C (already visited A)- # Don't verify exact order for diamond pattern due to shared dependencies- DIAMOND_EXPECTED: ClassVar[list[str] | None] = None-- # Test case 4: Multiple independent chains- MULTIPLE_CHAINS_PIPES: ClassVar[dict[str, PipeBlueprintUnion]] = {- # Chain 1: A -> B- "pipe_b": PipeSequenceBlueprint(- description="B depends on A",- inputs={},- output="Text",- steps=[SubPipeBlueprint(pipe="pipe_a", result="result_a")],- ),- "pipe_a": PipeLLMBlueprint(description="A", inputs={}, output="Text"),- # Chain 2: X -> Y- "pipe_y": PipeSequenceBlueprint(- description="Y depends on X",- inputs={},- output="Text",- steps=[SubPipeBlueprint(pipe="pipe_x", result="result_x")],- ),- "pipe_x": PipeLLMBlueprint(description="X", inputs={}, output="Text"),- }- # Depth-first from roots (pipe_b, pipe_y alphabetically): pipe_b -> pipe_a, then pipe_y -> pipe_x- MULTIPLE_CHAINS_EXPECTED: ClassVar[list[str]] = ["pipe_b", "pipe_a", "pipe_y", "pipe_x"]-- # Test case 5: PipeBatch dependency- PIPE_BATCH_PIPES: ClassVar[dict[str, PipeBlueprintUnion]] = {- "batch_pipe": PipeBatchBlueprint(- description="Batch depends on process",- inputs={"items": "Item[]"},- output="Text",- branch_pipe_code="process_item",- input_list_name="items",- input_item_name="item",- ),- "process_item": PipeLLMBlueprint(description="Process", inputs={}, output="Text"),- }- PIPE_BATCH_EXPECTED: ClassVar[list[str]] = ["batch_pipe", "process_item"]-- # Test case 6: PipeCondition with multiple branches- PIPE_CONDITION_PIPES: ClassVar[dict[str, PipeBlueprintUnion]] = {- "router": PipeConditionBlueprint(- description="Routes to different pipes",- inputs={},- output="Text",- expression="category",- outcomes={- "small": "process_small",- "large": "process_large",- },- default_outcome="process_default",- ),- "process_large": PipeLLMBlueprint(description="Large", inputs={}, output="Text"),- "process_small": PipeLLMBlueprint(description="Small", inputs={}, output="Text"),- "process_default": PipeLLMBlueprint(description="Default", inputs={}, output="Text"),- }- # Router first, then its dependencies in alphabetical order- PIPE_CONDITION_EXPECTED: ClassVar[list[str]] = ["router", "process_default", "process_large", "process_small"]-- # Test case 7: Circular dependency (should raise error)- CIRCULAR_PIPES: ClassVar[dict[str, PipeBlueprintUnion]] = {- "pipe_a": PipeSequenceBlueprint(- description="A depends on C (circular!)",- inputs={},- output="Text",- steps=[SubPipeBlueprint(pipe="pipe_c", result="result_c")],- ),- "pipe_b": PipeSequenceBlueprint(- description="B depends on A",- inputs={},- output="Text",- steps=[SubPipeBlueprint(pipe="pipe_a", result="result_a")],- ),- "pipe_c": PipeSequenceBlueprint(- description="C depends on B",- inputs={},- output="Text",- steps=[SubPipeBlueprint(pipe="pipe_b", result="result_b")],- ),- }-- # Test case 8: Reference to non-existent pipe (should be ignored in sorting)- MISSING_DEPENDENCY_PIPES: ClassVar[dict[str, PipeBlueprintUnion]] = {- "pipe_b": PipeSequenceBlueprint(- description="B depends on A and Z (Z doesn't exist)",- inputs={},- output="Text",- steps=[- SubPipeBlueprint(pipe="pipe_a", result="result_a"),- SubPipeBlueprint(pipe="pipe_z", result="result_z"), # Z doesn't exist in this bundle- ],- ),- "pipe_a": PipeLLMBlueprint(description="A", inputs={}, output="Text"),- }- MISSING_DEPENDENCY_EXPECTED: ClassVar[list[str]] = ["pipe_b", "pipe_a"] # Z is ignored as it's not in the bundle-- # Test case 9: Image inversion pipeline - realistic multi-step sequence- IMAGE_INVERSION_PIPES: ClassVar[dict[str, PipeBlueprintUnion]] = {- "analyze_image_content": PipeLLMBlueprint(- description="Analyzes the input photo to understand visual elements, composition, mood, etc.",- inputs={"input_photo": "Image"},- output="ImageAnalysis",- prompt="Analyze this image: $input_photo",- ),- "define_opposite_concept": PipeLLMBlueprint(- description="Determines what constitutes the opposite for the analyzed image",- inputs={"image_analysis": "ImageAnalysis"},- output="OppositeDefinition",- prompt="Define opposite for: $image_analysis",- ),- "generate_image_prompt": PipeLLMBlueprint(- description="Crafts a detailed image generation prompt from the opposite definition",- inputs={"opposite_definition": "OppositeDefinition"},- output="ImagePrompt",- prompt="Generate prompt from: $opposite_definition",- ),- "generate_opposite_image": PipeImgGenBlueprint(- description="Generates the opposite image using AI",- inputs={"generation_prompt": "ImagePrompt"},- output="Image",- prompt="@generation_prompt",- ),- "photo_opposite_pipeline": PipeSequenceBlueprint(- description="Main pipeline that generates the opposite of an input photo",- inputs={"input_photo": "Image"},- output="Image",- steps=[- SubPipeBlueprint(pipe="analyze_image_content", result="image_analysis"),- SubPipeBlueprint(pipe="define_opposite_concept", result="opposite_concept"),- SubPipeBlueprint(pipe="generate_image_prompt", result="generation_prompt"),- SubPipeBlueprint(pipe="generate_opposite_image", result="opposite_image"),- ],- ),- }- # Controller first, then dependencies in step order- IMAGE_INVERSION_EXPECTED: ClassVar[list[str]] = [- "photo_opposite_pipeline",- "analyze_image_content",- "define_opposite_concept",- "generate_image_prompt",- "generate_opposite_image",- ]-- # Test case 10: Complex nested pipeline with PipeSequence containing another PipeSequence and PipeCondition- COMPLEX_NESTED_PIPES: ClassVar[dict[str, PipeBlueprintUnion]] = {- # Main sequence with nested controllers- "main_pipeline": PipeSequenceBlueprint(- description="Main pipeline with nested controllers",- inputs={"input": "Text"},- output="Text",- steps=[- SubPipeBlueprint(pipe="nested_sequence", result="prepared"),- SubPipeBlueprint(pipe="router", result="processed"),- SubPipeBlueprint(pipe="final_process", result="final"),- ],- ),- # Nested sequence- "nested_sequence": PipeSequenceBlueprint(- description="Nested preparation sequence",- inputs={"input": "Text"},- output="Text",- steps=[- SubPipeBlueprint(pipe="prepare_data", result="prepared_data"),- SubPipeBlueprint(pipe="validate_data", result="validated_data"),- ],- ),- # Condition router- "router": PipeConditionBlueprint(- description="Routes based on size",- inputs={"prepared": "Text"},- output="Text",- expression="size",- outcomes={- "small": "process_small",- "large": "process_large",- },- default_outcome="process_default",- ),- # LLM operators- "prepare_data": PipeLLMBlueprint(- description="Prepare the data",- inputs={"input": "Text"},- output="Text",- prompt="Prepare: $input",- ),- "validate_data": PipeLLMBlueprint(- description="Validate the prepared data",- inputs={"prepared_data": "Text"},- output="Text",- prompt="Validate: $prepared_data",- ),- "process_small": PipeLLMBlueprint(- description="Process small items",- inputs={"item": "Text"},- output="Text",- prompt="Process small: $item",- ),- "process_large": PipeLLMBlueprint(- description="Process large items",- inputs={"item": "Text"},- output="Text",- prompt="Process large: $item",- ),- "process_default": PipeLLMBlueprint(- description="Default processing",- inputs={"item": "Text"},- output="Text",- prompt="Process default: $item",- ),- "final_process": PipeLLMBlueprint(- description="Final processing step",- inputs={"processed": "Text"},- output="Text",- prompt="Final process: $processed",- ),- }- # Expected order: main_pipeline first, then following step order- # Step 1: nested_sequence and its steps (prepare_data, validate_data)- # Step 2: router and its dependencies (alphabetically: process_default, process_large, process_small)- # Step 3: final_process- COMPLEX_NESTED_EXPECTED: ClassVar[list[str]] = [- "main_pipeline",- "nested_sequence",- "prepare_data",- "validate_data",- "router",- "process_default",- "process_large",- "process_small",- "final_process",- ]-- # Aggregate all test cases- TEST_CASES: ClassVar[- list[- tuple[- str, # test_name- dict[str, PipeBlueprintUnion], # pipes- list[str] | None, # expected_order (None if should raise error)- type[Exception] | None, # expected_exception (None if should succeed)- ]- ]- ] = [- ("no_dependencies", NO_DEPENDENCIES_PIPES, NO_DEPENDENCIES_EXPECTED, None),- ("simple_chain", SIMPLE_CHAIN_PIPES, SIMPLE_CHAIN_EXPECTED, None),- ("diamond_pattern", DIAMOND_PIPES, DIAMOND_EXPECTED, None),- ("multiple_chains", MULTIPLE_CHAINS_PIPES, MULTIPLE_CHAINS_EXPECTED, None),- ("pipe_batch", PIPE_BATCH_PIPES, PIPE_BATCH_EXPECTED, None),- ("pipe_condition", PIPE_CONDITION_PIPES, PIPE_CONDITION_EXPECTED, None),- ("circular_dependency", CIRCULAR_PIPES, None, PipeValidationError),- ("missing_dependency", MISSING_DEPENDENCY_PIPES, MISSING_DEPENDENCY_EXPECTED, None),- ("image_inversion", IMAGE_INVERSION_PIPES, IMAGE_INVERSION_EXPECTED, None),- ("complex_nested", COMPLEX_NESTED_PIPES, COMPLEX_NESTED_EXPECTED, None),- ]diff --git a/tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py b/tests/unit/pipelex/mthds_parsing/test_pipe_sorter.pydeleted file mode 100644index fd126115b..000000000--- a/tests/unit/pipelex/mthds_parsing/test_pipe_sorter.py+++ /dev/null@@ -1,75 +0,0 @@-"""Unit tests for pipe dependency sorting."""--import pytest--from pipelex.core.pipes.exceptions import PipeValidationError-from pipelex.mthds_parsing.pipe_sorter import sort_pipes_by_dependencies-from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipeBlueprintUnion-from tests.unit.pipelex.mthds_parsing.test_data_pipe_sorter import PipeSorterTestCases---class TestSortPipesByDependencies:- """Test suite for the sort_pipes_by_dependencies function."""-- @pytest.mark.parametrize(- ("test_name", "pipes", "expected_order", "expected_exception"),- PipeSorterTestCases.TEST_CASES,- )- def test_sort_pipes_by_dependencies(- self,- test_name: str,- pipes: dict[str, PipeBlueprintUnion],- expected_order: list[str] | None,- expected_exception: type[Exception] | None,- ):- """Test pipe sorting with various dependency patterns.-- Args:- test_name: Name of the test case for identification- pipes: Dictionary of pipe_code to PipeBlueprintUnion- expected_order: Expected order of pipe codes after sorting (None if should raise)- expected_exception: Expected exception type (None if should succeed)- """- if expected_exception:- # Test that circular dependencies raise the correct exception- with pytest.raises(expected_exception):- sort_pipes_by_dependencies(pipes)- else:- # Test successful sorting- sorted_pipes = sort_pipes_by_dependencies(pipes)- sorted_codes = [code for code, _ in sorted_pipes]-- # Verify all pipes are present- assert len(sorted_codes) == len(pipes), f"Test '{test_name}': Not all pipes were included in sorted result"- assert set(sorted_codes) == set(pipes.keys()), f"Test '{test_name}': Pipe codes don't match"-- # Verify the order respects depth-first pre-order dependencies- # In depth-first pre-order, each pipe comes before its dependencies- # (unless the dependency was already visited through another path)- for code, blueprint in sorted_pipes:- dependencies = blueprint.pipe_dependencies- code_index = sorted_codes.index(code)- for dep_code in dependencies:- # Only check dependencies that exist in this bundle- if dep_code in pipes:- dep_index = sorted_codes.index(dep_code)- # Skip if dependency was visited earlier (shared dependency)- if dep_index < code_index:- continue- assert code_index < dep_index, (- f"Test '{test_name}': In depth-first pre-order, pipe '{code}' "- f"should come before its dependency '{dep_code}' in {sorted_codes}"- )-- # For test cases with a specific expected order, verify exact match- if expected_order is not None:- assert sorted_codes == expected_order, f"Test '{test_name}': Expected {expected_order}, got {sorted_codes}"-- def test_circular_dependency_error_carries_domain_code(self):- """The cycle error must stay domain-qualified: `domain_code` rides alongside- `pipe_code` so the wire item can identify the pipe by full ref.- """- with pytest.raises(PipeValidationError) as exc_info:- sort_pipes_by_dependencies(PipeSorterTestCases.CIRCULAR_PIPES, domain_code="cycling_domain")- assert exc_info.value.pipe_code is not None- assert exc_info.value.domain_code == "cycling_domain"diff --git a/tests/unit/pipelex/pipe_operators/pipe_llm/test_pipe_llm_templating_style.py b/tests/unit/pipelex/pipe_operators/pipe_llm/test_pipe_llm_templating_style.pyindex 345650cca..46acf5241 100644--- a/tests/unit/pipelex/pipe_operators/pipe_llm/test_pipe_llm_templating_style.py+++ b/tests/unit/pipelex/pipe_operators/pipe_llm/test_pipe_llm_templating_style.py@@ -1,4 +1,4 @@-"""Authored `templating_style` on PipeLLM: parsing shapes, spec passthrough, factory widening.+"""Authored `templating_style` on PipeLLM: parsing shapes, factory widening.The authored surface is a typed union — a bare string is the `tag_style` shorthand, an inlinetable is the full struct — and the union never travels past parsing: the factory widens a bare@@ -8,7 +8,6 @@ table is the full struct — and the union never travels past parsing: the factofrom collections.abc import Callablefrom typing import Any-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpecfrom pipelex.pipe_machinery.pipe_factory import PipeFactoryfrom pipelex.pipe_operators.llm.pipe_llm import PipeLLMfrom pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint@@ -39,19 +38,6 @@ class TestPipeLLMTemplatingStyle:blueprint = _make_blueprint(templating_style={"tag_style": "xml", "text_format": "markdown"})assert blueprint.templating_style == TemplatingStyle(tag_style=TagStyle.XML, text_format=TextFormat.MARKDOWN)- def test_spec_passes_through_to_blueprint(self):- spec = PipeLLMSpec.model_validate(- {- "pipe_code": "templating_style_spec_case",- "description": "templating style spec passthrough",- "inputs": {},- "output": "native.Text",- "prompt": "Say hello",- "templating_style": "square_brackets",- }- )- assert spec.to_blueprint().templating_style is TagStyle.SQUARE_BRACKETS-def test_factory_widens_bare_tag_style(self, load_empty_library: Callable[[], str]):load_empty_library()pipe = PipeFactory[PipeLLM].make_from_blueprint(diff --git a/tests/unit/pipelex/pipeline/test_build_validated_pipes.py b/tests/unit/pipelex/pipeline/test_build_validated_pipes.pyindex 4213eae8b..c88a05619 100644--- a/tests/unit/pipelex/pipeline/test_build_validated_pipes.py+++ b/tests/unit/pipelex/pipeline/test_build_validated_pipes.py@@ -1,7 +1,7 @@"""Pin the ``build_validated_pipes`` projection contract (the C-8 fix).``build_validated_pipes`` turns a dry-run result map into the ``validated_pipes`` JSON list that the-agent CLI + builder ops publish. Two guarantees must hold, and a regression in either would silently+agent CLI and the protocol validation report publish. Two guarantees must hold, and a regression in either would silentlycorrupt the published contract while the rest of the suite stays green:1. **Truthful status.** A FAILURE (e.g. an ``allowed_to_fail`` pipe) and a SKIPPED (cross-package)diff --git a/tests/unit/pipelex/builder/operations/test_inputs_ops.py b/tests/unit/pipelex/pipeline/test_inputs_template.pysimilarity index 98%rename from tests/unit/pipelex/builder/operations/test_inputs_ops.pyrename to tests/unit/pipelex/pipeline/test_inputs_template.pyindex cb2fe2c88..2364d39b7 100644--- a/tests/unit/pipelex/builder/operations/test_inputs_ops.py+++ b/tests/unit/pipelex/pipeline/test_inputs_template.py@@ -1,4 +1,4 @@-"""Unit tests for build_inputs_for_pipe in builder operations (inputs_ops)."""+"""Unit tests for build_inputs_for_pipe, the inputs template engine behind `pipelex-agent inputs`."""from __future__ import annotations@@ -9,13 +9,13 @@ from typing import TYPE_CHECKING, Anyimport pytest-from pipelex.builder.operations.inputs_ops import build_inputs_for_pipefrom pipelex.core.pipes.inputs.exceptions import NoInputsRequiredError+from pipelex.pipeline.inputs_template import build_inputs_for_pipeif TYPE_CHECKING:from pytest_mock import MockerFixture-MODULE = "pipelex.builder.operations.inputs_ops"+MODULE = "pipelex.pipeline.inputs_template"class TestBuildInputsForPipe:diff --git a/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py b/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.pyindex 11c20d125..01ff04800 100644--- a/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py+++ b/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py@@ -16,7 +16,7 @@ from mthds.protocol.exceptions import PipelineRequestErrorfrom mthds.protocol.models import ModelCategory as MthdsModelCategoryfrom mthds.protocol.protocol import PROTOCOL_VERSION-from pipelex.builder.operations.models_ops import ModelCategory+from pipelex.cogt.models.model_listing import ModelCategoryfrom pipelex.pipeline.runner import (PipelexModelDeck,PipelexMTHDSProtocol,@@ -119,34 +119,34 @@ class TestRunnerProtocolSurfaces:assert deck.model_dump(mode="json")["models"][1] == {"name": "strict_verdict", "type": "judgment"}assert deck.aliases["judgment"] == {"default-judgment": "strict_verdict"}- @pytest.mark.parametrize("builder_category", list(ModelCategory))- async def test_models_types_every_builder_category_by_the_protocol_member_of_its_name(+ @pytest.mark.parametrize("listing_category", list(ModelCategory))+ async def test_models_types_every_listing_category_by_the_protocol_member_of_its_name(self,mocker: MockerFixture,- builder_category: ModelCategory,+ listing_category: ModelCategory,) -> None:- """Every category the builder serves has a protocol category of the same name, so none of+ """Every category the model listing serves has a protocol category of the same name, so none ofits presets is left out of the flat list or typed by an invented value."""payload: dict[str, Any] = {- "presets": {builder_category: [{"name": "some_preset"}]},- "aliases": {builder_category: {}},- "waterfalls": {builder_category: {}},+ "presets": {listing_category: [{"name": "some_preset"}]},+ "aliases": {listing_category: {}},+ "waterfalls": {listing_category: {}},}mocker.patch("pipelex.pipeline.runner.list_models", return_value=payload)runner = PipelexMTHDSProtocol()deck = await runner.models()- assert [(model_info.name, model_info.type) for model_info in deck.models] == [("some_preset", MthdsModelCategory(builder_category))]+ assert [(model_info.name, model_info.type) for model_info in deck.models] == [("some_preset", MthdsModelCategory(listing_category))]@pytest.mark.parametrize("protocol_category", list(MthdsModelCategory))- async def test_models_category_filter_translates_to_builder_enum(+ async def test_models_category_filter_translates_to_listing_enum(self,mocker: MockerFixture,protocol_category: MthdsModelCategory,) -> None:- """Each protocol-level category filter reaches list_models as the builder's member of the same name."""+ """Each protocol-level category filter reaches list_models as the model listing's member of the same name."""one_category_payload: dict[str, Any] = {"presets": {protocol_category: [{"name": "some_preset"}]},"aliases": {protocol_category: {"best": "some_preset"}},diff --git a/tests/unit/pipelex/test_kernel_layer_import_closure.py b/tests/unit/pipelex/test_kernel_layer_import_closure.pyindex d772dd944..762b79fb7 100644--- a/tests/unit/pipelex/test_kernel_layer_import_closure.py+++ b/tests/unit/pipelex/test_kernel_layer_import_closure.py@@ -120,7 +120,6 @@ INTERPRETER_PACKAGES: tuple[str, ...] = ("pipe_operators","pipe_controllers","codegen",- "builder",# The built-ins that adapt interpreter-layer ports; they construct interpreter-layer objects."interpreter_plugins",# Core's Pipe machinery and the pipe-kind registration manifest, hoisted out of `core/`.diff --git a/tests/unit/pipelex/tools/misc/test_find_files_in_dir.py b/tests/unit/pipelex/tools/misc/test_find_files_in_dir.pyindex 90902cabc..8d1ea69d1 100644--- a/tests/unit/pipelex/tools/misc/test_find_files_in_dir.py+++ b/tests/unit/pipelex/tools/misc/test_find_files_in_dir.py@@ -128,214 +128,6 @@ class TestFindFilesInDir:assert "node_file.py" not in file_namesassert "cache_file.py" not in file_names- def test_find_files_with_force_include_dirs_full_path(self):- """Test finding files with force force include directories using full paths."""- with tempfile.TemporaryDirectory() as temp_dir:- # Create files in root- (Path(temp_dir) / "root.py").touch()-- # Create excluded directory structure- venv_dir = Path(temp_dir) / ".venv"- venv_lib = venv_dir / "lib" / "python3.11" / "site-packages"- venv_lib.mkdir(parents=True)- (venv_lib / "excluded.py").touch()-- # Create include directory within excluded- force_include_dir = venv_lib / "pipelex"- force_include_dir.mkdir()- (force_include_dir / "important.py").touch()-- # Create nested file in include dir- include_nested = force_include_dir / "builder"- include_nested.mkdir()- (include_nested / "builder.py").touch()-- # Create another file in venv but outside include dir- other_venv = venv_lib / "other_package"- other_venv.mkdir()- (other_venv / "other.py").touch()-- files = find_files_in_dir(- Path(temp_dir),- pattern="*.py",- is_recursive=True,- excluded_dirs=[".venv"],- force_include_dirs=[str(force_include_dir)],- )-- file_names = [f.name for f in files]- file_paths_str = [str(f) for f in files]-- # Should include root and include dir files, but not other venv files- assert len(files) == 3- assert "root.py" in file_names- assert "important.py" in file_names- assert "builder.py" in file_names- assert "excluded.py" not in file_names- assert "other.py" not in file_names-- # Verify the full paths are correct- assert any(str(force_include_dir / "important.py") in path for path in file_paths_str)- assert any(str(include_nested / "builder.py") in path for path in file_paths_str)-- def test_find_files_with_force_include_dirs_directory_name(self):- """Test finding files with force force include directories using directory names."""- with tempfile.TemporaryDirectory() as temp_dir:- # Create files in root- (Path(temp_dir) / "root.py").touch()-- # Create excluded directory structure- venv_dir = Path(temp_dir) / ".venv"- venv_lib = venv_dir / "lib"- venv_lib.mkdir(parents=True)- (venv_lib / "excluded.py").touch()-- # Create include directory by name within excluded- pipelex_dir = venv_lib / "pipelex"- pipelex_dir.mkdir()- (pipelex_dir / "important.py").touch()-- # Create another pipelex directory elsewhere to test name matching- src_pipelex = Path(temp_dir) / "src" / "pipelex"- src_pipelex.mkdir(parents=True)- (src_pipelex / "also_important.py").touch()-- files = find_files_in_dir(- Path(temp_dir),- pattern="*.py",- is_recursive=True,- excluded_dirs=[".venv"],- force_include_dirs=["pipelex"],- )-- file_names = [f.name for f in files]-- # Should include root, both pipelex directories (one from venv as included, one from src)- assert len(files) == 3- assert "root.py" in file_names- assert "important.py" in file_names- assert "also_important.py" in file_names- assert "excluded.py" not in file_names-- def test_find_files_with_force_include_dirs_mixed_types(self):- """Test finding files with force force include directories using both full paths and names."""- with tempfile.TemporaryDirectory() as temp_dir:- # Create files in root- (Path(temp_dir) / "root.py").touch()-- # Create excluded directory structure- venv_dir = Path(temp_dir) / ".venv"- venv_packages = venv_dir / "lib" / "site-packages"- venv_packages.mkdir(parents=True)-- # Include by full path- pipelex_dir = venv_packages / "pipelex"- pipelex_dir.mkdir()- (pipelex_dir / "pipelex_file.py").touch()-- # Another excluded directory- node_modules = Path(temp_dir) / "node_modules"- node_modules.mkdir()- (node_modules / "node_file.py").touch()-- # Include by name within node_modules- special_dir = node_modules / "special"- special_dir.mkdir()- (special_dir / "special_file.py").touch()-- # Regular file in node_modules- (node_modules / "regular_node.py").touch()-- files = find_files_in_dir(- Path(temp_dir),- pattern="*.py",- is_recursive=True,- excluded_dirs=[".venv", "node_modules"],- force_include_dirs=[str(pipelex_dir), "special"],- )-- file_names = [f.name for f in files]-- # Should include root, pipelex (full path include), and special (name include)- assert len(files) == 3- assert "root.py" in file_names- assert "pipelex_file.py" in file_names- assert "special_file.py" in file_names- assert "node_file.py" not in file_names- assert "regular_node.py" not in file_names-- def test_find_files_with_multiple_force_include_dirs_full_paths(self):- """Test finding files with multiple force include directories using full paths."""- with tempfile.TemporaryDirectory() as temp_dir:- # Create files in root- (Path(temp_dir) / "root.py").touch()-- # Create excluded directory- venv_dir = Path(temp_dir) / ".venv"- packages = venv_dir / "site-packages"- packages.mkdir(parents=True)-- # First include directory- pkg1 = packages / "package1"- pkg1.mkdir()- (pkg1 / "pkg1_file.py").touch()-- # Second include directory- pkg2 = packages / "package2"- pkg2.mkdir()- (pkg2 / "pkg2_file.py").touch()-- # Non-included directory- pkg3 = packages / "package3"- pkg3.mkdir()- (pkg3 / "pkg3_file.py").touch()-- files = find_files_in_dir(- Path(temp_dir),- pattern="*.py",- is_recursive=True,- excluded_dirs=[".venv"],- force_include_dirs=[str(pkg1), str(pkg2)],- )-- file_names = [f.name for f in files]-- assert len(files) == 3- assert "root.py" in file_names- assert "pkg1_file.py" in file_names- assert "pkg2_file.py" in file_names- assert "pkg3_file.py" not in file_names-- def test_find_files_with_deeply_nested_force_include(self):- """Test finding files with deeply nested force include directories."""- with tempfile.TemporaryDirectory() as temp_dir:- # Create deeply nested structure- deep_path = Path(temp_dir) / ".venv" / "lib" / "python3.11" / "site-packages" / "pipelex" / "builder"- deep_path.mkdir(parents=True)- (deep_path / "deep_file.py").touch()-- # Create file at intermediate level that should be excluded- intermediate = Path(temp_dir) / ".venv" / "lib" / "python3.11" / "site-packages"- (intermediate / "intermediate.py").touch()-- # Create file at root- (Path(temp_dir) / "root.py").touch()-- files = find_files_in_dir(- Path(temp_dir),- pattern="*.py",- is_recursive=True,- excluded_dirs=[".venv"],- force_include_dirs=[str(deep_path)],- )-- file_names = [f.name for f in files]-- assert len(files) == 2- assert "root.py" in file_names- assert "deep_file.py" in file_names- assert "intermediate.py" not in file_names-def test_find_files_no_excluded_dirs(self):"""Test that passing None for excluded_dirs works correctly."""with tempfile.TemporaryDirectory() as temp_dir:@@ -354,48 +146,6 @@ class TestFindFilesInDir:assert "file1.py" in file_namesassert "venv_file.py" in file_names- def test_find_files_no_force_include_dirs(self):- """Test that passing None for force_include_dirs works correctly."""- with tempfile.TemporaryDirectory() as temp_dir:- # Create files- (Path(temp_dir) / "file1.py").touch()-- venv_dir = Path(temp_dir) / ".venv"- venv_dir.mkdir()- (venv_dir / "venv_file.py").touch()-- files = find_files_in_dir(Path(temp_dir), pattern="*.py", is_recursive=True, excluded_dirs=[".venv"], force_include_dirs=None)-- # Should exclude all venv files when no includes- assert len(files) == 1- assert files[0].name == "file1.py"-- def test_find_files_force_include_not_in_excluded_dir(self):- """Test that force include directories outside excluded directories are handled correctly."""- with tempfile.TemporaryDirectory() as temp_dir:- # Create normal directory- src_dir = Path(temp_dir) / "src"- src_dir.mkdir()- (src_dir / "src_file.py").touch()-- # Create excluded directory- venv_dir = Path(temp_dir) / ".venv"- venv_dir.mkdir()- (venv_dir / "venv_file.py").touch()-- # Include directory is in src, not in excluded dir- files = find_files_in_dir(- Path(temp_dir),- pattern="*.py",- is_recursive=True,- excluded_dirs=[".venv"],- force_include_dirs=[str(src_dir)],- )-- # Should find src file (not excluded) but not venv file- assert len(files) == 1- assert files[0].name == "src_file.py"-def test_find_files_pattern_matching(self):"""Test that file pattern matching works correctly with exclusions."""with tempfile.TemporaryDirectory() as temp_dir:@@ -433,21 +183,6 @@ class TestFindFilesInDir:# Empty list should behave like None - no exclusionsassert len(files) == 2- def test_find_files_empty_force_include_list(self):- """Test that passing an empty list for force_include_dirs works correctly."""- with tempfile.TemporaryDirectory() as temp_dir:- (Path(temp_dir) / "file1.py").touch()-- venv_dir = Path(temp_dir) / ".venv"- venv_dir.mkdir()- (venv_dir / "venv_file.py").touch()-- files = find_files_in_dir(Path(temp_dir), pattern="*.py", is_recursive=True, excluded_dirs=[".venv"], force_include_dirs=[])-- # Empty include list should exclude all venv files- assert len(files) == 1- assert files[0].name == "file1.py"-def test_exclude_using_absolute_path_structures_directory(self):"""Test excluding structures directory using absolute path (build_structures_cmd use case)."""with tempfile.TemporaryDirectory() as temp_dir:diff --git a/tests/unit/pipelex/tools/typing/test_format_agent_pydantic_validation_error.py b/tests/unit/pipelex/tools/typing/test_format_agent_pydantic_validation_error.pydeleted file mode 100644index 0592f02b8..000000000--- a/tests/unit/pipelex/tools/typing/test_format_agent_pydantic_validation_error.py+++ /dev/null@@ -1,174 +0,0 @@-import json-from typing import Any, ClassVar, Literal--import pytest-from pydantic import BaseModel, ConfigDict, Field, ValidationError-from typing_extensions import override--from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error_for_agent---class _SimpleModel(BaseModel):- model_config = ConfigDict(extra="forbid")- name: str- age: int---class _LiteralModel(BaseModel):- tone: Literal["Casual", "Professional", "Academic"] = Field(..., description="Tone")---class _NonSerializable:- """An object that is not JSON-serializable."""-- @override- def __repr__(self) -> str:- return "<NonSerializable>"---class TestData:- MISSING_FIELD: ClassVar[tuple[dict[str, Any], str]] = (- {"age": 25},- "missing_fields",- )- EXTRA_FIELD: ClassVar[tuple[dict[str, Any], str]] = (- {"name": "Alice", "age": 25, "unknown": "x"},- "extra_fields",- )- LARGE_INPUT: ClassVar[tuple[dict[str, Any], str]] = (- {"age": "A" * 500},- "missing_fields",- )- MULTIPLE_ERRORS: ClassVar[tuple[dict[str, Any], str]] = (- {"unknown": "x"},- "missing_fields",- )---class TestFormatPydanticValidationErrorForAgent:- """Tests for format_pydantic_validation_error_for_agent function."""-- @pytest.mark.parametrize(- ("input_data", "expected_category"),- [- TestData.MISSING_FIELD,- TestData.EXTRA_FIELD,- TestData.LARGE_INPUT,- TestData.MULTIPLE_ERRORS,- ],- ids=["missing_field", "extra_field", "large_input", "multiple_errors"],- )- def test_structured_details(self, input_data: dict[str, Any], expected_category: str) -> None:- """Test that structured details contain expected fields and categories."""- with pytest.raises(ValidationError) as exc_info:- _SimpleModel.model_validate(input_data)-- message, details = format_pydantic_validation_error_for_agent(exc_info.value)-- # Structure checks- assert details["model"] == "_SimpleModel"- assert details["error_count"] >= 1- assert expected_category in details["categories"]- assert len(details["errors"]) == details["error_count"]-- # Message checks- assert "Validation failed for _SimpleModel" in message- assert str(details["error_count"]) in message-- # Every error has required keys- for error in details["errors"]:- assert "field_path" in error- assert "error_type" in error- assert "message" in error- assert "input_value" in error- assert "context" in error-- def test_large_input_value_not_truncated(self) -> None:- """Test that large input values are NOT truncated (key improvement over raw pydantic)."""- large_value = "B" * 500-- class _ModelWithInt(BaseModel):- value: int-- with pytest.raises(ValidationError) as exc_info:- _ModelWithInt.model_validate({"value": large_value})-- _message, details = format_pydantic_validation_error_for_agent(exc_info.value)-- # The per-error input_value should contain the full large string, not truncated- error = details["errors"][0]- assert isinstance(error["input_value"], str)- assert len(error["input_value"]) == 500- assert error["input_value"] == large_value-- def test_literal_error_with_context(self) -> None:- """Test that literal errors include expected values in context."""- with pytest.raises(ValidationError) as exc_info:- _LiteralModel.model_validate({"tone": "InvalidTone"})-- message, details = format_pydantic_validation_error_for_agent(exc_info.value)-- assert details["model"] == "_LiteralModel"- assert "literal_errors" in details["categories"]- assert details["error_count"] == 1-- error = details["errors"][0]- assert error["field_path"] == "tone"- assert error["error_type"] == "literal_error"- assert error["input_value"] == "InvalidTone"- assert "expected" in error["context"]- assert "literal" in message.lower()-- def test_non_serializable_input_falls_back_to_repr(self) -> None:- """Test that non-JSON-serializable input values fall back to repr() without crashing."""-- class _ModelWithAny(BaseModel):- model_config = ConfigDict(extra="forbid")- value: int-- non_serializable = _NonSerializable()- with pytest.raises(ValidationError) as exc_info:- _ModelWithAny.model_validate({"value": non_serializable})-- message, details = format_pydantic_validation_error_for_agent(exc_info.value)-- assert details["error_count"] >= 1- # The non-serializable input should be represented as its repr string- error = details["errors"][0]- assert isinstance(error["input_value"], str)- assert "NonSerializable" in error["input_value"]- assert "Validation failed" in message-- def test_context_with_non_serializable_values_is_json_safe(self) -> None:- """Test that context values containing non-JSON-serializable objects are serialized safely."""-- class _ConstrainedModel(BaseModel):- score: int = Field(..., ge=10)-- with pytest.raises(ValidationError) as exc_info:- _ConstrainedModel.model_validate({"score": 5})-- _message, details = format_pydantic_validation_error_for_agent(exc_info.value)-- # The entire details dict must be JSON-serializable (no TypeError)- serialized = json.dumps(details)- assert isinstance(serialized, str)-- # Context should contain the 'ge' constraint value, serialized- error = details["errors"][0]- assert "context" in error- assert isinstance(error["context"], dict)-- def test_multiple_errors_all_reported(self) -> None:- """Test that all errors are reported with correct error_count."""- with pytest.raises(ValidationError) as exc_info:- _SimpleModel.model_validate({"unknown_field": "x"})-- message, details = format_pydantic_validation_error_for_agent(exc_info.value)-- # Should have at least 3 errors: missing 'name', missing 'age', extra 'unknown_field'- assert details["error_count"] >= 3- assert len(details["errors"]) == details["error_count"]- assert "missing_fields" in details["categories"]- assert "extra_fields" in details["categories"]- assert "errors" in message.lower()