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.
Remove pipe builder loop and related MTHDS workflows (#793)
Louis Choquel926fce46fd26
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cd34c84fc..5cbebc95d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,12 @@- **Agent CLI inputs**: Refactored `_inputs_core` to delegate to `builder.operations.inputs_ops.build_inputs_for_pipe` instead of duplicating bundle validation and input rendering logic.- **Agent CLI run**: Added graph generation support with ReactFlow HTML output and side-effect metadata tracking in `_run_core`.+### Removed++- **`BuilderLoop`** and its iterative build-validate-fix cycle (`builder_loop.py`, `builder.py`, `builder_errors.py`). The build-agent CLI now drives spec construction directly.+- **`pipelex build pipe`** CLI command and associated MTHDS workflow files (`builder.mthds`, `agentic_builder.mthds`, `pipe_design.mthds`, `concept_fixer.mthds`, `synthesize_image.mthds`).+- **`pipelex-tools` runtime dependency**: Moved to dev-only dependency; `plxt` is now invoked via subprocess passthrough.+## [v0.22.0] - 2026-03-25### Addeddiff --git a/pipelex/builder/CLAUDE.md b/pipelex/builder/CLAUDE.mdindex 363f90ba1..d7b319345 100644--- a/pipelex/builder/CLAUDE.md+++ b/pipelex/builder/CLAUDE.md@@ -1,25 +1,16 @@# Builder-Transforms high-level specifications into valid, executable Pipelex pipeline bundles (`.mthds` files). The builder is a spec-to-MTHDS compiler with built-in iterative repair.+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- ↑ |- | validate_bundle()- | |- └──── fix (up to N attempts) ─────── errors? ──→ done```-`BuilderLoop.build_and_fix()` orchestrates: build → validate → fix → re-validate loop.-## Code Layout```-builder.py # reconstruct_bundle_with_pipe_fixes() helper-builder_loop.py # BuilderLoop — the main orchestration class-builder_errors.py # Error typesexceptions.py # Exception typesconventions.py # File naming defaults (bundle.mthds, inputs.json)bundle_spec.py # PipelexBundleSpec — top-level spec model@@ -43,6 +34,14 @@ pipe/pipe_parallel_spec.py # PipeParallel — concurrent controllerpipe_condition_spec.py # PipeCondition — branching controllerpipe_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 and talent operations+ 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 operationstalents/llm_talent.py # LLMTalent enum + preset mappingextract_talent.py # ExtractTalent enum + preset mapping@@ -81,23 +80,6 @@ Pipe inputs and outputs use multiplicity suffixes on concept names:- `Text[]` — variable-length list- `Text[N]` — exactly N items-## BuilderLoop Fix Strategies--The loop applies these fixes automatically when validation fails:--| Problem | Fix |-|---------|-----|-| Undeclared concept | Generate via LLM ("generate_missing_concepts" pipeline), or remove from PipeParallel.combined_output |-| UNKNOWN_CONCEPT | Create concept that refines Text |-| INPUT_STUFF_SPEC_MISMATCH | Rewrite inputs from pipe.needed_inputs() |-| MISSING/EXTRANEOUS_INPUT_VARIABLE | Sync inputs with pipe.needed_inputs() |-| INADEQUATE_OUTPUT_CONCEPT (Sequence) | Set output = last step's output |-| INADEQUATE_OUTPUT_CONCEPT (Condition) | Set output = common output or native.Anything |-| INADEQUATE_OUTPUT_MULTIPLICITY | Match last step's output multiplicity |-| Compose multiplicity mismatch | Add `[]` to input concept, change field to list type |--After fixing, `_prune_unreachable_specs()` removes pipes unreachable from `main_pipe` and their unused concepts.-## Talent SystemTalents are abstract capability labels mapped to concrete model presets. They remain in `talents/` and are used by the `pipelex-agent models` CLI to help agents choose appropriate presets. PipeSpec subclasses accept model presets directly via a `model: str | None` field, bypassing talent resolution. When modifying talent enums, update both the enum and its preset mapping dict in `pipelex.toml`.diff --git a/pipelex/builder/agentic_builder.mthds b/pipelex/builder/agentic_builder.mthdsdeleted file mode 100644index 8375f04f0..000000000--- a/pipelex/builder/agentic_builder.mthds+++ /dev/null@@ -1,29 +0,0 @@-domain = "agentic_builder"-description = "Agent-focused builder sequences for structured generation. Assumes drafts are pre-generated."--# No concepts defined - reuses from builder and pipe_design domains--[pipe]--# PipeBatch to detail all pipe specs from signatures-[pipe.detail_all_pipe_specs]-type = "PipeBatch"-description = "Generate detailed specs for all pipe signatures by batching over them."-inputs = { plan_draft = "builder.PlanDraft", pipe_signatures = "pipe_design.PipeSignature[]", concept_specs = "builder.ConceptSpec[]" }-output = "pipe_design.PipeSpec[]"-input_list_name = "pipe_signatures"-input_item_name = "pipe_signature"-branch_pipe_code = "pipe_design.detail_pipe_spec"--# Main agent builder: from flow to bundle (skips all drafting)-[pipe.build_from_flow]-type = "PipeSequence"-description = "Build a complete PipelexBundleSpec from pre-generated flow and concepts. This is the main entry point for agent-driven building."-inputs = { brief = "builder.UserBrief", plan_draft = "builder.PlanDraft", prepared_flow = "builder.FlowDraft", concept_specs = "builder.ConceptSpec[]" }-output = "builder.PipelexBundleSpec"-steps = [- { pipe = "builder.design_pipe_signatures", result = "pipe_signatures" },- { pipe = "builder.write_bundle_header", result = "bundle_header_spec" },- { pipe = "detail_all_pipe_specs", result = "pipe_specs" },- { pipe = "builder.assemble_pipelex_bundle_spec", result = "pipelex_bundle_spec" },-]diff --git a/pipelex/builder/builder.mthds b/pipelex/builder/builder.mthdsdeleted file mode 100644index 852b4a96b..000000000--- a/pipelex/builder/builder.mthds+++ /dev/null@@ -1,379 +0,0 @@-domain = "builder"-description = "Auto-generate a Pipelex bundle (concepts + pipes) from a short user brief."--[concept]-UserBrief = "A short, natural-language description of what the user wants."-PlanDraft = "Natural-language pipeline plan text describing sequences, inputs, outputs."-ConceptDrafts = "Textual draft of the concepts to create."-PipelexBundleSpec = "A Pipelex bundle spec."-BundleHeaderSpec = "A domain information object."-FlowDraft = "Draft of the flow of the pipeline."--## Concepts-ConceptStructureSpec = "A concept spec with structure but without full implementation."-ConceptSpec = "A specification for a concept including its code, description, and a structure draft as plain text."---[pipe]-[pipe.pipe_builder]-type = "PipeSequence"-description = "This pipe is going to be the entry point for the builder. It will take a UserBrief and return a PipelexBundleSpec."-inputs = { brief = "UserBrief" }-output = "PipelexBundleSpec"-steps = [- { pipe = "draft_the_plan", result = "plan_draft" },- { pipe = "draft_the_concepts", result = "concept_drafts" },- { pipe = "structure_concepts", result = "concept_specs" },- { pipe = "draft_flow", result = "flow_draft" },- { pipe = "review_flow", result = "prepared_flow" },- { pipe = "design_pipe_signatures", result = "pipe_signatures" },- { pipe = "write_bundle_header", result = "bundle_header_spec" },- { pipe = "pipe_design.detail_pipe_spec", batch_over = "pipe_signatures", batch_as = "pipe_signature", result = "pipe_specs" },- { pipe = "assemble_pipelex_bundle_spec", result = "pipelex_bundle_spec" },-]--[pipe.draft_the_plan]-type = "PipeLLM"-description = "Turn the brief into a pseudo-code plan describing controllers, pipes, their inputs/outputs."-inputs = { brief = "UserBrief" }-output = "PlanDraft"-model = "$pipe-builder-engineering"-prompt = """-# Return a draft of a plan that narrates the pipeline as pseudo-steps (no code):-- For each pipe: state the pipe's description, inputs (by name using snake_case), and the output (by name using snake_case),-DO NOT indicate the inputs or output type. Just name them.-- Note where you will want structured outputs or inputs.--## Memory and flow:-- We have a memory system: the outputs of each pipe are added to the memory and can be used as inputs by subsequent pipes.-- The pipeline's initial inputs are added to the memory at the beginning.-- You don't need to flatten lists at the end or even in intermediate steps: our system manages branching and the memory flows into each branch.-- At the end of the pipeline, all the memory is delivered. However, consider adding a final COMPOSE step when:- - The brief asks for a cohesive deliverable (report, document, result, summary, card, profile, package)- - Multiple related outputs should be bundled as a single structured object- - The user would benefit from a unified output rather than scattered variables-- Skip the final composition only when the outputs are truly independent or when the user explicitly wants separate items.--## Available orchestration controllers:-- SEQUENCE: execute a sequence of pipes in order. It must reference the pipes it will execute.-- BATCH: concurrently executes THE SAME pipe on each element of a list taken from the memory. BATCH is a map operator: it transforms the input list in a new list of outputs, so if you want to apply several steps to the individual items, the batch MUST branch into a SEQUENCE of these steps.-- PARALLEL: concurrently executes DIFFERENT PIPES on any stuff from the memory. The outputs of each of the parallel pipes will be usable in the following steps.-- CONDITION: branches to a specific pipe, based on the evaluation of a conditional expression and according to an outcome map. There can also be a default outcome.--When describing the task of a pipe controller, be concise, don't detail all the sub-pipes but list the pipes they will use.--## Available pipe operators:-- LLM: uses a Vision/LLM to generate text or structured objects. It can generate single items or lists of items.-- IMG_GEN: uses an AI model to generate images from a prompt that is either the result of a previous step or part of the pipeline's original inputs. As the image generation prompt MUST be a text, you can plan to use an LLM step to write it.-- EXTRACT: extracts content from an image or a document, always outputs a list of pages (possibly a list of one page). Use it only when you need to use OCR or document extraction.-- COMPOSE: combines variables from working memory into a new structured object using field composition (construct mode) or renders a Jinja2 template to produce Text/Html output (template mode).- Use COMPOSE at the end of a pipeline when the brief implies a unified deliverable. For example:- - A "report" combining analysis, findings, and recommendations- - A "product card" combining description, price, and image- - A "profile" combining biography, skills, and achievements-------## Final output decision:-Ask yourself: "Would the user prefer to receive one cohesive object or multiple separate pieces?"-- If the brief mentions words like "report", "document", "card", "profile", "summary", "package", "bundle" → likely needs a final COMPOSE-- If the brief lists multiple things that logically go together → likely needs a final COMPOSE-- If the outputs are independent items to be used separately → no final COMPOSE needed-------Now let's write the plan.--Make it narrative concise markdown format, no need to write tags such as "Description:", just write what you need to write.-Do not write any intro or outro, just write the plan.--What is important is to name the variables, from the initial inputs to the final outputs.-And the variable names must be consistent between the various steps.-In case of multiple items used as list in inputs or outputs, name them with a plural variable name when they are multiple, but then use the singular variable name when working with each item of the list.--It's also VERY IMPORTANT to list all the variables used by each pipe. All the memory is available, yes, so you can combine any inputs, but you must state which ones you will actually use in each pipe.--Apply the DRY principle: don't repeat yourself. if you have a task to apply several times, describe it as a dedicated pipe.--@brief--"""--[pipe.draft_the_concepts]-type = "PipeLLM"-description = "Interpret the draft of a plan to create an AI pipeline, and define the needed concepts."-inputs = { plan_draft = "PlanDraft", brief = "UserBrief" }-output = "ConceptDrafts"-model = "$pipe-builder-engineering"-prompt = """-We are working on writing an AI pipeline to fulfill this brief:-@brief--We have already written a plan for the pipeline. It's built using pipes, each with its own inputs (one or more) and output (single).-Your job is to clarify the different concepts used in the plan.--Variables are snake_case and concepts are PascalCase.--We want clear concepts but we don't want too many concepts. If a concept can be reused in the pipeline, it's the same concept.-For instance:-- If you have a "FlowerDescription" concept, then it can be used for rose_description, tulip_description, beautiful_flower_description, dead_flower_description, etc.-- DO NOT define concepts that include adjectives: "LongArticle" is wrong, "Article" is right.-- DO NOT include circumstances in the concept description:- "ArticleAboutApple" is wrong, "Article" is right.- "CounterArgument" is wrong, "Argument" is right.-- Concepts are always expressed as singular nouns, even if we're to use them as a list:- for instance, define the concept as "Article" not "Articles", "Employee" not "Employees".- If we need multiple items, we'll indicate it elsewhere so you don't bother with it here.-- Provide a concise description for each concept--If the concept can be expressed as a text, html, image, document, number, or page:-- Name the concept, define it and just write "refines: Text", "refines: Html" (for HTML content), "refines: Document" (and note that PDF is a document), or "refines: Image" etc.-- No need to define its structure-Else, if you need structure for your concept, draft its structure:-- field name in snake_case-- description:- - description: the description of the field, in natural language- - type: the type of the field:- - text, integer, boolean, number, date for primitive values- - concept when the field should contain a previously-defined structured concept- - concept_ref: (only when type=concept) the name of the referenced concept (e.g., "CVAnalysis")- - required: add required = true if the field is required (otherwise, leave it empty)- - default_value: the default value of the field--When building composite/aggregate concepts that combine multiple other concepts:-- Use type=concept with concept_ref to reference the other structured concepts-- Example: if ProjectReport needs to include ProjectSummary, RiskAnalysis, and BudgetBreakdown, each field should use type=concept with the appropriate concept_ref, NOT type=text-- This allows proper object composition rather than flattening structured data into text--@plan_draft--DO NOT redefine native concepts: Text, Html, Image, Document, Number, Page, TextAndImages, ImgGenPrompt, JSON, Anything, Dynamic. They are built-in and must NOT be redeclared.--Do not write any intro or outro, do not mention the brief or the plan draft, just write the concept drafts.-List the concept drafts in Markdown format with a heading 3 for each, e.g. `### Concept FooBar`.-"""--[pipe.structure_concepts]-type = "PipeLLM"-description = "Structure the concept definitions."-inputs = { concept_drafts = "ConceptDrafts" }-output = "ConceptSpec[]"-model = "$pipe-builder-engineering"-system_prompt = """-You are an expert at data extraction and json formatting.-"""-prompt = """-@concept_drafts-"""---[pipe.draft_flow]-type = "PipeLLM"-description = "Draft the flow of the pipeline."-inputs = { plan_draft = "PlanDraft", brief = "UserBrief", concept_specs = "ConceptSpec[]" }-output = "FlowDraft"-model = "$pipe-builder-engineering"-system_prompt = """-You are a Senior engineer.-"""-prompt = """-# Your job is to structure the flow we have drafted based on a brief:--@brief--@plan_draft--{% if concept_specs %}-We have already defined the concepts you must use for the inputs and outputs of the pipes:-@concept_specs-And of course you still have the native concepts if required: Text, Html, Image, Document, Number, Page, TextAndImages, ImgGenPrompt, JSON, Anything, Dynamic.-{% else %}-You can use the native concepts for the inputs and outputs of the pipes, as required: Text, Html, Image, Document, Number, Page, TextAndImages, ImgGenPrompt, JSON, Anything, Dynamic.-{% endif %}--## For PipeOperators:--The flow you design must include the contracts for each of the PipeOperators to use: PipeLLM, PipeImgGen, PipeExtract, PipeCompose.-Shape of the contract for PipeOperator is:-- type: PipeLLM | PipeImgGen | PipeExtract | PipeCompose-- description: What the pipe does (string)-- inputs: Dictionary mapping variable names (snake_case) to concept codes (PascalCase), possibly with multiplicity brackets.-- result: Variable name for the pipe's result (snake_case). Can be referenced in subsequent pipes.-- output: Output concept code (PascalCase) possibly with multiplicity: 'Text' (single), 'Article[]' (list), 'Image[5]' (exactly 5).--**PipeCompose** has two modes:-- Template mode: Renders a template using variables from working memory. Output must be Text (or a concept that refines Text), or Html (or a concept that refines Html) if generating HTML content. Use for generating formatted text/documents.-- Construct mode: Composes a StructuredContent object by mapping fields from working memory variables. Use for assembling structured objects from multiple sources.- - PREFER `{ from = "the_varname" }` for direct object assignment- - Use `{ template = "..." }` ONLY for string composition (combining prefix with a variable)--## For the PipeControllers, which really define the flow, we need a more detailed contract, related to each type of controller:--### Start with the same contract as pipe operators above:-- type: PipeSequence | PipeParallel | PipeCondition | PipeBatch-- description: ditto-- inputs: ditto-- result: ditto-- output: ditto--### Then add the details for each type of controller:--**PipeSequence:**-- steps: List of sub-pipes to execute sequentially. Each step has: pipe (name of the pipe to execute), result (variable name).--**PipeParallel:**-- branches: List of sub-pipes to execute concurrently.-- add_each_output: Boolean - include individual outputs in combined result.-- combined_output: Optional ConceptCode (PascalCase) for combined structure.--**PipeBatch:**-- branch_pipe_code: Pipe to apply to each item in the list (applied concurrently to all items).-- For PipeBatch, 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_list_name: List variable to iterate over (snake_case, plural).-- input_item_name: Name for individual items in each branch (snake_case, singular).-- IMPORTANT: input_list_name should be a PLURAL noun, and input_item_name should be the- SINGULAR form. They must be DIFFERENT from each other, and input_item_name must not match- any key in the batch pipe's inputs dict.- Examples: list "items" → item "item", list "report_data" → item "single_report_data".--**PipeCondition:**-- jinja2_expression_template: Jinja2 expression to evaluate.-- outcomes: Mapping dict[str, str] of expression results to pipe codes.-- default_outcome: Add a default outcome to the outcomes map.-Becareful, the outputs "fail" and "continue" are special outcomes, they are not pipe codes.--> "continue" is a special outcome that allows to continue the sequence, "fail" is a special outcome that fails the whole pipeline. To use with caution.--## More rules:-- For each pipe: give a unique snake_case pipe_code, based on a verb, and craft description of what the pipe does.-- When specifying the inputs and outputs of the pipes, you must indicate the concept associated to each variable name.-- The output concept of a PipeSequence must always be the same as the output concept of the last pipe in the sequence.-- Regarding PipeImgGen, which uses an AI model to generate images from a text prompt: as the image generation prompt MUST be a text, you must use a PipeLLM step to write the prompt, unless the prompt is part of the pipeline's initial inputs.-- When a variable comprises multiple items, use bracket notation along with the SINGULAR concept:- - The concept is singular, like "Article" (not "Articles")- - You can set output = "Article[]" to get a list of arbitrary length, or set output = "Article[5]" for exactly 5 items- - Examples: output = "Text[]" (multiple texts), output = "Image[3]" (exactly 3 images), output = "Employee[]" (list of employees)- - In particular, a PipeBatch always as an input which is a list on which it is batching, use indeterminate multiplicity for the list, i.e. "Concept[]".--## Flow:-- We have a memory system: the outputs of each pipe are added to the memory and can be used as inputs by subsequent pipes.-- The pipeline's initial inputs are added to the memory at the beginning.-- You don't need to flatten lists at the end or even in intermediate steps: our system manages branching and the memory flows into each branch.-- At the end of the pipeline, all the memory is delivered. However, consider adding a final PipeCompose step when:- - The brief asks for a cohesive deliverable (report, document, result, summary, card, profile, package)- - Multiple related outputs should be bundled as a single structured object- - The user would benefit from a unified output rather than scattered variables-- Skip the final composition only when the outputs are truly independent or when the user explicitly wants separate items.-- If you have a sequence which has only one step, then don't make that a sequence, make it a single pipe. Or check if you forgot to include another step maybe.-- If you're in a sequence and you are to apply a pipe to a previous output which is multiple, use a PipeBatch step.-- PipeBatch is a map operator: it transforms the input list in a new list of outputs, so if you want to apply several steps to the individual items, the branch_pipe_code MUST be a PipeSequence of these steps.-- Apply the DRY principle: don't repeat yourself. if you have a task to apply several times, make it a dedicated pipe you can use and reuse.--IMPORTANT: define the main pipe of the pipeline, i.e. unless it's a single pipe workflow, the main pipe is the overall orchestrator sequence of the whole pipeline. Give it a clear name, make it clear it's the main pipe in a "# Comment", but don't name it "main" or "orchestrator" or "pipeline", just state it's main in a comment.--If the main pipe has an input which is multiple (a list) then don't hesitate to batch over it.--At the end, recap the list of variables used, with a super concise recap of what they represent, also state their concept and multiplicity, and if the concept refines a native concept, state it too. Btw, by default, unstructured concepts refine Text, state it when it's the case.-"""---[pipe.review_flow]-type = "PipeLLM"-description = "Review a draft flow and make it consistent."-inputs = { flow_draft = "FlowDraft", brief = "UserBrief" }-output = "FlowDraft"-model = "$pipe-builder-engineering"-system_prompt = """-You are a Senior engineer.-"""-prompt = """-Your job is to review a draft flow that was designed from a bried.--@brief--@flow_draft--Recap the flow by narrating the we have step by step, from the beginning to the end.-Is the flow consistent? Issues to watch out for:-- Do we have a main pipe appropriate to answer the brief? Otherwise we'll have to add one.-- Check that the inputs of the main pipe are consistent with the brief. For instance it should not require as input some variable which is to be generated by its own flow steps.-- If the main pipe has an input which is multiple (a list), are we correctly batching over it?-- Are there any missing variables or variable names that are not the expected names?-- PipeImgGen must take a single input which must be a text or a concept that refines text, if it's not the case, it needs fixing. For instance if the input is some structured concept, you'll have to add a PipeLLM step to write the prompt from the structured concept.-- Does the pipeline produce multiple related outputs that should be delivered as a single cohesive object? If the brief implies a unified deliverable (report, document, card, profile, summary), consider adding a final PipeCompose step to bundle them.--If the flow is consistent, state it in a declarative sentence like "The flow has been checked and is consistent:" and then copy the flow like you received it.--Otherwise, state that it was fixed like "The flow has been checked and fixed:" and then write the fixed flow. Your fixed flow must be flawless and consistent.-"""--[pipe.design_pipe_signatures]-type = "PipeLLM"-description = "Write the pipe signatures for the plan."-inputs = { prepared_flow = "FlowDraft", brief = "UserBrief" }-output = "pipe_design.PipeSignature[]"-model = "$pipe-builder-engineering"-system_prompt = """-You are a Senior engineer.-"""-prompt = """-# Your job is to structure the required PipeSignatures that make up the AI workflow we have prepared based on a brief.--@brief--@prepared_flow--## The PipeSignatures are like contracts for the pipes to build:-- For each pipe: give a unique snake_case pipe_code, based on a verb, and craft description of what the pipe does.-- Be clear which is the main pipe of the pipeline, don't write "main" in its pipe_code, but make it clear in its description.-- Contrary to the draft, now when specifying the inputs and outputs of the pipes, you must indicate the concept associated to each variable name.-- When a variable comprises multiple items, use bracket notation along with the SINGULAR concept:- - The concept is singular, like "Article" (not "Articles")- - You can set output = "Article[]" to get a list of arbitrary length, or set output = "Article[5]" for exactly 5 items- - Examples: output = "Text[]" (multiple texts), output = "Image[3]" (exactly 3 images), output = "Employee[]" (list of employees)-- The output concept of a PipeSequence must always be the same as the output concept of the last pipe in the sequence.-- Pipe controllers (PipeSequence, PipeParallel, PipeCondition) depend on other pipes, so you must list these dependencies in the pipe_dependencies attribute.-- Regarding PipeImgGen, which uses an AI model to generate images from a text prompt: as the image generation prompt MUST be a text, you must use a PipeLLM step to write the prompt, unless it's part of the pipeline's initial inputs.---## Flow:-- We have a memory system: the outputs of each pipe are added to the memory and can be used as inputs by subsequent pipes.-- The pipeline's initial inputs are added to the memory at the beginning.-- You don't need to flatten lists at the end or even in intermediate steps: our system manages branching and the memory flows into each branch.-- At the end of the pipeline, all the memory is delivered. However, if the flow ends with a final PipeCompose step to bundle multiple outputs into a cohesive deliverable, ensure the pipe signatures reflect this.-"""--[pipe.write_bundle_header]-type = "PipeLLM"-description = "Write the bundle header."-inputs = { brief = "UserBrief", pipe_signatures = "pipe_design.PipeSignature" }-output = "BundleHeaderSpec"-model = "$pipe-builder-engineering"-prompt = """-Name and define the domain of this process:-@brief--@pipe_signatures--For example, if the brief is about generating and analyzing a compliance matrix out of a RFP,-the domain would be "rfp_compliance" and the description would be "Generating and analyzing compliance related to RFPs".-The domain name should be not more than 4 words, in snake_case.-For the description, be concise.-The main pipe is the one that will carry out the main task of the pipeline, it should be pretty obvious to identify.-"""--[pipe.assemble_pipelex_bundle_spec]-type = "PipeCompose"-description = "Compile the pipelex bundle spec."-inputs = { pipe_specs = "pipe_design.PipeSpec[]", concept_specs = "ConceptSpec[]", bundle_header_spec = "BundleHeaderSpec" }-output = "PipelexBundleSpec"--[pipe.assemble_pipelex_bundle_spec.construct]-domain = { from = "bundle_header_spec.domain_code" }-description = { from = "bundle_header_spec.description" }-system_prompt = { from = "bundle_header_spec.system_prompt" }-main_pipe = { from = "bundle_header_spec.main_pipe" }-concept = { from = "concept_specs", list_to_dict_keyed_by = "the_concept_code" }-pipe = { from = "pipe_specs", list_to_dict_keyed_by = "pipe_code" }diff --git a/pipelex/builder/builder.py b/pipelex/builder/builder.pydeleted file mode 100644index dbe7c75fd..000000000--- a/pipelex/builder/builder.py+++ /dev/null@@ -1,17 +0,0 @@-from pipelex.builder.builder_errors import (- PipelexBundleUnexpectedError,-)-from pipelex.builder.bundle_spec import PipelexBundleSpec-from pipelex.builder.pipe.pipe_spec_union import PipeSpecUnion---def reconstruct_bundle_with_pipe_fixes(pipelex_bundle_spec: PipelexBundleSpec, fixed_pipes: list[PipeSpecUnion]) -> PipelexBundleSpec:- if not pipelex_bundle_spec.pipe:- msg = "No pipes section found in bundle spec"- raise PipelexBundleUnexpectedError(msg)-- for fixed_pipe_blueprint in fixed_pipes:- pipe_code = fixed_pipe_blueprint.pipe_code- pipelex_bundle_spec.pipe[pipe_code] = fixed_pipe_blueprint-- return pipelex_bundle_specdiff --git a/pipelex/builder/builder_errors.py b/pipelex/builder/builder_errors.pydeleted file mode 100644index c862ed7a8..000000000--- a/pipelex/builder/builder_errors.py+++ /dev/null@@ -1,17 +0,0 @@-from pipelex.base_exceptions import PipelexError-from pipelex.core.memory.working_memory import WorkingMemory-from pipelex.types import Self---class PipeBuilderError(PipelexError):- def __init__(self: Self, message: str, working_memory: WorkingMemory | None = None) -> None:- self.working_memory = working_memory- super().__init__(message)---class ConceptSpecError(PipelexError):- """Details of a single concept failure during dry run."""---class PipelexBundleUnexpectedError(PipelexError):- """Raised when an unexpected error occurs during validation."""diff --git a/pipelex/builder/builder_loop.py b/pipelex/builder/builder_loop.pydeleted file mode 100644index 5dc994836..000000000--- a/pipelex/builder/builder_loop.py+++ /dev/null@@ -1,1155 +0,0 @@-import re-from pathlib import Path-from typing import TYPE_CHECKING, cast--from mthds.models.pipeline_inputs import PipelineInputs-from mthds.package.bundle_scanner import build_domain_exports_from_scan, scan_bundles_for_domain_info-from mthds.package.discovery import MANIFEST_FILENAME-from mthds.package.manifest.parser import serialize_manifest_to_toml-from mthds.package.manifest.schema import MethodsManifest--from pipelex import builder, log-from pipelex.builder.builder import (- PipelexBundleSpec,- PipeSpecUnion,- reconstruct_bundle_with_pipe_fixes,-)-from pipelex.builder.builder_errors import PipeBuilderError-from pipelex.builder.concept.concept_spec import ConceptSpec, ConceptStructureSpecFieldType-from pipelex.builder.exceptions import PipelexBundleSpecBlueprintError-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_parallel_spec import PipeParallelSpec-from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.config import get_config-from pipelex.core.concepts.native.concept_native import NativeConceptCode-from pipelex.core.pipes.exceptions import PipeFactoryErrorType, PipeValidationErrorType-from pipelex.core.pipes.pipe_blueprint import PipeCategory-from pipelex.core.pipes.variable_multiplicity import format_concept_with_multiplicity, parse_concept_with_multiplicity-from pipelex.core.qualified_ref import QualifiedRef-from pipelex.graph.graphspec import GraphSpec-from pipelex.hub import get_required_pipe-from pipelex.language.mthds_factory import MthdsFactory-from pipelex.pipe_controllers.condition.special_outcome import SpecialOutcome-from pipelex.pipeline.runner import PipelexRunner-from pipelex.pipeline.validate_bundle import ValidateBundleError, validate_bundle-from pipelex.system.configuration.configs import PipelineExecutionConfig-from pipelex.tools.misc.file_utils import get_incremental_file_path, save_text_to_path-from pipelex.tools.misc.json_utils import save_as_json_to_path-from pipelex.tools.misc.string_utils import get_root_from_dotted_path--if TYPE_CHECKING:- from pipelex.pipe_controllers.condition.pipe_condition import PipeCondition---class BuilderLoop:- async def build_and_fix(- self,- builder_pipe: str,- inputs: PipelineInputs | None = None,- execution_config: PipelineExecutionConfig | None = None,- is_save_first_iteration_enabled: bool = True,- is_save_second_iteration_enabled: bool = True,- is_save_working_memory_enabled: bool = True,- output_dir: str | None = None,- ) -> tuple[PipelexBundleSpec, GraphSpec | None]:- # TODO: Doesn't make sense to be able to put a builder_pipe code but hardcoding the Path to the builder pipe.- runner = PipelexRunner(- library_dirs=[str(Path(builder.__file__).parent)],- execution_config=execution_config,- )- response = await runner.execute_pipeline(- pipe_code=builder_pipe,- inputs=inputs,- )- pipe_output = response.pipe_output-- if is_save_working_memory_enabled:- working_memory_path = get_incremental_file_path(- base_path=output_dir or "results/pipe-builder",- base_name="working_memory",- extension="json",- )- save_as_json_to_path(object_to_save=pipe_output.working_memory.smart_dump(), path=str(working_memory_path), create_directory=True)-- pipelex_bundle_spec = pipe_output.working_memory.get_stuff_as(name="pipelex_bundle_spec", content_type=PipelexBundleSpec)- if pipelex_bundle_spec.pipe:- log.debug(f"Builder produced spec with pipe keys: {list(pipelex_bundle_spec.pipe.keys())}")- log.debug(f"Builder produced spec with main_pipe: '{pipelex_bundle_spec.main_pipe}'")- pipelex_bundle_spec = self._strip_native_concept_declarations(pipelex_bundle_spec=pipelex_bundle_spec)- pipelex_bundle_spec = self._strip_namespace_from_pipe_codes(pipelex_bundle_spec=pipelex_bundle_spec)-- if pipelex_bundle_spec.pipe:- for pipe_key, pipe_spec in pipelex_bundle_spec.pipe.items():- pipe_detail = f"key='{pipe_key}', pipe_code='{pipe_spec.pipe_code}', type={pipe_spec.type}"- if isinstance(pipe_spec, PipeBatchSpec):- pipe_detail += f", branch_pipe_code='{pipe_spec.branch_pipe_code}'"- elif isinstance(pipe_spec, PipeSequenceSpec):- step_codes = [step.pipe_code for step in pipe_spec.steps]- pipe_detail += f", step_pipe_codes={step_codes}"- elif isinstance(pipe_spec, PipeParallelSpec):- branch_codes = [branch.pipe_code for branch in pipe_spec.branches]- pipe_detail += f", branch_pipe_codes={branch_codes}"- elif isinstance(pipe_spec, PipeConditionSpec):- pipe_detail += f", outcome_values={list(pipe_spec.outcomes.values())}"- log.debug(f" Pipe spec: {pipe_detail}")-- if is_save_first_iteration_enabled:- try:- mthds_content = MthdsFactory.make_mthds_content(blueprint=pipelex_bundle_spec.to_blueprint())- first_iteration_path = get_incremental_file_path(- base_path=output_dir or "results/pipe-builder",- base_name="generated_pipeline_1st_iteration",- extension="mthds",- )- save_text_to_path(text=mthds_content, path=str(first_iteration_path), create_directory=True)- except PipelexBundleSpecBlueprintError as exc:- log.warning(f"Could not save first iteration MTHDS: {exc}")-- max_attempts = get_config().pipelex.builder_config.fix_loop_max_attempts- for attempt in range(1, max_attempts + 1):- log.debug(f"Fix loop attempt {attempt}/{max_attempts}")-- # Phase 1: Create blueprint from spec- log.debug("Phase 1: creating blueprint from spec")- try:- bundle_blueprint = pipelex_bundle_spec.to_blueprint()- except PipelexBundleSpecBlueprintError as exc:- log.debug("Phase 1: blueprint creation failed")- if attempt < max_attempts:- log.info(f"⚠️ Blueprint creation failed on attempt {attempt}/{max_attempts}, fixing undeclared concepts...")- pipelex_bundle_spec = await self._fix_undeclared_concept_references(pipelex_bundle_spec=pipelex_bundle_spec)- pipelex_bundle_spec = self._strip_native_concept_declarations(pipelex_bundle_spec=pipelex_bundle_spec)- pipelex_bundle_spec = self._strip_namespace_from_pipe_codes(pipelex_bundle_spec=pipelex_bundle_spec)- continue- msg = f"Failed to create bundle blueprint after {max_attempts} attempts: {exc}"- raise PipeBuilderError(msg) from exc-- log.debug("Phase 1: blueprint created successfully")-- # Phase 2: Validate the bundle- log.debug("Phase 2: validating bundle")- try:- await validate_bundle(blueprints=[bundle_blueprint])- log.debug("Phase 2: validation passed")- if attempt > 1:- log.info(f"✅ Bundle validation passed after fixes (attempt {attempt}/{max_attempts})")- break # Validation passed- except ValidateBundleError as exc:- if attempt < max_attempts:- log.info(f"⚠️ Validation failed on attempt {attempt}/{max_attempts}, attempting fixes...")- pipelex_bundle_spec = self._fix_bundle_validation_error(- bundle_error=exc,- pipelex_bundle_spec=pipelex_bundle_spec,- is_save_second_iteration_enabled=is_save_second_iteration_enabled,- output_dir=output_dir,- )- if pipelex_bundle_spec.pipe:- log.debug(f"After Phase 2 fix: pipe keys={list(pipelex_bundle_spec.pipe.keys())}")- pipelex_bundle_spec = self._strip_native_concept_declarations(pipelex_bundle_spec=pipelex_bundle_spec)- pipelex_bundle_spec = self._strip_namespace_from_pipe_codes(pipelex_bundle_spec=pipelex_bundle_spec)- else:- log.error(f"❌ Validation failed after {max_attempts} attempts, raising error")- # Save the last bundle state so the user can inspect/fix it manually- try:- mthds_content = MthdsFactory.make_mthds_content(blueprint=pipelex_bundle_spec.to_blueprint())- failed_bundle_path = get_incremental_file_path(- base_path=output_dir or "results/pipe-builder",- base_name="failed_bundle",- extension="mthds",- )- save_text_to_path(text=mthds_content, path=str(failed_bundle_path), create_directory=True)- log.warning(f"Last bundle state saved to: {failed_bundle_path}")- exc.failed_bundle_path = str(failed_bundle_path)- except Exception as save_exc:- log.warning(f"Could not save failed bundle state: {save_exc}")- raise-- return pipelex_bundle_spec, pipe_output.graph_spec-- async def _fix_undeclared_concept_references(- self,- pipelex_bundle_spec: PipelexBundleSpec,- ) -> PipelexBundleSpec:- """Fix undeclared concept references in pipe and concept specs.-- Collects all concept references from pipe specs and concept definitions (refines,- structure concept_ref, item_concept_ref), determines which are undeclared,- fixes PipeParallel combined_output references deterministically, and generates- ConceptSpec definitions for any remaining undeclared concepts via an LLM pipeline.- """- # Step 1: Collect all local concept references from pipe specs and concept definitions- concept_references: list[tuple[str, str, str]] = [] # (bare_concept_code, source_description, field_context)- if pipelex_bundle_spec.pipe:- for pipe_code, pipe_spec in pipelex_bundle_spec.pipe.items():- source = f"pipe '{pipe_code}'"- # Parse output — skip cross-package refs- output_parse = parse_concept_with_multiplicity(pipe_spec.output)- output_concept = output_parse.concept_ref_or_code- if not QualifiedRef.has_cross_package_prefix(output_concept):- if "." not in output_concept or output_concept.split(".")[0] == pipelex_bundle_spec.domain:- bare_code = output_concept.split(".")[-1] if "." in output_concept else output_concept- concept_references.append((bare_code, source, "output"))-- # Parse inputs — skip cross-package refs- if pipe_spec.inputs:- for input_name, input_concept_str in pipe_spec.inputs.items():- input_parse = parse_concept_with_multiplicity(input_concept_str)- input_concept = input_parse.concept_ref_or_code- if not QualifiedRef.has_cross_package_prefix(input_concept):- if "." not in input_concept or input_concept.split(".")[0] == pipelex_bundle_spec.domain:- bare_code = input_concept.split(".")[-1] if "." in input_concept else input_concept- concept_references.append((bare_code, source, f"input '{input_name}'"))-- # Parse PipeParallel combined_output — skip cross-package refs- if isinstance(pipe_spec, PipeParallelSpec) and pipe_spec.combined_output:- combined_parse = parse_concept_with_multiplicity(pipe_spec.combined_output)- combined_concept = combined_parse.concept_ref_or_code- if not QualifiedRef.has_cross_package_prefix(combined_concept):- if "." not in combined_concept or combined_concept.split(".")[0] == pipelex_bundle_spec.domain:- bare_code = combined_concept.split(".")[-1] if "." in combined_concept else combined_concept- concept_references.append((bare_code, source, "combined_output"))-- # Collect concept references from concept definitions (refines, structure concept_ref, item_concept_ref)- if pipelex_bundle_spec.concept:- for concept_code, concept_spec_or_name in pipelex_bundle_spec.concept.items():- if not isinstance(concept_spec_or_name, ConceptSpec):- continue- source = f"concept '{concept_code}'"-- # Check refines — skip cross-package refs- if concept_spec_or_name.refines:- ref = concept_spec_or_name.refines- if not QualifiedRef.has_cross_package_prefix(ref) and ("." not in ref or ref.split(".")[0] == pipelex_bundle_spec.domain):- bare_code = ref.split(".")[-1] if "." in ref else ref- concept_references.append((bare_code, source, "refines"))-- # Check structure fields — skip cross-package refs- if concept_spec_or_name.structure:- for field_name, field_spec in concept_spec_or_name.structure.items():- if field_spec.concept_ref:- ref = field_spec.concept_ref- if not QualifiedRef.has_cross_package_prefix(ref):- if "." not in ref or ref.split(".")[0] == pipelex_bundle_spec.domain:- bare_code = ref.split(".")[-1] if "." in ref else ref- concept_references.append((bare_code, source, f"structure.{field_name}.concept_ref"))- if field_spec.item_concept_ref:- ref = field_spec.item_concept_ref- if not QualifiedRef.has_cross_package_prefix(ref):- if "." not in ref or ref.split(".")[0] == pipelex_bundle_spec.domain:- bare_code = ref.split(".")[-1] if "." in ref else ref- concept_references.append((bare_code, source, f"structure.{field_name}.item_concept_ref"))-- # Step 2: Determine which are undeclared- declared_concepts: set[str] = set()- if pipelex_bundle_spec.concept:- declared_concepts = set(pipelex_bundle_spec.concept.keys())- native_concept_codes = {native.value for native in NativeConceptCode.values_list()}-- undeclared: set[str] = set()- undeclared_refs: list[tuple[str, str, str]] = []- for ref_code, source_desc, field_context in concept_references:- if ref_code not in declared_concepts and ref_code not in native_concept_codes:- undeclared.add(ref_code)- undeclared_refs.append((ref_code, source_desc, field_context))-- if not undeclared:- return pipelex_bundle_spec-- log.info(f"🔍 Found {len(undeclared)} undeclared concept(s): {', '.join(sorted(undeclared))}")-- # Step 3: Fix PipeParallel combined_output deterministically (no pipeline needed)- if pipelex_bundle_spec.pipe:- for pipe_code, pipe_spec in pipelex_bundle_spec.pipe.items():- if not isinstance(pipe_spec, PipeParallelSpec):- continue- if not pipe_spec.combined_output:- continue-- combined_parse = parse_concept_with_multiplicity(pipe_spec.combined_output)- combined_concept = combined_parse.concept_ref_or_code- bare_combined = combined_concept.split(".")[-1] if "." in combined_concept else combined_concept-- if bare_combined not in undeclared:- continue-- if pipe_spec.add_each_output:- log.info(f"🔧 Removing undeclared combined_output '{pipe_spec.combined_output}' from PipeParallel '{pipe_code}'")- pipe_spec.combined_output = None-- # Also fix output if it references an undeclared concept- output_parse = parse_concept_with_multiplicity(pipe_spec.output)- output_concept = output_parse.concept_ref_or_code- bare_output = output_concept.split(".")[-1] if "." in output_concept else output_concept- if bare_output in undeclared:- log.info(f"🔧 Setting output of PipeParallel '{pipe_code}' to 'Anything'")- pipe_spec.output = "Anything"-- # Recompute undeclared: some concepts may no longer be referenced after PipeParallel fixes- still_referenced = self._collect_local_bare_concept_codes(pipelex_bundle_spec=pipelex_bundle_spec)- no_longer_referenced = undeclared - still_referenced- if no_longer_referenced:- log.info(f"🔧 Concepts no longer referenced after PipeParallel fixes: {', '.join(sorted(no_longer_referenced))}")- undeclared -= no_longer_referenced-- # Step 4: Create remaining undeclared concepts via pipeline- if undeclared:- # Build context for the LLM- lines: list[str] = ["Missing concepts that need to be defined:\n"]- for ref_code, source_desc, field_context in undeclared_refs:- if ref_code in undeclared:- lines.append(f"- '{ref_code}' referenced in {source_desc} ({field_context})")-- lines.append("\nExisting declared concepts for context:")- if pipelex_bundle_spec.concept:- for concept_code, concept_spec_or_name in pipelex_bundle_spec.concept.items():- if isinstance(concept_spec_or_name, ConceptSpec):- lines.append(f"- {concept_code}: {concept_spec_or_name.description}")- else:- lines.append(f"- {concept_code}: {concept_spec_or_name}")- else:- lines.append("- (none)")-- undeclared_concepts = "\n".join(lines)- log.info(f"🤖 Generating ConceptSpec definitions for {len(undeclared)} undeclared concept(s) via LLM...")-- concept_fixer_runner = PipelexRunner(- library_dirs=[str(Path(builder.__file__).parent / "concept")],- )- concept_fixer_response = await concept_fixer_runner.execute_pipeline(- pipe_code="generate_missing_concepts",- inputs={"undeclared_concepts": undeclared_concepts},- )- concept_fixer_output = concept_fixer_response.pipe_output-- generated_concepts_list = concept_fixer_output.working_memory.get_stuff_as_list(- name="generate_missing_concepts",- item_type=ConceptSpec,- )-- if pipelex_bundle_spec.concept is None:- pipelex_bundle_spec.concept = {}-- for concept_spec in generated_concepts_list.items:- pipelex_bundle_spec.concept[concept_spec.the_concept_code] = concept_spec- log.info(f"🔧 Added generated concept '{concept_spec.the_concept_code}' to bundle")-- return self._prune_unreachable_specs(pipelex_bundle_spec=pipelex_bundle_spec)-- def _prune_unreachable_specs(self, pipelex_bundle_spec: PipelexBundleSpec) -> PipelexBundleSpec:- """Remove unreachable pipes and unused concepts from the bundle spec.-- Walks the call graph from main_pipe to find all reachable pipes, removes- unreachable ones, then collects all concept references from reachable pipes- and concept definitions (transitively) to remove unused concepts.-- Args:- pipelex_bundle_spec: The bundle spec to prune (modified in place)-- Returns:- The pruned bundle spec- """- if not pipelex_bundle_spec.pipe:- return pipelex_bundle_spec-- domain = pipelex_bundle_spec.domain-- # Step A: Find all reachable pipes by walking the call graph from main_pipe- reachable_pipes: set[str] = set()- to_visit: list[str] = [pipelex_bundle_spec.main_pipe]- special_outcome_values = SpecialOutcome.value_list()-- while to_visit:- pipe_code = to_visit.pop()- if pipe_code in reachable_pipes:- continue-- pipe_spec = pipelex_bundle_spec.pipe.get(pipe_code)- if pipe_spec is None:- log.warning(f"Pipe '{pipe_code}' is referenced but not found in bundle spec pipes")- continue- reachable_pipes.add(pipe_code)-- sub_pipe_codes: list[str] = []- if isinstance(pipe_spec, PipeSequenceSpec):- sub_pipe_codes = [step.pipe_code for step in pipe_spec.steps]- elif isinstance(pipe_spec, PipeParallelSpec):- sub_pipe_codes = [branch.pipe_code for branch in pipe_spec.branches]- elif isinstance(pipe_spec, PipeBatchSpec):- sub_pipe_codes = [pipe_spec.branch_pipe_code]- elif isinstance(pipe_spec, PipeConditionSpec):- for outcome_value in pipe_spec.outcomes.values():- if outcome_value not in special_outcome_values:- sub_pipe_codes.append(outcome_value)- if pipe_spec.default_outcome not in special_outcome_values:- sub_pipe_codes.append(pipe_spec.default_outcome)-- to_visit.extend(sub_pipe_codes)-- # Step B: Remove unreachable pipes- unreachable = set(pipelex_bundle_spec.pipe.keys()) - reachable_pipes- for pipe_code in unreachable:- del pipelex_bundle_spec.pipe[pipe_code]- log.info(f"🧹 Removed unreachable pipe '{pipe_code}'")-- # Step C: Collect all concept references from reachable pipes- referenced_concepts: set[str] = set()- for pipe_code in reachable_pipes:- pipe_spec = pipelex_bundle_spec.pipe.get(pipe_code)- if pipe_spec is None:- continue- referenced_concepts.update(self._collect_concept_refs_from_pipe_spec(pipe_spec=pipe_spec, domain=domain))-- # Step D: Collect transitive concept references from concept definitions- if pipelex_bundle_spec.concept:- changed = True- while changed:- changed = False- for concept_code in list(referenced_concepts):- concept_spec_or_name = pipelex_bundle_spec.concept.get(concept_code)- if not isinstance(concept_spec_or_name, ConceptSpec):- continue- new_refs = self._collect_concept_refs_from_concept_spec(concept_spec=concept_spec_or_name, domain=domain)- for bare_ref in new_refs:- if bare_ref not in referenced_concepts and bare_ref in pipelex_bundle_spec.concept:- referenced_concepts.add(bare_ref)- changed = True-- # Step E: Remove unused concepts- if pipelex_bundle_spec.concept:- unused = set(pipelex_bundle_spec.concept.keys()) - referenced_concepts- for concept_code in unused:- del pipelex_bundle_spec.concept[concept_code]- log.info(f"🧹 Removed unused concept '{concept_code}'")-- return pipelex_bundle_spec-- @staticmethod- def _extract_local_bare_code(concept_ref_or_code: str, domain: str) -> str | None:- """Extract a bare concept code only if the reference is local.-- A reference is considered local if it has no domain prefix or if- its domain prefix matches the bundle domain. Cross-package refs- (containing '->') are never local.-- Args:- concept_ref_or_code: A concept reference like "Document", "my_domain.Document", or "external.Document"- domain: The bundle's domain-- Returns:- The bare concept code if local, or None if external or cross-package- """- if QualifiedRef.has_cross_package_prefix(concept_ref_or_code):- return None- if "." not in concept_ref_or_code:- return concept_ref_or_code- prefix, bare_code = concept_ref_or_code.rsplit(".", maxsplit=1)- if prefix == domain:- return bare_code- return None-- @staticmethod- def _collect_concept_refs_from_pipe_spec(pipe_spec: PipeSpecUnion, domain: str) -> set[str]:- """Collect local bare concept codes referenced by a single pipe spec.-- Scans output, inputs, and (for PipeParallelSpec) combined_output.-- Args:- pipe_spec: The pipe spec to scan- domain: The bundle's domain for locality filtering-- Returns:- Set of bare concept codes referenced by this pipe spec- """- refs: set[str] = set()-- # Output- output_parse = parse_concept_with_multiplicity(pipe_spec.output)- bare_output = BuilderLoop._extract_local_bare_code(concept_ref_or_code=output_parse.concept_ref_or_code, domain=domain)- if bare_output is not None:- refs.add(bare_output)-- # Inputs- if pipe_spec.inputs:- for input_concept_str in pipe_spec.inputs.values():- input_parse = parse_concept_with_multiplicity(input_concept_str)- bare_input = BuilderLoop._extract_local_bare_code(concept_ref_or_code=input_parse.concept_ref_or_code, domain=domain)- if bare_input is not None:- refs.add(bare_input)-- # PipeParallel combined_output- if isinstance(pipe_spec, PipeParallelSpec) and pipe_spec.combined_output:- combined_parse = parse_concept_with_multiplicity(pipe_spec.combined_output)- bare_combined = BuilderLoop._extract_local_bare_code(concept_ref_or_code=combined_parse.concept_ref_or_code, domain=domain)- if bare_combined is not None:- refs.add(bare_combined)-- return refs-- @staticmethod- def _collect_concept_refs_from_concept_spec(concept_spec: ConceptSpec, domain: str) -> set[str]:- """Collect local bare concept codes referenced by a single concept spec.-- Scans refines, and structure fields' concept_ref and item_concept_ref.-- Args:- concept_spec: The concept spec to scan- domain: The bundle's domain for locality filtering-- Returns:- Set of bare concept codes referenced by this concept spec- """- refs: set[str] = set()-- # Refines- if concept_spec.refines:- bare_ref = BuilderLoop._extract_local_bare_code(concept_ref_or_code=concept_spec.refines, domain=domain)- if bare_ref is not None:- refs.add(bare_ref)-- # Structure fields- if concept_spec.structure:- for field_spec in concept_spec.structure.values():- if field_spec.concept_ref:- bare_ref = BuilderLoop._extract_local_bare_code(concept_ref_or_code=field_spec.concept_ref, domain=domain)- if bare_ref is not None:- refs.add(bare_ref)- if field_spec.item_concept_ref:- bare_ref = BuilderLoop._extract_local_bare_code(concept_ref_or_code=field_spec.item_concept_ref, domain=domain)- if bare_ref is not None:- refs.add(bare_ref)-- return refs-- @staticmethod- def _collect_local_bare_concept_codes(pipelex_bundle_spec: PipelexBundleSpec) -> set[str]:- """Collect bare concept codes referenced locally from pipe specs and concept definitions.-- Only includes references whose domain prefix is absent or matches the bundle domain.- This is used to determine which concepts are still actively referenced after spec mutations.-- Args:- pipelex_bundle_spec: The bundle spec to scan-- Returns:- Set of bare concept codes (without domain prefix) that are referenced- """- domain = pipelex_bundle_spec.domain- referenced: set[str] = set()-- # Scan pipe specs- if pipelex_bundle_spec.pipe:- for pipe_spec in pipelex_bundle_spec.pipe.values():- referenced.update(BuilderLoop._collect_concept_refs_from_pipe_spec(pipe_spec=pipe_spec, domain=domain))-- # Scan concept definitions- if pipelex_bundle_spec.concept:- for concept_spec_or_name in pipelex_bundle_spec.concept.values():- if not isinstance(concept_spec_or_name, ConceptSpec):- continue- referenced.update(BuilderLoop._collect_concept_refs_from_concept_spec(concept_spec=concept_spec_or_name, domain=domain))-- return referenced-- @staticmethod- def _strip_native_concept_declarations(pipelex_bundle_spec: PipelexBundleSpec) -> PipelexBundleSpec:- """Remove any concept declarations that collide with native concept codes.-- Native concepts are built-in and must not be redeclared in a bundle.- This is a safety net for when the builder LLM ignores the instruction- not to redefine them.- """- if not pipelex_bundle_spec.concept:- return pipelex_bundle_spec- native_codes = {native.value for native in NativeConceptCode.values_list()}- to_remove = [code for code in pipelex_bundle_spec.concept if code in native_codes]- for code in to_remove:- del pipelex_bundle_spec.concept[code]- log.info(f"Stripped native concept declaration '{code}' (native concepts are built-in)")- return pipelex_bundle_spec-- @staticmethod- def _strip_dotted_pipe_code(pipe_code: str) -> str:- """Extract bare pipe code from a potentially dotted pipe code.-- If the code contains a dot, return the part after the last dot.- Otherwise, return the code unchanged.-- Args:- pipe_code: A pipe code like "my_pipe" or "domain.my_pipe" or "a.b.my_pipe"-- Returns:- The bare pipe code (part after last dot, or unchanged if no dot)- """- if "." in pipe_code:- return pipe_code.rsplit(".", maxsplit=1)[1]- return pipe_code-- @staticmethod- def _strip_namespace_from_pipe_codes(pipelex_bundle_spec: PipelexBundleSpec) -> PipelexBundleSpec:- """Strip namespace prefixes from pipe definition codes and internal pipe references.-- The builder LLM sometimes generates dotted pipe codes (e.g., 'domain.my_pipe')- for pipe definitions and internal references. Pipe definition codes must be bare- snake_case since the namespace comes from the bundle's domain field.-- Pipe definition keys and pipe_code fields are always stripped (unconditionally).- Internal pipe references in controllers (branch_pipe_code, steps, branches,- outcomes) are only stripped when the stripped code matches a pipe defined in- the same bundle — otherwise the reference may legitimately point to a pipe- in another domain.-- Affected fields:- - Pipe dict keys (unconditional)- - main_pipe (unconditional)- - PipeSpec.pipe_code inside each pipe value (unconditional)- - PipeBatchSpec.branch_pipe_code (conditional on bundle membership)- - PipeSequenceSpec.steps[*].pipe_code (conditional on bundle membership)- - PipeParallelSpec.branches[*].pipe_code (conditional on bundle membership)- - PipeConditionSpec.outcomes values and default_outcome (conditional on bundle membership)- """- strip = BuilderLoop._strip_dotted_pipe_code- special_outcome_values = SpecialOutcome.value_list()-- # Strip main_pipe (unconditional — it always refers to a pipe in this bundle)- stripped_main = strip(pipelex_bundle_spec.main_pipe)- if stripped_main != pipelex_bundle_spec.main_pipe:- log.info(f"Stripped namespace from main_pipe: '{pipelex_bundle_spec.main_pipe}' → '{stripped_main}'")- pipelex_bundle_spec.main_pipe = stripped_main-- if not pipelex_bundle_spec.pipe:- return pipelex_bundle_spec-- # Pass 1: Strip pipe dict keys and pipe_code fields (unconditional for definitions),- # and build the set of defined bare pipe codes for reference resolution- new_pipes: dict[str, PipeSpecUnion] = {}- for key, pipe_spec in pipelex_bundle_spec.pipe.items():- stripped_key = strip(key)- if stripped_key != key:- log.info(f"Stripped namespace from pipe key: '{key}' → '{stripped_key}'")-- stripped_pipe_code = strip(pipe_spec.pipe_code)- if stripped_pipe_code != pipe_spec.pipe_code:- log.info(f"Stripped namespace from pipe_code: '{pipe_spec.pipe_code}' → '{stripped_pipe_code}'")- pipe_spec.pipe_code = stripped_pipe_code-- new_pipes[stripped_key] = pipe_spec-- pipelex_bundle_spec.pipe = new_pipes- defined_pipe_codes = set(new_pipes.keys())-- # Pass 2: Strip internal pipe references when the stripped code matches- # a pipe defined in this bundle OR the dotted prefix matches the bundle's- # own domain (LLM hallucinating the namespace). Only preserve dotted codes- # whose prefix is a genuinely different domain.- bundle_domain = pipelex_bundle_spec.domain-- def _should_strip_ref(ref_code: str, stripped_code: str) -> bool:- """Decide whether a dotted pipe reference should be stripped.-- Strip if the bare code exists in the bundle's defined pipes, or if- the dotted prefix matches the bundle's own domain.- """- if stripped_code == ref_code:- return False- ref_domain = get_root_from_dotted_path(ref_code)- return stripped_code in defined_pipe_codes or ref_domain == bundle_domain-- for pipe_spec in pipelex_bundle_spec.pipe.values():- if isinstance(pipe_spec, PipeBatchSpec):- stripped_branch = strip(pipe_spec.branch_pipe_code)- if _should_strip_ref(pipe_spec.branch_pipe_code, stripped_branch):- log.info(f"Stripped namespace from branch_pipe_code: '{pipe_spec.branch_pipe_code}' → '{stripped_branch}'")- pipe_spec.branch_pipe_code = stripped_branch-- elif isinstance(pipe_spec, PipeSequenceSpec):- for step in pipe_spec.steps:- stripped_step = strip(step.pipe_code)- if _should_strip_ref(step.pipe_code, stripped_step):- log.info(f"Stripped namespace from sequence step pipe_code: '{step.pipe_code}' → '{stripped_step}'")- step.pipe_code = stripped_step-- elif isinstance(pipe_spec, PipeParallelSpec):- for branch in pipe_spec.branches:- stripped_branch = strip(branch.pipe_code)- if _should_strip_ref(branch.pipe_code, stripped_branch):- log.info(f"Stripped namespace from parallel branch pipe_code: '{branch.pipe_code}' → '{stripped_branch}'")- branch.pipe_code = stripped_branch-- elif isinstance(pipe_spec, PipeConditionSpec):- new_outcomes: dict[str, str] = {}- for condition_key, outcome_value in pipe_spec.outcomes.items():- if outcome_value in special_outcome_values:- new_outcomes[condition_key] = outcome_value- else:- stripped_outcome = strip(outcome_value)- if _should_strip_ref(outcome_value, stripped_outcome):- log.info(f"Stripped namespace from condition outcome: '{outcome_value}' → '{stripped_outcome}'")- new_outcomes[condition_key] = stripped_outcome- else:- new_outcomes[condition_key] = outcome_value- pipe_spec.outcomes = new_outcomes-- if pipe_spec.default_outcome not in special_outcome_values:- stripped_default = strip(pipe_spec.default_outcome)- if _should_strip_ref(pipe_spec.default_outcome, stripped_default):- log.info(f"Stripped namespace from default_outcome: '{pipe_spec.default_outcome}' → '{stripped_default}'")- pipe_spec.default_outcome = stripped_default-- log.debug(f"After namespace stripping: main_pipe='{pipelex_bundle_spec.main_pipe}', pipe keys={list(pipelex_bundle_spec.pipe.keys())}")- return pipelex_bundle_spec-- def _fix_bundle_validation_error(- self,- bundle_error: ValidateBundleError,- pipelex_bundle_spec: PipelexBundleSpec,- is_save_second_iteration_enabled: bool,- output_dir: str | None = None,- ) -> PipelexBundleSpec:- fixed_pipes: list[PipeSpecUnion] = []- added_concepts: list[str] = []- # Handle pipe factory errors (e.g., missing output concepts)- for factory_error in bundle_error.pipe_factory_errors:- match factory_error.error_type:- case PipeFactoryErrorType.UNKNOWN_CONCEPT:- # Fix unknown concept by adding a new concept that refines Text to the bundle- unknown_concept_code = factory_error.missing_concept_code- if not unknown_concept_code:- continue-- # Create a simple concept that refines Text- new_concept = ConceptSpec(- the_concept_code=unknown_concept_code,- description=unknown_concept_code,- refines="Text",- )-- # Add the concept to the bundle- if pipelex_bundle_spec.concept is None:- pipelex_bundle_spec.concept = {}-- pipelex_bundle_spec.concept[unknown_concept_code] = new_concept- added_concepts.append(unknown_concept_code)- log.info(f"🔧 Added unknown concept '{unknown_concept_code}' (refines Text) to bundle for pipe '{factory_error.pipe_code}'")-- case PipeFactoryErrorType.UNKNOWN_FACTORY_ERROR:- continue-- # Handle pipe validation errors- for val_error in bundle_error.pipe_validation_error_data:- if not val_error.pipe_code or not pipelex_bundle_spec.pipe:- continue-- pipe_spec = pipelex_bundle_spec.pipe.get(val_error.pipe_code)- if not pipe_spec:- continue-- match val_error.error_type:- case PipeValidationErrorType.INPUT_STUFF_SPEC_MISMATCH:- # Fix input stuff spec mismatch by updating the specific mismatched input(s)- # This applies to ALL pipe categories (operators and controllers)- if not PipeCategory.is_controller_by_str(category_str=pipe_spec.pipe_category):- continue-- pipe = get_required_pipe(pipe_code=val_error.pipe_code)- needed_inputs = pipe.needed_inputs()-- # Start with existing inputs, we'll only override the mismatched ones- new_inputs: dict[str, str] = dict(pipe_spec.inputs) if pipe_spec.inputs else {}-- # Get the variable names that have mismatches- mismatched_variables = val_error.variable_names or []-- # Update only the mismatched inputs with the correct concept from needed_inputs- for variable_name in mismatched_variables:- for named_stuff_spec in needed_inputs.named_stuff_specs:- if named_stuff_spec.variable_name == variable_name:- old_value = new_inputs.get(variable_name, "NOT SET")- concept_code_with_multiplicity = format_concept_with_multiplicity(- concept_code_or_string=named_stuff_spec.concept.code,- multiplicity=named_stuff_spec.multiplicity,- )- new_inputs[variable_name] = concept_code_with_multiplicity- # TODO: return a structured report of what was done, let the caller decide if they want to print it or act on it- log.info(- f"🔧 Fixed input requirement mismatch for pipe '{val_error.pipe_code}': input '{variable_name}' "- f"changed from '{old_value}' → '{concept_code_with_multiplicity}'"- )- break-- pipe_spec.inputs = new_inputs- fixed_pipes.append(pipe_spec)-- case PipeValidationErrorType.MISSING_INPUT_VARIABLE | PipeValidationErrorType.EXTRANEOUS_INPUT_VARIABLE:- # Fix input variables for PipeController ONLY by copying all requirements from needed_inputs- if not PipeCategory.is_controller_by_str(category_str=pipe_spec.pipe_category):- continue-- pipe = get_required_pipe(pipe_code=val_error.pipe_code)- needed_inputs = pipe.needed_inputs()- old_inputs = dict(pipe_spec.inputs) if pipe_spec.inputs else {}- fixed_inputs: dict[str, str] = {}- for named_stuff_spec in needed_inputs.named_stuff_specs:- concept_code_with_multiplicity = format_concept_with_multiplicity(- concept_code_or_string=named_stuff_spec.concept.code,- multiplicity=named_stuff_spec.multiplicity,- )- fixed_inputs[named_stuff_spec.variable_name] = concept_code_with_multiplicity-- # Only apply fix if it actually changes something (avoid infinite loops)- if fixed_inputs != old_inputs:- pipe_spec.inputs = fixed_inputs- fixed_pipes.append(pipe_spec)- log.info(f"🔧 Fixed input variables for pipe '{val_error.pipe_code}': BEFORE={old_inputs} → AFTER={fixed_inputs}")- else:- variable_names_str = ", ".join(val_error.variable_names) if val_error.variable_names else "unknown"- log.warning(- f"⚠️ Cannot auto-fix {val_error.error_type.replace('_', ' ')} for pipe '{val_error.pipe_code}': needed_inputs() "- f"doesn't include the missing variable '{variable_names_str}'. "- f"This might be an intermediate variable that shouldn't be in inputs."- )-- case PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT | PipeValidationErrorType.INADEQUATE_OUTPUT_MULTIPLICITY:- # Fix output concept/multiplicity mismatch for PipeSequence by updating to match last step's output- if isinstance(pipe_spec, PipeSequenceSpec):- last_step = pipe_spec.steps[-1]- last_step_pipe_code = last_step.pipe_code-- # Get the last step's pipe spec to retrieve its output- last_step_pipe_spec = pipelex_bundle_spec.pipe.get(last_step_pipe_code)- if not last_step_pipe_spec:- continue-- old_output = pipe_spec.output- new_output = last_step_pipe_spec.output-- # Set the sequence output to match the last step's output- pipe_spec.output = new_output- fixed_pipes.append(pipe_spec)- # TODO: return a structured report of what was done, let the caller decide if they want to print it or act on it- error_kind = "concept" if val_error.error_type == PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT else "multiplicity"- log.info(- f"🔧 Fixed output {error_kind} for pipe '{val_error.pipe_code}': output changed from '{old_output}' → "- f"'{new_output}' (matching last step '{last_step_pipe_code}')"- )-- # Fix output concept for PipeCondition by checking mapped pipes' outputs- elif isinstance(pipe_spec, PipeConditionSpec):- # Get the PipeCondition instance to access pipe_dependencies()- pipe_condition = cast("PipeCondition", get_required_pipe(pipe_code=val_error.pipe_code))- mapped_pipe_codes = pipe_condition.pipe_dependencies()-- if not mapped_pipe_codes:- # No mapped pipes (all special outcomes), any output is fine- continue-- # Collect all unique output concept refs from mapped pipes- mapped_output_refs: set[str] = set()- for mapped_pipe_code in mapped_pipe_codes:- mapped_pipe = get_required_pipe(pipe_code=mapped_pipe_code)- mapped_output_refs.add(mapped_pipe.output.concept.concept_ref)-- old_output = pipe_spec.output-- # If all mapped pipes have same output, use that; otherwise use Anything- if len(mapped_output_refs) == 1:- new_output = next(iter(mapped_output_refs))- else:- new_output = "native.Anything"-- pipe_spec.output = new_output- fixed_pipes.append(pipe_spec)- log.info(- f"🔧 Fixed output concept for PipeCondition '{val_error.pipe_code}': output changed from '{old_output}' → '{new_output}'"- )-- case PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX:- log.info(f"⚠️ Invalid pipe code syntax detected for pipe '{val_error.pipe_code}' — will be fixed by namespace stripping")- continue-- case (- PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE- | PipeValidationErrorType.IMG_GEN_INPUT_NOT_TEXT_COMPATIBLE- | PipeValidationErrorType.UNKNOWN_VALIDATION_ERROR- | PipeValidationErrorType.CIRCULAR_DEPENDENCY_ERROR- | PipeValidationErrorType.BATCH_ITEM_NAME_COLLISION- ):- continue-- # Handle dry run errors (e.g., PipeCompose multiplicity mismatches)- if bundle_error.dry_run_error_message:- dry_run_fixed_pipes = self._fix_dry_run_compose_multiplicity_mismatch(- dry_run_error_message=bundle_error.dry_run_error_message,- pipelex_bundle_spec=pipelex_bundle_spec,- )- fixed_pipes.extend(dry_run_fixed_pipes)-- # Reconstruct bundle if we made pipe changes- if fixed_pipes:- pipelex_bundle_spec = reconstruct_bundle_with_pipe_fixes(pipelex_bundle_spec=pipelex_bundle_spec, fixed_pipes=fixed_pipes)-- # Save second iteration if we made any changes (pipes or concepts)- if (fixed_pipes or added_concepts) and is_save_second_iteration_enabled:- try:- mthds_content = MthdsFactory.make_mthds_content(blueprint=pipelex_bundle_spec.to_blueprint())- second_iteration_path = get_incremental_file_path(- base_path=output_dir or "results/pipe-builder",- base_name="generated_pipeline_2nd_iteration",- extension="mthds",- )- save_text_to_path(text=mthds_content, path=str(second_iteration_path))- except PipelexBundleSpecBlueprintError as exc:- log.warning(f"Could not save second iteration MTHDS: {exc}")-- return pipelex_bundle_spec-- # --- Dry run multiplicity mismatch fix ----- def _fix_dry_run_compose_multiplicity_mismatch(- self,- dry_run_error_message: str,- pipelex_bundle_spec: PipelexBundleSpec,- ) -> list[PipeSpecUnion]:- """Fix multiplicity mismatches detected in PipeCompose dry run errors.-- Parses dry run error messages to identify cases where a PipeCompose field- receives ListContent but the concept structure expects a scalar type (e.g., str).- Fixes by adding [] to the pipe input and changing the concept structure field to list type.-- Args:- dry_run_error_message: The error message from dry run failure- pipelex_bundle_spec: The bundle spec to fix (modified in place for concept structure)-- Returns:- List of fixed pipe specs to include in bundle reconstruction- """- fixed_pipes: list[PipeSpecUnion] = []-- if not pipelex_bundle_spec.pipe:- return fixed_pipes-- # Extract compose pipe code and output concept from error message- # Pattern: "In pipe 'compose_pipe_code' (output: OutputConcept)"- pipe_match = re.search(r"In pipe '(\w+)' \(output: (\w+)\)", dry_run_error_message)- if not pipe_match:- return fixed_pipes-- compose_pipe_code = pipe_match.group(1)- output_concept_code = pipe_match.group(2)-- # Find all multiplicity mismatches: "field_name: ListContent (expected str) <-- MISMATCH"- mismatch_matches = re.findall(r"(\w+): ListContent \(expected (\w+)\) <-- MISMATCH", dry_run_error_message)- if not mismatch_matches:- return fixed_pipes-- # Get the PipeComposeSpec- pipe_spec = pipelex_bundle_spec.pipe.get(compose_pipe_code)- if not isinstance(pipe_spec, PipeComposeSpec):- return fixed_pipes-- any_fix_applied = False- for field_name, _expected_type in mismatch_matches:- fix_applied = self._fix_single_multiplicity_mismatch(- pipe_spec=pipe_spec,- pipelex_bundle_spec=pipelex_bundle_spec,- compose_pipe_code=compose_pipe_code,- output_concept_code=output_concept_code,- field_name=field_name,- )- if fix_applied:- any_fix_applied = True-- if any_fix_applied:- fixed_pipes.append(pipe_spec)-- return fixed_pipes-- def _fix_single_multiplicity_mismatch(- self,- pipe_spec: PipeComposeSpec,- pipelex_bundle_spec: PipelexBundleSpec,- compose_pipe_code: str,- output_concept_code: str,- field_name: str,- ) -> bool:- """Fix a single field's multiplicity mismatch in a PipeCompose.-- Adds [] to the pipe input concept ref and changes the concept structure- field from its current scalar type to a list type.-- Returns:- True if a fix was applied, False otherwise- """- # Find which input variable maps to this field via construct spec- input_variable = self._find_input_for_construct_field(- pipe_spec=pipe_spec,- field_name=field_name,- )- if not input_variable:- log.warning(f"Could not find input variable for field '{field_name}' in compose pipe '{compose_pipe_code}'")- return False-- # Get the input's concept ref- if not pipe_spec.inputs or input_variable not in pipe_spec.inputs:- log.warning(f"Input variable '{input_variable}' not found in inputs of '{compose_pipe_code}'")- return False-- old_input_concept = pipe_spec.inputs[input_variable]- parse_result = parse_concept_with_multiplicity(old_input_concept)-- any_fix_applied = False-- # Fix 1: Add [] to the input concept (skip if already has multiplicity)- if parse_result.multiplicity is None:- new_input_concept = format_concept_with_multiplicity(- concept_code_or_string=parse_result.concept_ref_or_code,- multiplicity=True,- )- pipe_spec.inputs[input_variable] = new_input_concept- any_fix_applied = True- log.info(- f"🔧 Fixed input multiplicity in '{compose_pipe_code}': "- f"input '{input_variable}' changed from '{old_input_concept}' → '{new_input_concept}'"- )-- # Fix 2: Update the output concept's structure field to LIST type- concept_fixed = self._fix_concept_field_to_list(- pipelex_bundle_spec=pipelex_bundle_spec,- concept_code=output_concept_code,- field_name=field_name,- item_concept_ref=parse_result.concept_ref_or_code,- )- if concept_fixed:- any_fix_applied = True- log.info(f"🔧 Fixed concept field '{output_concept_code}.{field_name}' changed to list[concept[{parse_result.concept_ref_or_code}]]")-- return any_fix_applied-- def _find_input_for_construct_field(- self,- pipe_spec: PipeComposeSpec,- field_name: str,- ) -> str | None:- """Find the input variable that maps to a construct field.-- Examines the construct_spec to find which input variable is used- for a given field, looking for {"from": "variable_name"} patterns.-- Args:- pipe_spec: The PipeComposeSpec to examine- field_name: The field name to look up-- Returns:- The input variable name, or None if not found- """- if not pipe_spec.construct_spec:- return None-- field_spec = pipe_spec.construct_spec.get(field_name)- if not field_spec:- return None-- # Check if it's a {"from": "variable_name"} pattern- if isinstance(field_spec, dict):- from_dict = cast("dict[str, str]", field_spec)- from_value = from_dict.get("from")- if isinstance(from_value, str):- # Handle dotted paths like "deal.customer" -> "deal"- return get_root_from_dotted_path(from_value)-- return None-- def _fix_concept_field_to_list(- self,- pipelex_bundle_spec: PipelexBundleSpec,- concept_code: str,- field_name: str,- item_concept_ref: str,- ) -> bool:- """Fix a concept's structure field type from scalar to list[concept[X]].-- Args:- pipelex_bundle_spec: The bundle spec containing concepts- concept_code: The concept code whose structure field to modify- field_name: The field name within the concept's structure- item_concept_ref: The concept reference for list items-- Returns:- True if the fix was applied, False otherwise- """- if not pipelex_bundle_spec.concept:- return False-- concept_spec = pipelex_bundle_spec.concept.get(concept_code)- if not isinstance(concept_spec, ConceptSpec):- return False-- if not concept_spec.structure:- return False-- field_spec = concept_spec.structure.get(field_name)- if not field_spec:- return False-- # Skip if the field is already correctly typed as LIST with the right item_concept_ref- if (- field_spec.type == ConceptStructureSpecFieldType.LIST- and field_spec.item_type == "concept"- and field_spec.item_concept_ref == item_concept_ref- ):- return False-- # Update the field to LIST type and clear fields that are invalid for LIST- field_spec.type = ConceptStructureSpecFieldType.LIST- field_spec.item_type = "concept"- field_spec.item_concept_ref = item_concept_ref- field_spec.default_value = None- field_spec.concept_ref = None- field_spec.choices = None-- return True---def maybe_generate_manifest_for_output(output_dir: Path) -> Path | None:- """Generate a METHODS.toml if the output directory contains multiple domains.-- Scans all .mthds files in the output directory, parses their headers to- extract domain and main_pipe information, and generates a METHODS.toml- if multiple distinct domains are found.-- Args:- output_dir: Directory to scan for .mthds files-- Returns:- Path to the generated METHODS.toml, or None if not generated- """- mthds_files = sorted(output_dir.rglob("*.mthds"))- if not mthds_files:- return None-- # Parse each bundle to extract domain and pipe info- domain_pipes, domain_main_pipes, errors = scan_bundles_for_domain_info(mthds_files)- for error in errors:- log.warning(f"Could not parse {error}")-- # Only generate manifest when multiple domains are present- if len(domain_pipes) < 2:- return None-- # Build exports: include main_pipe and all pipes from each domain- exports = build_domain_exports_from_scan(domain_pipes, domain_main_pipes)-- dir_name = output_dir.name.replace("-", "_").replace(" ", "_").lower()- manifest = MethodsManifest(- address=f"example.com/yourorg/{dir_name}",- version="0.1.0",- description=f"Package generated from {len(mthds_files)} .mthds file(s)",- exports=exports,- )-- manifest_path = output_dir / MANIFEST_FILENAME- toml_content = serialize_manifest_to_toml(manifest)- manifest_path.write_text(toml_content, encoding="utf-8")-- return manifest_pathdiff --git a/pipelex/builder/concept/concept_fixer.mthds b/pipelex/builder/concept/concept_fixer.mthdsdeleted file mode 100644index c8a176b94..000000000--- a/pipelex/builder/concept/concept_fixer.mthds+++ /dev/null@@ -1,46 +0,0 @@-domain = "concept_fixer"-description = "Generate ConceptSpec definitions for missing concepts referenced in a pipeline."--[concept]-UndeclaredConcepts = "A list of undeclared concept codes with the pipes that reference them, and the existing declared concepts for context."--[pipe]--[pipe.generate_missing_concepts]-type = "PipeLLM"-description = "Generate structured ConceptSpec definitions for each missing concept referenced in a pipeline."-inputs = { undeclared_concepts = "UndeclaredConcepts" }-output = "builder.ConceptSpec[]"-model = "$pipe-builder-engineering"-system_prompt = """-You are an expert at defining data concepts for AI pipelines.-"""-prompt = """-A pipeline references concepts that have not been declared.-Below is the list of undeclared concepts, where each one is referenced, and the existing declared concepts for context.--@undeclared_concepts--Define each undeclared concept as a ConceptSpec. Use the existing concepts as context to infer the right structure or refinement. Follow these rules:--Variables are snake_case and concepts are PascalCase.--If the concept can be expressed as a text, html, image, document, number, or page:-- Name the concept, define it and just write refines: Text, refines: Html (for HTML content), refines: Document (and note that PDF is a document), or refines: Image etc.-- No need to define its structure--Else, if you need structure for your concept, define its structure:-- field name in snake_case-- description: the description of the field, in natural language-- type: the type of the field:- - text, integer, boolean, number, date for primitive values- - concept when the field should contain a previously-defined structured concept-- concept_ref: (only when type=concept) the name of the referenced concept-- required: add required = true if the field is required (otherwise, leave it empty)--When building composite/aggregate concepts that combine multiple other concepts:-- Use type=concept with concept_ref to reference the other structured concepts-- This allows proper object composition rather than flattening structured data into text--DO NOT redefine native concepts: Text, Html, Image, Document, Number, Page, TextAndImages, ImgGenPrompt, JSON, Anything, Dynamic. They are built-in and must NOT be redeclared.-"""diff --git a/pipelex/builder/operations/runner_code_ops.py b/pipelex/builder/operations/runner_code_ops.pyindex 37e5c0b59..76395f1d0 100644--- a/pipelex/builder/operations/runner_code_ops.py+++ b/pipelex/builder/operations/runner_code_ops.py@@ -25,7 +25,9 @@ async def build_runner_code_for_pipe(Generated Python runner code as a string.Raises:- Exception: If parsing, validation, or code generation fails.+ MthdsDecodeError: If MTHDS content has TOML syntax errors.+ PipeValidationError: If pipe validation fails.+ DryRunError: If dry-running the pipes fails."""library_manager = get_library_manager()library_id, _ = library_manager.open_library()diff --git a/pipelex/builder/pipe/pipe_design.mthds b/pipelex/builder/pipe/pipe_design.mthdsdeleted file mode 100644index a556d5ccb..000000000--- a/pipelex/builder/pipe/pipe_design.mthds+++ /dev/null@@ -1,309 +0,0 @@-domain = "pipe_design"--[concept]-PipeSignature = "A pipe contract which says what the pipe does, not how it does it: code (the pipe code in snake_case), type, description, inputs, output."-PipeSpec = "A structured spec for a pipe (union)."-# Pipe controllers-PipeBatchSpec = "A structured spec for a PipeBatch."-PipeConditionSpec = "A structured spec for a PipeCondition."-PipeParallelSpec = "A structured spec for a PipeParallel."-PipeSequenceSpec = "A structured spec for a PipeSequence."-# Pipe operators-PipeFuncSpec = "A structured spec for a PipeFunc."-PipeImgGenSpec = "A structured spec for a PipeImgGen."-PipeComposeSpec = "A structured spec for a pipe jinja2."-PipeLLMSpec = "A structured spec for a PipeLLM."-PipeExtractSpec = "A structured spec for a PipeExtract."-PipeSearchSpec = "A structured spec for a PipeSearch."-PipeFailure = "Details of a single pipe failure during dry run."--[pipe]--[pipe.detail_pipe_spec]-type = "PipeCondition"-description = "Route by signature.type to the correct spec emitter."-inputs = { plan_draft = "builder.PlanDraft", pipe_signature = "PipeSignature", concept_specs = "builder.ConceptSpec[]" }-output = "Anything"-expression = "pipe_signature.type"-default_outcome = "fail"--[pipe.detail_pipe_spec.outcomes]-PipeSequence = "detail_pipe_sequence"-PipeParallel = "detail_pipe_parallel"-PipeCondition = "detail_pipe_condition"-PipeLLM = "detail_pipe_llm"-PipeExtract = "detail_pipe_extract"-PipeImgGen = "detail_pipe_img_gen"-PipeBatch = "detail_pipe_batch"-PipeCompose = "detail_pipe_compose"-PipeSearch = "detail_pipe_search"--# ────────────────────────────────────────────────────────────────────────────────-# PIPE CONTROLLERS-# ────────────────────────────────────────────────────────────────────────────────--[pipe.detail_pipe_sequence]-type = "PipeLLM"-description = "Build a PipeSequenceSpec from the signature (children referenced by code)."-inputs = { plan_draft = "builder.PlanDraft", pipe_signature = "PipeSignature", concept_specs = "builder.ConceptSpec[]" }-output = "PipeSequenceSpec"-model = "$pipe-builder-engineering"-prompt = """-# Orchestrate a sequence of pipe steps that will run one after the other.--@plan_draft--You must pick the relevant concepts for inputs and outputs from the following possibilities:-@concept_specs--+ you can use the native concepts: Text, Html, Image, Document (note: PDF is a document), Number, Page, TextAndImages, ImgGenPrompt, JSON, Anything, Dynamic--@pipe_signature--Based on the pipe signature, build the PipeSequenceSpec.--Note:-- The output concept of a pipe sequence must always be the same as the output concept of the last pipe in the sequence.-"""--[pipe.detail_pipe_parallel]-type = "PipeLLM"-description = "Build a PipeParallelSpec from the signature."-inputs = { plan_draft = "builder.PlanDraft", pipe_signature = "PipeSignature", concept_specs = "builder.ConceptSpec[]" }-output = "PipeParallelSpec"-model = "$pipe-builder-engineering"-prompt = """-Orchestrate a set of independent pipes that will run concurrently.--@plan_draft--You must pick the relevant concepts for inputs and outputs from the following possibilities:-@concept_specs--+ you can use the native concepts: Text, Html, Image, Document (note: PDF is a document), Number, Page, TextAndImages, ImgGenPrompt, JSON, Anything, Dynamic--@pipe_signature--Based on the pipe signature, build the PipeParallelSpec.--Notes:-- Set add_each_output to true: each parallel branch's output will be available individually in working memory by its result name.-- Do NOT set combined_output unless the concept is explicitly listed in the concept specs above.-- The output of the PipeParallel should be set to "Anything" when add_each_output is true and no combined_output is used.-"""--[pipe.detail_pipe_condition]-type = "PipeLLM"-description = "Build a PipeConditionSpec from the signature (provide expression/outcome consistent with children)."-inputs = { plan_draft = "builder.PlanDraft", pipe_signature = "PipeSignature", concept_specs = "builder.ConceptSpec[]" }-output = "PipeConditionSpec"-model = "$pipe-builder-engineering"-prompt = """-Design a PipeConditionSpec to route to the correct pipe based on a conditional expression.--@plan_draft--You must pick the relevant concepts for inputs and outputs from the following possibilities:-@concept_specs--+ you can use the native concepts: Text, Html, Image, Document (note: PDF is a document), Number, Page, TextAndImages, ImgGenPrompt, JSON, Anything, Dynamic--@pipe_signature--Based on the pipe signature, build the PipeConditionSpec.-"""--[pipe.detail_pipe_batch]-type = "PipeLLM"-description = "Build a PipeBatchSpec from the signature."-inputs = { plan_draft = "builder.PlanDraft", pipe_signature = "PipeSignature", concept_specs = "builder.ConceptSpec[]" }-output = "PipeBatchSpec"-model = "$pipe-builder-engineering"-prompt = """-Design a PipeBatchSpec to run a pipe in batch.-Whatever it's really going to do has already been decided as part of this plan:-@plan_draft--You must pick the relevant concepts for inputs and outputs from the following possibilities:-@concept_specs--+ you can use the native concepts: Text, Html, Image, Document (note: PDF is a document), Number, Page, TextAndImages, ImgGenPrompt, JSON, Anything, Dynamic--Based on the pipe signature, build the PipeBatchSpec.--@pipe_signature--CRITICAL NAMING RULES for PipeBatch:-- input_list_name should be a PLURAL noun (e.g., "reports", "items", "images")-- input_item_name should be the SINGULAR form (e.g., "report", "item", "image")-- input_item_name must be DIFFERENT from input_list_name-- input_item_name must NOT match any key in the inputs dict-Examples:- - input_list_name = "reports", input_item_name = "report" ✓- - input_list_name = "report_data", input_item_name = "single_report_data" ✓- - input_list_name = "reports", input_item_name = "reports" ✗ (same as list name!)- - input_list_name = "report_data", input_item_name = "report_data" ✗ (same as inputs key!)-"""--# ────────────────────────────────────────────────────────────────────────────────-# PIPE OPERATORS-# ────────────────────────────────────────────────────────────────────────────────--[pipe.detail_pipe_llm]-type = "PipeLLM"-description = "Build a PipeLLMSpec from the signature."-inputs = { plan_draft = "builder.PlanDraft", pipe_signature = "PipeSignature", concept_specs = "builder.ConceptSpec[]" }-output = "PipeLLMSpec"-model = "$pipe-builder-engineering"-prompt = """-Design a PipeLLMSpec to use an LLM to generate a text, or a structured object using different kinds of inputs.-Whatever it's really going to do has already been decided as part of this plan:-@plan_draft--You must pick the relevant concepts for inputs and outputs from the following possibilities:-@concept_specs--+ you can use the native concepts: Text, Html, Image, Document (note: PDF is a document), Number, Page, TextAndImages, ImgGenPrompt, JSON, Anything, Dynamic--Based on the pipe signature, build the PipeLLMSpec.--@pipe_signature--Notes:-- If we are generating a structured concept, indicate it in the system_prompt to clarify the task.-- But DO NOT detail the structure in any of the user/system prompts: we will add the schema later. So, don't write a bullet-list of all the attributes to determine.-- If it's to generate free form text, the prompt should indicate to be concise.-- If it's to generate an image generation prompt, the prompt should indicate to be VERY concise and focus and apply the best practice for image generation.-"""--[pipe.detail_pipe_extract]-type = "PipeLLM"-description = "Build a PipeExtractSpec from the signature."-inputs = { plan_draft = "builder.PlanDraft", pipe_signature = "PipeSignature", concept_specs = "builder.ConceptSpec[]" }-output = "PipeExtractSpec"-model = "$pipe-builder-engineering"-prompt = """-Design a PipeExtractSpec to extract text from an image or a pdf.-Whatever it's really going to do has already been decided as part of this plan:-@plan_draft--You must pick the relevant concepts for inputs and outputs from the following possibilities:-@concept_specs--+ you can use the native concepts: Text, Html, Image, Document (note: PDF is a document), Number, Page, TextAndImages, ImgGenPrompt, JSON, Anything, Dynamic--Based on the pipe signature, build the PipeExtractSpec.--@pipe_signature-"""--[pipe.detail_pipe_img_gen]-type = "PipeLLM"-description = "Build a PipeImgGenSpec from the signature."-inputs = { plan_draft = "builder.PlanDraft", pipe_signature = "PipeSignature", concept_specs = "builder.ConceptSpec[]" }-output = "PipeImgGenSpec"-model = "$pipe-builder-engineering"-prompt = """-Your job is to design a PipeImgGenSpec to generate an image from a text prompt.-Whatever it's really going to do has already been decided as part of this plan:-@plan_draft--You must pick the relevant concepts for inputs and outputs from the following possibilities:-@concept_specs--+ you can use the native concepts: Text, Html, Image, Document (note: PDF is a document), Number, Page, TextAndImages, ImgGenPrompt, JSON, Anything, Dynamic--Based on the pipe signature, build the PipeImgGenSpec.--@pipe_signature--Notes:-- The inputs for the image has to be a single input which must be a Text or another concept which refines Text.-"""--[pipe.detail_pipe_search]-type = "PipeLLM"-description = "Build a PipeSearchSpec from the signature."-inputs = { plan_draft = "builder.PlanDraft", pipe_signature = "PipeSignature", concept_specs = "builder.ConceptSpec[]" }-output = "PipeSearchSpec"-model = "$pipe-builder-engineering"-prompt = """-Design a PipeSearchSpec to search the web for up-to-date information.-Whatever it's really going to do has already been decided as part of this plan:-@plan_draft--You must pick the relevant concepts for inputs and outputs from the following possibilities:-@concept_specs--+ you can use the native concepts: Text, Html, Image, Document (note: PDF is a document), Number, Page, TextAndImages, ImgGenPrompt, JSON, SearchResult, Anything, Dynamic--Based on the pipe signature, build the PipeSearchSpec.--@pipe_signature--Notes:-- The prompt is a search query template: use dollar-sign prefix for inline variables.-- Choose web-search for standard searches or web-search-deep for comprehensive research.-- The output must be SearchResult or a concept that refines SearchResult.-"""--[pipe.detail_pipe_compose]-type = "PipeLLM"-description = "Build a PipeComposeSpec from the signature."-inputs = { plan_draft = "builder.PlanDraft", pipe_signature = "PipeSignature", concept_specs = "builder.ConceptSpec[]" }-output = "PipeComposeSpec"-model = "$pipe-builder-engineering"-prompt = """-Design a PipeComposeSpec to compose content from working memory variables.-Whatever it's really going to do has already been decided as part of this plan:-@plan_draft--You must pick the relevant concepts for inputs and outputs from the following possibilities:-@concept_specs--+ you can use the native concepts: Text, Html, Image, Document (note: PDF is a document), Number, Page, TextAndImages, ImgGenPrompt, JSON, Anything, Dynamic--Based on the pipe signature, build the PipeComposeSpec.--PipeCompose has two modes - choose the appropriate one based on the pipe's purpose:--**Template mode** (for Text/Html output):-- Use when you need to render a template to produce formatted text-- Requires: template (template string), target_format (plain/markdown/html/json/mermaid)-- Output must be Text (or a concept that refines Text), or Html (or a concept that refines Html) if generating HTML content-- **IMPORTANT - Use Pipelex pre-processor syntax in templates:**- - Use `@ + variable_name` to render an entire object with all its attributes automatically formatted- - Use `$ + variable_name.field` for inline field access within text- - Only use raw Jinja2 double-braces when you need a specific single field in isolation- - **NEVER manually list all attributes** of an object in a template - use @ syntax instead to render the whole object--**Construct mode** (for StructuredContent output):-- Use when you need to assemble a structured object from working memory variables-- Requires: construct (dict mapping field names to composition specs)-- Each field can use:- - A fixed value (string, number, boolean, list)- - `{ from = "the_variable" }` to reference a variable directly from working memory- - `{ from = "the_variable.path" }` to reference a nested field- - `{ template = "..." }` ONLY when string interpolation is needed (e.g., combining a prefix with a variable)-- **IMPORTANT - Best practices for construct mode:**- - **PREFER `{ from = "the_variable" }`** for direct object/value assignment- - **NEVER use templates to manually list attributes** - if you need the whole object, use `{ from = "the_variable" }`- - Use `{ template = "..." }` only for string composition like prefixes, formatting, or combining multiple fields into a single string--**Examples of CORRECT vs INCORRECT usage:**--WRONG - manually listing attributes in a template:- summary = { template = "Skills: (( the_obj.skills ))\nExperience: (( the_obj.experience ))" }-CORRECT - direct reference to get the whole object:- summary = { from = "the_obj" }--WRONG - template mode manually listing attributes:- template = "Skills: (( the_data.skills ))\nExperience: (( the_data.experience ))"-CORRECT - use @ + the_data to auto-render the whole object:- template = "(@ + the_data)"--CORRECT - template for string composition (prefix + field):- code = { template = "INV-($ + the_order.id)" }--@pipe_signature-"""diff --git a/pipelex/builder/synthetic_inputs/synthesize_image.mthds b/pipelex/builder/synthetic_inputs/synthesize_image.mthdsdeleted file mode 100644index 310d2c98c..000000000--- a/pipelex/builder/synthetic_inputs/synthesize_image.mthds+++ /dev/null@@ -1,93 +0,0 @@-domain = "synthetic_data"-description = "Generate synthetic test images based on category and optional description. Supports photograph, screenshot, chart, diagram, document_scan, and handwritten categories."-main_pipe = "synthesize_image"--# ============================================================================-# CONCEPTS-# ============================================================================--[concept.ImageRequest]-description = "Request for synthetic image generation"--[concept.ImageRequest.structure]-category = { choices = [- "photograph",- "screenshot",- "chart",- "diagram",- "document_scan",- "handwritten",-], description = "Image category", required = true }-description = "Optional description of the image to generate"--# ============================================================================-# PIPES-# ============================================================================--# Main orchestration - creates prompt then routes rendering by category-[pipe.synthesize_image]-type = "PipeSequence"-description = "Generate synthetic image: create prompt then render with category-specific model"-inputs = { request = "ImageRequest" }-output = "Image"-steps = [- { pipe = "create_image_prompt", result = "img_prompt" },- { pipe = "route_rendering", result = "image" },-]--# -----------------------------------------------------------------------------# Unified Prompt Generation-# ------------------------------------------------------------------------------[pipe.create_image_prompt]-type = "PipeLLM"-description = "Create an image generation prompt based on category and description"-inputs = { request = "ImageRequest" }-output = "ImgGenPrompt"-model = "$pipe-builder-img-gen-prompting"-prompt = """-Create an image generation prompt based on the category and description.--@request--Generate a typical description of the image.--If the user description is empty or minimal, imagine something reasonable based on the category.-"""--# -----------------------------------------------------------------------------# Category-based Rendering Router-# ------------------------------------------------------------------------------[pipe.route_rendering]-type = "PipeCondition"-description = "Route to appropriate image generation model based on category"-inputs = { request = "ImageRequest", img_prompt = "ImgGenPrompt" }-output = "Image"-expression = "request.category"-outcomes = { photograph = "render_photo", document_scan = "render_ui", handwritten = "render_photo", screenshot = "render_ui", diagram = "render_ui", chart = "render_chart" }-default_outcome = "render_photo"--[pipe.render_photo]-type = "PipeImgGen"-description = "Render photorealistic image"-inputs = { img_prompt = "ImgGenPrompt" }-output = "Image"-prompt = "$img_prompt"-model = "$synthesize-photo"--[pipe.render_ui]-type = "PipeImgGen"-description = "Render UI/diagram image"-inputs = { img_prompt = "ImgGenPrompt" }-output = "Image"-prompt = "$img_prompt"-model = "$synthesize-ui"--[pipe.render_chart]-type = "PipeImgGen"-description = "Render chart image"-inputs = { img_prompt = "ImgGenPrompt" }-output = "Image"-prompt = "$img_prompt"-model = "$synthesize-chart"diff --git a/pipelex/cli/commands/build/app.py b/pipelex/cli/commands/build/app.pyindex 4831c7753..fabe55587 100644--- a/pipelex/cli/commands/build/app.py+++ b/pipelex/cli/commands/build/app.py@@ -2,7 +2,6 @@ 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.pipe_cmd import build_pipe_cmdfrom pipelex.cli.commands.build.runner.app import build_runner_appfrom pipelex.cli.commands.build.structures_cmd import build_structures_command@@ -11,6 +10,5 @@ build_app = typer.Typer(help="Build working pipelines from natural language requ# inputs, output, runner are now Typer groups with 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 TypeScript)")-build_app.command("pipe", help="Build a Pipelex bundle with one validation/fix loop correcting deterministic issues")(build_pipe_cmd)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/pipe_cmd.py b/pipelex/cli/commands/build/pipe_cmd.pydeleted file mode 100644index 60986ae14..000000000--- a/pipelex/cli/commands/build/pipe_cmd.py+++ /dev/null@@ -1,366 +0,0 @@-import asyncio-import os-import time-from pathlib import Path-from typing import Annotated--import typer-from posthog import tag--from pipelex import log-from pipelex.builder.builder_errors import PipeBuilderError-from pipelex.builder.builder_loop import BuilderLoop, maybe_generate_manifest_for_output-from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAME-from pipelex.builder.exceptions import PipelexBundleSpecBlueprintError-from pipelex.builder.runner_code import generate_runner_code-from pipelex.cli.cli_factory import make_pipelex_for_cli-from pipelex.cli.commands.build.structures_cmd import generate_structures_from_blueprints-from pipelex.cli.error_handlers import (- ErrorContext,- handle_build_validation_failure,- handle_model_availability_error,- handle_model_choice_error,-)-from pipelex.config import get_config-from pipelex.core.interpreter.helpers import MTHDS_EXTENSION-from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError-from pipelex.core.pipes.variable_multiplicity import parse_concept_with_multiplicity-from pipelex.graph.graph_factory import generate_graph_outputs, save_graph_outputs_to_dir-from pipelex.hub import get_console, get_report_delegate, get_required_pipe, get_telemetry_manager-from pipelex.language.mthds_factory import MthdsFactory-from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError-from pipelex.pipe_run.pipe_run_mode import PipeRunMode-from pipelex.pipelex import PACKAGE_VERSION, Pipelex-from pipelex.pipeline.runner import PipelexRunner-from pipelex.pipeline.validate_bundle import ValidateBundleError-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,- get_incremental_directory_path,- get_incremental_file_path,- save_text_to_path,-)-from pipelex.tools.misc.json_utils import save_as_json_to_path-from pipelex.tools.misc.pretty import PrettyPrinter--COMMAND = "build"-SUB_COMMAND_PIPE = "pipe"---"""-Today's example:-pipelex build pipe "Imagine a cute animal mascot for a startup based on its elevator pitch"-pipelex build pipe "Imagine a cute animal mascot for a startup based on its elevator pitch and some brand guidelines"-pipelex build pipe "Imagine a cute animal mascot for a startup based on its elevator pitch and some brand guidelines, \- include 3 variants of the ideas and 2 variants of each prompt"-pipelex build pipe "Imagine a cute animal mascot for a startup based on its elevator pitch \- and some brand guidelines, propose 2 different ideas, and for each, 3 style variants in the image generation prompt, \- at the end we want the rendered image" -o mascot--pipelex build pipe "Given an expense report, apply company rules"-pipelex build pipe "Take a CV, a Job offer text, and analyze if they match"-pipelex build pipe "Take a CV and a Job offer text, analyze if they match and generate 5 questions for the interview"-pipelex build pipe "Take a CV and a Job offer, analyze if they match and generate 5 questions for the interview"--pipelex build pipe \- "Take a Job offer text and a bunch of CVs, analyze how each CV matches the Job offer and generate 5 questions for each interview"--pipelex build pipe \- "Take a Job offer and a bunch of CVs, analyze how each CV matches the Job offer and generate 5 questions for each interview"--# Other ideas:-pipelex build pipe "Take a photo as input, and render the opposite of the photo, don't structure anything, use only text content, be super concise"-pipelex build pipe "Take a photo as input, and render the opposite of the photo"-pipelex build pipe "Given an RDFP, build a compliance matrix"-pipelex build pipe "Given a theme, write a Haiku"-"""---def build_pipe_cmd(- prompt: Annotated[- str,- typer.Argument(help="Prompt describing what the pipeline should do"),- ],- builder_pipe: Annotated[- str,- typer.Option("--builder-pipe", help="Builder pipe to use for generating the pipeline"),- ] = "pipe_builder",- output_name: Annotated[- str | None,- typer.Option("--output-name", "-o", help="Base name for the generated file or directory (without extension)"),- ] = None,- output_dir: Annotated[- str | None,- typer.Option("--output-dir", help="Directory where files will be generated"),- ] = None,- no_output: Annotated[- bool,- typer.Option("--no-output", help="Skip saving the pipeline to file"),- ] = False,- no_extras: Annotated[- bool,- typer.Option("--no-extras", help="Skip generating inputs.json and runner.py, only generate the MTHDS file"),- ] = False,- bundle_view: Annotated[- bool,- typer.Option("--bundle-view/--no-bundle-view", help="Generate bundle view HTML and SVG files"),- ] = False,- graph: Annotated[- bool | None,- typer.Option("--graph/--no-graph", help="Generate execution graphs for both build process and built pipeline"),- ] = None,- graph_full_data: Annotated[- bool | None,- typer.Option(- "--graph-full-data/--graph-no-data",- help="Override config: include or exclude full serialized data in graphs (requires --graph)",- ),- ] = None,-) -> None:- make_pipelex_for_cli(context=ErrorContext.VALIDATION_BEFORE_BUILD_PIPE)-- typer.secho("Building pipeline...\n", fg=typer.colors.GREEN, bold=True)-- async def run_pipeline():- start_time = time.time()- # Get builder config- builder_config = get_config().pipelex.builder_config-- # Case 1: --no-output flag → Don't save anything- if no_output:- typer.secho("\n⚠️ Pipeline will not be saved to file (--no-output specified)", fg=typer.colors.YELLOW)-- # Build execution config with graph overrides if --graph is enabled- execution_config = get_config().pipelex.pipeline_execution_config.with_graph_config_overrides(- generate_graph=graph,- force_include_full_data=graph_full_data,- )-- # Build the pipeline- builder_loop = BuilderLoop()- try:- pipelex_bundle_spec, builder_graph_spec = await builder_loop.build_and_fix(- builder_pipe=builder_pipe, inputs={"brief": prompt}, execution_config=execution_config, output_dir=output_dir- )- except PipeBuilderError as exc:- msg = f"Builder loop: Failed to execute pipeline: {exc}."- if exc.working_memory:- failure_memory_path = get_incremental_file_path(- base_path=builder_config.default_output_dir,- base_name="failure_memory",- extension="json",- )- save_as_json_to_path(object_to_save=exc.working_memory.smart_dump(), path=str(failure_memory_path))- typer.secho(f"❌ {msg}", fg=typer.colors.RED)- typer.secho(f"❌ Failure memory saved to: {failure_memory_path}", fg=typer.colors.RED)- else:- typer.secho(f"❌ {msg}", fg=typer.colors.RED)- typer.secho("❌ No failure memory available", fg=typer.colors.RED)- raise typer.Exit(1) from exc- except ValidateBundleError as exc:- handle_build_validation_failure(exc)-- # Return early if no output requested- if no_output:- return-- # Determine base output directory- base_dir = output_dir or builder_config.default_output_dir-- # Determine output path and whether to generate extras- bundle_file_name = Path(f"{builder_config.default_bundle_file_name}{MTHDS_EXTENSION}")-- if no_extras:- # Generate single file: {base_dir}/{name}_01.mthds- name = output_name or builder_config.default_bundle_file_name- mthds_file_path = get_incremental_file_path(- base_path=base_dir,- base_name=name,- extension="mthds",- )- extras_output_dir = "" # Not used in no_extras mode- else:- # Generate directory with extras: {base_dir}/{name}_01/bundle.mthds + extras- dir_name = output_name or builder_config.default_directory_base_name- extras_output_dir = get_incremental_directory_path(- base_path=base_dir,- base_name=dir_name,- )- mthds_file_path = Path(extras_output_dir) / bundle_file_name-- # Save the MTHDS file- ensure_directory_for_file_path(file_path=str(mthds_file_path))- try:- mthds_content = MthdsFactory.make_mthds_content(blueprint=pipelex_bundle_spec.to_blueprint())- except PipelexBundleSpecBlueprintError as exc:- typer.secho(f"❌ Failed to convert bundle spec to blueprint: {exc}", fg=typer.colors.RED)- raise typer.Exit(1) from exc- save_text_to_path(text=mthds_content, path=str(mthds_file_path))- log.verbose(f"Pipelex bundle saved to: {mthds_file_path}")-- if no_extras:- end_time = time.time()- console = get_console()- console.print(f"\n[green]✓[/green] [bold]Pipeline built successfully ({end_time - start_time:.1f}s)[/bold]")- console.print(f" Output: {mthds_file_path}")- return-- # Generate METHODS.toml if multiple domains exist in output dir- manifest_path = maybe_generate_manifest_for_output(output_dir=Path(extras_output_dir))- if manifest_path:- log.verbose(f"Package manifest generated: {manifest_path}")-- # Generate extras (inputs and runner)- main_pipe_code = pipelex_bundle_spec.main_pipe- domain_code = pipelex_bundle_spec.domain- if main_pipe_code:- saved_bundle_view_formats: list[str] = []- saved_structure_names: list[str] = []- saved_graph_sections: list[tuple[str, list[str]]] = []-- try:- if bundle_view:- pretty = pipelex_bundle_spec.rendered_pretty()- # Generate pretty HTML- pretty_html = PrettyPrinter.pretty_html(pretty=pretty)- html_path = os.path.join(extras_output_dir, "bundle_view.html")- save_text_to_path(text=pretty_html, path=html_path)- log.verbose(f"Pretty HTML saved to: {html_path}")- saved_bundle_view_formats.append("html")-- # Generate pretty SVG- pretty_svg = PrettyPrinter.pretty_svg(pretty=pretty)- svg_path = os.path.join(extras_output_dir, "bundle_view.svg")- save_text_to_path(text=pretty_svg, path=svg_path)- log.verbose(f"Pretty SVG saved to: {svg_path}")- saved_bundle_view_formats.append("svg")-- pipe = get_required_pipe(pipe_code=main_pipe_code)-- # Generate structures folder FIRST (before runner, since runner imports from structures)- structures_output_dir = Path(extras_output_dir) / "structures"- generated_structures = generate_structures_from_blueprints(- blueprints=[pipelex_bundle_spec.to_blueprint()],- output_directory=structures_output_dir,- skip_existing_check=True,- quiet=True,- )- if generated_structures:- saved_structure_names = [concept_code for _, concept_code in generated_structures]- log.verbose(f"Generated {len(generated_structures)} structure(s) in: {structures_output_dir}")-- # Generate inputs.json (only if the pipe has inputs)- has_inputs = not pipe.inputs.is_empty- if has_inputs:- inputs_json_str = pipe.inputs.render_inputs(indent=2)- inputs_json_path = os.path.join(extras_output_dir, DEFAULT_INPUTS_FILE_NAME)- save_text_to_path(text=inputs_json_str, path=inputs_json_path)- log.verbose(f"Inputs template saved to: {inputs_json_path}")-- # Determine if output is a list from the bundle spec- main_pipe_spec = pipelex_bundle_spec.pipe[main_pipe_code] if pipelex_bundle_spec.pipe else None- output_is_list = False- if main_pipe_spec:- output_parse = parse_concept_with_multiplicity(main_pipe_spec.output)- output_is_list = output_parse.multiplicity is not None-- # Generate runner.py (after structures are generated)- runner_code = generate_runner_code(pipe, output_multiplicity=output_is_list, library_dir=extras_output_dir)- runner_path = os.path.join(extras_output_dir, f"run_{main_pipe_code}.py")- save_text_to_path(text=runner_code, path=runner_path)- log.verbose(f"Python runner script saved to: {runner_path}")-- # Generate empty __init__.py to make it a proper Python package- init_path = os.path.join(extras_output_dir, "__init__.py")- save_text_to_path(text="", path=init_path)- log.verbose(f"Package init file saved to: {init_path}")-- get_report_delegate().generate_report()-- # Generate graphs if it was tracked during the build process- if builder_graph_spec:- # Save builder pipeline graph in graphs/ subfolder- graphs_dir = Path(extras_output_dir) / "graphs"- builder_graph_dir = graphs_dir / "builder_graph"- builder_graph_outputs = await generate_graph_outputs(- graph_spec=builder_graph_spec,- graph_config=execution_config.graph_config,- pipe_code=builder_pipe,- )- builder_saved = save_graph_outputs_to_dir(graph_outputs=builder_graph_outputs, output_dir=builder_graph_dir)- if builder_saved:- builder_formats = list(dict.fromkeys(key.split("_")[0] for key in builder_saved))- saved_graph_sections.append(("builder", builder_formats))-- # Run built pipeline in dry-run mode to generate its graph- try:- built_pipe_execution_config = execution_config.with_graph_config_overrides(mock_inputs=True)-- # pass empty library_dirs to avoid loading any libraries set at env var or instance level:- # we don't want any other pipeline to interfere with the pipeline we just built- built_runner = PipelexRunner(- pipe_run_mode=PipeRunMode.DRY,- execution_config=built_pipe_execution_config,- library_dirs=[],- )- built_pipe_response = await built_runner.execute_pipeline(- mthds_contents=[mthds_content],- )- built_pipe_output = built_pipe_response.pipe_output- if built_pipe_output.graph_spec:- pipeline_graph_dir = graphs_dir / "pipeline_graph"- log.verbose(f"Saving pipeline graph for pipe {main_pipe_code} to {pipeline_graph_dir}")- pipeline_graph_outputs = await generate_graph_outputs(- graph_spec=built_pipe_output.graph_spec,- graph_config=execution_config.graph_config,- pipe_code=main_pipe_code,- )- pipeline_saved = save_graph_outputs_to_dir(graph_outputs=pipeline_graph_outputs, output_dir=pipeline_graph_dir)- if pipeline_saved:- pipeline_formats = list(dict.fromkeys(key.split("_")[0] for key in pipeline_saved))- saved_graph_sections.append(("pipeline", pipeline_formats))- except Exception as graph_exc:- typer.secho(f"⚠️ Warning: Could not generate built pipeline graph: {graph_exc}", fg=typer.colors.YELLOW)-- # Print completion recap- end_time = time.time()- console = get_console()- console.print(f"\n[green]✓[/green] [bold]Pipeline built successfully ({end_time - start_time:.1f}s)[/bold]")- console.print(f" Output saved to [bold magenta]{extras_output_dir}[/bold magenta]:")- console.print(f" [green]✓[/green] bundle.mthds → {domain_code} → main pipe [red]{main_pipe_code}[/red]")- if saved_bundle_view_formats:- console.print(f" [green]✓[/green] bundle_view: {', '.join(saved_bundle_view_formats)}")- if saved_structure_names:- colored_structures = ", ".join(f"[green]{name}[/green]" for name in saved_structure_names)- console.print(f" [green]✓[/green] structures: {colored_structures}")- if has_inputs:- console.print(f" [green]✓[/green] {DEFAULT_INPUTS_FILE_NAME}")- console.print(f" [green]✓[/green] run_{main_pipe_code}.py")- for graph_label, graph_formats in saved_graph_sections:- console.print(f" [green]✓[/green] graphs/{graph_label}: {', '.join(graph_formats)}")- if has_inputs:- console.print(f"\n [yellow]Note:[/yellow] Fill {DEFAULT_INPUTS_FILE_NAME} with actual data before running.")- console.print(f" To run: [cyan]pipelex run bundle {extras_output_dir}[/cyan]")- else:- console.print(f"\n To run: [cyan]pipelex run bundle {extras_output_dir}[/cyan]")-- except Exception as exc:- typer.secho(f"⚠️ Warning: Could not generate extras: {exc}", fg=typer.colors.YELLOW)-- 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=f"{COMMAND} {SUB_COMMAND_PIPE}")-- asyncio.run(run_pipeline())-- 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.teardown_if_needed()diff --git a/pipelex/cli/error_handlers.py b/pipelex/cli/error_handlers.pyindex 647a113f7..5b9af8644 100644--- a/pipelex/cli/error_handlers.py+++ b/pipelex/cli/error_handlers.py@@ -35,7 +35,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_PIPE = "Pre-validation (build pipe)"VALIDATION_BEFORE_BUILD_RUNNER = "Pre-validation (build runner)"VALIDATION_BEFORE_BUILD_INPUTS = "Pre-validation (build inputs)"VALIDATION_BEFORE_BUILD_OUTPUT = "Pre-validation (build output)"@@ -222,28 +221,6 @@ def handle_validate_bundle_error(exc: ValidateBundleError, bundle_path: Path | Nraise typer.Exit(1) from exc-def handle_build_validation_failure(exc: ValidateBundleError) -> NoReturn:- """Handle ValidateBundleError that occurs when the builder loop cannot auto-fix validation issues.-- Args:- exc: The bundle validation error exception from the build loop- """- console = get_console()- console.print("\n[bold red]❌ Pipe build failed: validation errors could not be auto-fixed[/bold red]\n")- console.print("[yellow]The builder attempted to fix validation errors automatically but could not resolve all issues.[/yellow]\n")-- _display_validation_error_details(console=console, exc=exc)-- # Display build-specific tips- console.print(- "[bold green]💡 Tip:[/bold green] Try rephrasing your prompt or simplifying the pipeline requirements. "- "Breaking complex methods into smaller steps can also help."- )- console.print(f"[dim]Learn more: {URLs.documentation}[/dim]")- console.print(f"[dim]Join our Discord for help: {URLs.discord}[/dim]\n")- raise typer.Exit(1) from exc--def handle_telemetry_config_validation_error(exc: TelemetryConfigValidationError) -> NoReturn:"""Handle and display TelemetryConfigValidationError with migration guidance.diff --git a/pipelex/core/bundles/exceptions.py b/pipelex/core/bundles/exceptions.pyindex ec912a4a9..4329516ab 100644--- a/pipelex/core/bundles/exceptions.py+++ b/pipelex/core/bundles/exceptions.py@@ -5,11 +5,7 @@ from pipelex.types import StrEnumclass PipelexBundleBlueprintFixableErrorType(StrEnum):- """Types of fixable validation errors in Pipelex bundle blueprints.-- These error types represent validation issues that are actually fixed- in the builder loop auto-fix system.- """+ """Types of validation errors in Pipelex bundle blueprints that the build agent can address."""class PipelexBundleBlueprintValidationErrorData(BaseModel):diff --git a/pipelex/core/exceptions.py b/pipelex/core/exceptions.pyindex 123157362..115bb28c4 100644--- a/pipelex/core/exceptions.py+++ b/pipelex/core/exceptions.py@@ -6,8 +6,7 @@ from pipelex.core.pipes.exceptions import PipeFactoryErrorType, PipeValidationErclass PipeFactoryErrorData(BaseModel):"""Structured error data for Pipe factory errors.- This model captures errors raised during pipe creation from blueprints,- particularly missing concept errors that can be auto-fixed by the builder loop.+ This model captures errors raised during pipe creation from blueprints."""# === Error Classification ===diff --git a/pipelex/core/pipes/exceptions.py b/pipelex/core/pipes/exceptions.pyindex 40b6195a6..a5f4ad3f9 100644--- a/pipelex/core/pipes/exceptions.py+++ b/pipelex/core/pipes/exceptions.py@@ -13,11 +13,9 @@ class PipeFactoryErrorType(StrEnum):"""Types of pipe factory errors.These error types are raised during pipe creation from blueprints.- Some are auto-fixed in the builder loop (marked below)."""- # Errors that are auto-fixed in builder_loop.py- UNKNOWN_CONCEPT = "unknown_concept" # AUTO-FIXED: concept not declared in domain+ UNKNOWN_CONCEPT = "unknown_concept"# Generic fallback for unexpected factory errorsUNKNOWN_FACTORY_ERROR = "unknown_factory_error"@@ -26,8 +24,7 @@ class PipeFactoryErrorType(StrEnum):class PipeFactoryError(PipelexError):"""Raised when a pipe cannot be created from a blueprint.- This error includes structured data about the failure, particularly useful- for missing concept errors that can be auto-fixed by the builder loop.+ This error includes structured data about the failure.Attributes:message: Human-readable error message@@ -101,19 +98,16 @@ class PipeValidationErrorType(StrEnum):"""Types of pipe validation errors.These error types are raised during pipe validation from Pipe/Concept classes.- Only some are auto-fixed in the builder loop (marked below)."""- # Errors that are auto-fixed in builder_loop.py- MISSING_INPUT_VARIABLE = "missing_input_variable" # AUTO-FIXED- EXTRANEOUS_INPUT_VARIABLE = "extraneous_input_variable" # AUTO-FIXED- INPUT_STUFF_SPEC_MISMATCH = "input_stuff_spec_mismatch" # AUTO-FIXED- INADEQUATE_OUTPUT_CONCEPT = "inadequate_output_concept" # AUTO-FIXED- INADEQUATE_OUTPUT_MULTIPLICITY = "inadequate_output_multiplicity" # AUTO-FIXED+ MISSING_INPUT_VARIABLE = "missing_input_variable"+ EXTRANEOUS_INPUT_VARIABLE = "extraneous_input_variable"+ INPUT_STUFF_SPEC_MISMATCH = "input_stuff_spec_mismatch"+ INADEQUATE_OUTPUT_CONCEPT = "inadequate_output_concept"+ INADEQUATE_OUTPUT_MULTIPLICITY = "inadequate_output_multiplicity"CIRCULAR_DEPENDENCY_ERROR = "circular_dependency_error"- # Errors that are raised but NOT auto-fixed (will fail validation)LLM_OUTPUT_CANNOT_BE_IMAGE = "llm_output_cannot_be_image"IMG_GEN_INPUT_NOT_TEXT_COMPATIBLE = "img_gen_input_not_text_compatible"INVALID_PIPE_CODE_SYNTAX = "invalid_pipe_code_syntax"diff --git a/pipelex/libraries/library_manager.py b/pipelex/libraries/library_manager.pyindex 1108ed89a..83622afc7 100644--- a/pipelex/libraries/library_manager.py+++ b/pipelex/libraries/library_manager.py@@ -11,8 +11,8 @@ from mthds.package.manifest.schema import MTHDS_STANDARD_VERSION, MethodsManifesfrom pydantic import BaseModel, ValidationErrorfrom typing_extensions import override+import pipelex.builder as builder_pkg # package import — used for __file__ pathfrom pipelex import log-from pipelex.builder import builderfrom pipelex.cli.installed_methods import find_method_by_full_addressfrom pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprintfrom pipelex.core.concepts.concept_factory import ConceptFactory@@ -230,12 +230,12 @@ class LibraryManager(LibraryManagerAbstract):ClassRegistryUtils.import_modules_in_folder(folder_path=str(library_dir),base_class_names=[StructuredContent.__name__],- force_include_dirs=[str(Path(builder.__file__).parent)],+ force_include_dirs=[str(Path(builder_pkg.__file__).parent)],)# Only import files that contain @pipe_func decorated functions (uses AST pre-check)FuncRegistryUtils.register_funcs_in_folder(folder_path=str(library_dir),- force_include_dirs=[str(Path(builder.__file__).parent)],+ force_include_dirs=[str(Path(builder_pkg.__file__).parent)],)# Auto-discover and register all StructuredContent classes from sys.modules@@ -306,7 +306,7 @@ class LibraryManager(LibraryManagerAbstract):ClassRegistryUtils.import_modules_in_folder(folder_path=str(library_dir),base_class_names=[StructuredContent.__name__],- force_include_dirs=[str(Path(builder.__file__).parent)],+ force_include_dirs=[str(Path(builder_pkg.__file__).parent)],)# NOTE: We skip FuncRegistryUtils.register_funcs_in_folder() since we're not loading pipesdiff --git a/pipelex/libraries/library_utils.py b/pipelex/libraries/library_utils.pyindex e78129e5d..7b64a845a 100644--- a/pipelex/libraries/library_utils.py+++ b/pipelex/libraries/library_utils.py@@ -1,8 +1,8 @@from importlib.resources import filesfrom pathlib import Path+import pipelex.builder as builder_pkg # package import — used for __file__ pathfrom pipelex import log-from pipelex.builder import builderfrom pipelex.config import get_configfrom pipelex.core.interpreter.helpers import MTHDS_EXTENSION, is_pipelex_filefrom pipelex.tools.misc.file_utils import find_files_in_dir@@ -76,7 +76,7 @@ def get_pipelex_mthds_files_from_dirs(dirs: set[Path]) -> list[Path]:dir_path=str(dir_path),pattern=f"*{MTHDS_EXTENSION}",excluded_dirs=list(get_config().pipelex.scan_config.excluded_dirs),- force_include_dirs=[str(Path(builder.__file__).parent)],+ force_include_dirs=[str(Path(builder_pkg.__file__).parent)],)# Filter to only include valid Pipelex filesdiff --git a/pipelex/pipeline/validate_bundle.py b/pipelex/pipeline/validate_bundle.pyindex e0d7feb4d..16127d094 100644--- a/pipelex/pipeline/validate_bundle.py+++ b/pipelex/pipeline/validate_bundle.py@@ -19,7 +19,6 @@ from pipelex.core.pipes.handle_pipe_errors import ()from pipelex.core.pipes.pipe_abstract import PipeAbstractfrom pipelex.core.validation import report_validation_error-from pipelex.graph.graphspec import GraphSpecfrom pipelex.hub import get_library_manager, resolve_library_dirs, set_current_libraryfrom pipelex.libraries.library_utils import get_pipelex_mthds_files_from_dirsfrom pipelex.pipe_run.dry_run import DryRunError, DryRunOutput, dry_run_pipes@@ -66,9 +65,6 @@ class ValidateBundleError(PipelexError):# Dry run errorsself.dry_run_error_message = dry_run_error_message- # Path to a saved .mthds file with the last bundle state (set by builder_loop when all fix attempts are exhausted)- self.failed_bundle_path: str | None = None-super().__init__(message)@property@@ -85,7 +81,6 @@ class ValidateBundleResult(BaseModel):blueprints: list[PipelexBundleBlueprint]pipes: list[PipeAbstract]dry_run_result: dict[str, DryRunOutput]- graph_spec: GraphSpec | None = Noneasync def validate_bundle(diff --git a/tests/e2e/pipelex/cli/test_validate_cmd.py b/tests/e2e/pipelex/cli/test_validate_cmd.pyindex f2fa84ebf..ec0331527 100644--- a/tests/e2e/pipelex/cli/test_validate_cmd.py+++ b/tests/e2e/pipelex/cli/test_validate_cmd.py@@ -5,4 +5,7 @@ from pipelex.cli.commands.validate._validate_core import do_validate_all_librariclass TestValidateCommand:def test_validate_all(self):- do_validate_all_libraries_and_dry_run(library_dirs=[Path()])+ # Scan from the pipelex package directory, not CWD, to avoid picking up+ # test fixture .mthds files that conflict with each other (e.g. phase1+ # hierarchical domain fixtures with cross-domain refs but no METHODS.toml)+ do_validate_all_libraries_and_dry_run(library_dirs=[Path(__file__).resolve().parents[4] / "pipelex"])diff --git a/tests/integration/pipelex/builder/test_assemble_pipelex_bundle_spec.py b/tests/integration/pipelex/builder/test_assemble_pipelex_bundle_spec.pydeleted file mode 100644index 3806199f1..000000000--- a/tests/integration/pipelex/builder/test_assemble_pipelex_bundle_spec.py+++ /dev/null@@ -1,134 +0,0 @@-"""Integration tests for the assemble_pipelex_bundle_spec pipe.--These tests verify that the assemble_pipelex_bundle_spec pipe correctly-assembles a PipelexBundleSpec from working memory containing concept specs,-pipe specs, and bundle header spec.-"""--from pathlib import Path-from typing import TYPE_CHECKING, Callable--import pytest--from pipelex import pretty_print-from pipelex.builder.bundle_spec import PipelexBundleSpec-from pipelex.core.concepts.native.concept_native import NativeConceptCode-from pipelex.core.memory.working_memory import WorkingMemory-from pipelex.core.stuffs.list_content import ListContent-from pipelex.core.stuffs.stuff_factory import StuffFactory-from pipelex.hub import get_native_concept, get_pipe_library, get_pipe_router-from pipelex.pipe_run.pipe_job_factory import PipeJobFactory-from pipelex.pipe_run.pipe_run_params import PipeRunMode-from pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactory-from pipelex.pipeline.job_metadata import JobMetadata-from tests.integration.pipelex.test_data import AssemblePipelexBundleSpecTestCases--if TYPE_CHECKING:- from pipelex.builder.concept.concept_spec import ConceptSpec- from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec--[email protected](loop_scope="class")-class TestAssemblePipelexBundleSpec:- """Integration tests for the assemble_pipelex_bundle_spec pipe."""-- @pytest.fixture- def test_library_path(self) -> list[Path]:- """Path to the builder library."""- return [Path("pipelex/builder")]-- @pytest.fixture- def working_memory_with_specs(self, load_test_library: Callable[[list[Path]], None], test_library_path: list[Path]) -> WorkingMemory:- """Create working memory with concept specs, pipe specs, and bundle header spec."""- load_test_library(test_library_path)-- working_memory = WorkingMemory()-- # Add concept_specs as a list- concept_specs_content: ListContent[ConceptSpec] = ListContent(items=AssemblePipelexBundleSpecTestCases.CONCEPT_SPECS)- concept_specs_stuff = StuffFactory.make_stuff(- concept=get_native_concept(NativeConceptCode.TEXT),- content=concept_specs_content,- name="concept_specs",- )- working_memory.add_new_stuff(name="concept_specs", stuff=concept_specs_stuff)-- # Add pipe_specs as a list- pipe_specs_content: ListContent[PipeLLMSpec] = ListContent(items=AssemblePipelexBundleSpecTestCases.PIPE_SPECS)- pipe_specs_stuff = StuffFactory.make_stuff(- concept=get_native_concept(NativeConceptCode.TEXT),- content=pipe_specs_content,- name="pipe_specs",- )- working_memory.add_new_stuff(name="pipe_specs", stuff=pipe_specs_stuff)-- # Add bundle_header_spec- bundle_header_stuff = StuffFactory.make_stuff(- concept=get_native_concept(NativeConceptCode.TEXT),- content=AssemblePipelexBundleSpecTestCases.BUNDLE_HEADER,- name="bundle_header_spec",- )- working_memory.add_new_stuff(name="bundle_header_spec", stuff=bundle_header_stuff)-- return working_memory-- async def test_assemble_pipelex_bundle_spec_pipe_exists(- self,- load_test_library: Callable[[list[Path]], None],- test_library_path: list[Path],- ):- """Test that the assemble_pipelex_bundle_spec pipe is registered in the builder domain."""- load_test_library(test_library_path)-- pipe = get_pipe_library().get_required_pipe(pipe_code="assemble_pipelex_bundle_spec")- assert pipe is not None- assert pipe.code == "assemble_pipelex_bundle_spec"-- async def test_assemble_pipelex_bundle_spec_run(- self,- job_metadata: JobMetadata,- pipe_run_mode: PipeRunMode,- load_test_library: Callable[[list[Path]], None],- test_library_path: list[Path],- working_memory_with_specs: WorkingMemory,- ):- """Test running the assemble_pipelex_bundle_spec pipe to assemble a PipelexBundleSpec."""- load_test_library(test_library_path)-- # Get the pipe from the library- pipe = get_pipe_library().get_required_pipe(pipe_code="assemble_pipelex_bundle_spec")- assert pipe is not None-- # Create and run the pipe job- pipe_job = PipeJobFactory.make_pipe_job(- pipe=pipe,- job_metadata=job_metadata,- working_memory=working_memory_with_specs,- pipe_run_params=PipeRunParamsFactory.make_run_params(pipe_run_mode=pipe_run_mode),- )- pipe_output = await get_pipe_router().run(pipe_job=pipe_job)-- # Verify the output- main_stuff = pipe_output.main_stuff- assert main_stuff is not None-- # Check that the output is a PipelexBundleSpec- content = main_stuff.content- assert isinstance(content, PipelexBundleSpec), f"Expected PipelexBundleSpec, got {type(content)}"-- # Verify the assembled bundle spec- bundle_spec = content- assert bundle_spec.domain == "test_domain"- assert bundle_spec.description == "A test domain for assembly testing."- assert bundle_spec.main_pipe == "generate_plan"-- # Verify concepts were assembled- assert bundle_spec.concept is not None- assert "UserBrief" in bundle_spec.concept- assert "PlanDraft" in bundle_spec.concept-- # Verify pipes were assembled- assert bundle_spec.pipe is not None- assert "generate_plan" in bundle_spec.pipe-- pretty_print(bundle_spec, title="Assembled PipelexBundleSpec")diff --git a/tests/integration/pipelex/builder/test_builder_mthds_validation.py b/tests/integration/pipelex/builder/test_builder_mthds_validation.pydeleted file mode 100644index acf085cba..000000000--- a/tests/integration/pipelex/builder/test_builder_mthds_validation.py+++ /dev/null@@ -1,157 +0,0 @@-"""Tests for validating builder domain MTHDS files.--This module tests that builder.mthds and agentic_builder.mthds are valid and that-input/output types are correctly declared, especially for pipes that receive-batched outputs (lists) from previous steps.-"""--from pathlib import Path-from typing import ClassVar--import pytest--from pipelex.core.interpreter.interpreter import PipelexInterpreter-from pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint-from pipelex.pipeline.validate_bundle import validate_bundle--BUILDER_DIR = Path(__file__).parent.parent.parent.parent.parent / "pipelex" / "builder"---class TestData:- """Test data for builder MTHDS validation tests."""-- BUILDER_MTHDS_PATH: ClassVar[Path] = BUILDER_DIR / "builder.mthds"- AGENTIC_BUILDER_MTHDS_PATH: ClassVar[Path] = BUILDER_DIR / "agentic_builder.mthds"- PIPE_DESIGN_MTHDS_PATH: ClassVar[Path] = BUILDER_DIR / "pipe" / "pipe_design.mthds"---class TestBuilderMthdsValidation:- """Tests that builder domain MTHDS files are valid and type-consistent."""-- @pytest.mark.asyncio(loop_scope="class")- async def test_builder_mthds_loads_and_validates(self):- """Test that builder.mthds can be loaded and validated successfully."""- result = await validate_bundle(- mthds_file_path=TestData.BUILDER_MTHDS_PATH,- library_dirs=[BUILDER_DIR, BUILDER_DIR / "pipe"],- )-- assert result is not None- assert len(result.blueprints) == 1- assert result.blueprints[0].domain == "builder"- assert len(result.pipes) > 0-- @pytest.mark.asyncio(loop_scope="class")- async def test_agentic_builder_mthds_loads_and_validates(self):- """Test that agentic_builder.mthds can be loaded and validated successfully."""- result = await validate_bundle(- mthds_file_path=TestData.AGENTIC_BUILDER_MTHDS_PATH,- library_dirs=[BUILDER_DIR, BUILDER_DIR / "pipe"],- )-- assert result is not None- assert len(result.blueprints) == 1- assert result.blueprints[0].domain == "agentic_builder"- assert len(result.pipes) > 0-- @pytest.mark.asyncio(loop_scope="class")- async def test_pipe_design_mthds_loads_and_validates(self):- """Test that pipe_design.mthds can be loaded and validated successfully."""- result = await validate_bundle(- mthds_file_path=TestData.PIPE_DESIGN_MTHDS_PATH,- library_dirs=[BUILDER_DIR, BUILDER_DIR / "pipe"],- )-- assert result is not None- assert len(result.blueprints) == 1- assert result.blueprints[0].domain == "pipe_design"- assert len(result.pipes) > 0-- def test_assemble_pipelex_bundle_spec_has_list_inputs_in_builder(self):- """Test that assemble_pipelex_bundle_spec declares list inputs correctly in builder.mthds.-- This test catches the bug where pipe_specs was incorrectly declared as- "pipe_design.PipeSpec" instead of "pipe_design.PipeSpec[]" when the pipe- receives the output of a batch_over operation which produces a list.-- See: builder.mthds line 31 (batch_over produces list) and line 332 (input declaration)- """- blueprint = PipelexInterpreter.make_pipelex_bundle_blueprint(bundle_path=TestData.BUILDER_MTHDS_PATH)-- assert blueprint.pipe is not None- assert "assemble_pipelex_bundle_spec" in blueprint.pipe-- pipe_blueprint = blueprint.pipe["assemble_pipelex_bundle_spec"]- assert pipe_blueprint.inputs is not None-- # Verify pipe_specs is declared as a list (with [] notation)- pipe_specs_input = pipe_blueprint.inputs.get("pipe_specs")- assert pipe_specs_input is not None, "assemble_pipelex_bundle_spec must have pipe_specs input"- assert "[]" in pipe_specs_input, f"pipe_specs must be declared as a list (with []) since it receives batch output. Got: {pipe_specs_input}"-- # Verify concept_specs is declared as a list- concept_specs_input = pipe_blueprint.inputs.get("concept_specs")- assert concept_specs_input is not None, "assemble_pipelex_bundle_spec must have concept_specs input"- assert "[]" in concept_specs_input, f"concept_specs must be declared as a list (with []). Got: {concept_specs_input}"-- def test_detail_all_pipe_specs_outputs_list_in_agentic_builder(self):- """Test that detail_all_pipe_specs declares list output in agentic_builder.mthds.-- This test verifies that the PipeBatch that generates pipe_specs correctly- declares its output as a list, which is then consumed by assemble_pipelex_bundle_spec.- """- blueprint = PipelexInterpreter.make_pipelex_bundle_blueprint(bundle_path=TestData.AGENTIC_BUILDER_MTHDS_PATH)-- assert blueprint.pipe is not None- assert "detail_all_pipe_specs" in blueprint.pipe-- pipe_blueprint = blueprint.pipe["detail_all_pipe_specs"]- assert pipe_blueprint.output is not None-- # PipeBatch output should be declared as a list- assert "[]" in pipe_blueprint.output, f"detail_all_pipe_specs (PipeBatch) must declare list output. Got: {pipe_blueprint.output}"-- def test_batch_over_result_consistency_with_subsequent_inputs(self):- """Test that batch_over results are consumed by pipes with matching list inputs.-- In builder.mthds, pipe_builder uses batch_over on detail_pipe_spec to produce pipe_specs.- The subsequent assemble_pipelex_bundle_spec must declare pipe_specs as a list input.- """- blueprint = PipelexInterpreter.make_pipelex_bundle_blueprint(bundle_path=TestData.BUILDER_MTHDS_PATH)-- assert blueprint.pipe is not None-- # Find the pipe_builder sequence (we know it's a PipeSequenceBlueprint)- pipe_builder = blueprint.pipe.get("pipe_builder")- assert pipe_builder is not None- assert isinstance(pipe_builder, PipeSequenceBlueprint), "pipe_builder should be a PipeSequenceBlueprint"- assert pipe_builder.steps is not None-- # Find the step that uses batch_over and its result name- batch_result_name: str | None = None- for step in pipe_builder.steps:- if step.batch_over:- batch_result_name = step.result- break-- assert batch_result_name is not None, "pipe_builder should have a batch_over step with a result"-- # Find the assemble step that should consume this batch result- has_assemble_step = False- for step in pipe_builder.steps:- if step.pipe == "assemble_pipelex_bundle_spec":- has_assemble_step = True- break-- assert has_assemble_step, "pipe_builder should have assemble_pipelex_bundle_spec step"-- # Verify the assemble pipe declares the batch result as a list input- assemble_pipe = blueprint.pipe.get("assemble_pipelex_bundle_spec")- assert assemble_pipe is not None- assert assemble_pipe.inputs is not None-- batch_input = assemble_pipe.inputs.get(batch_result_name)- assert batch_input is not None, f"assemble_pipelex_bundle_spec must have {batch_result_name} input to receive batch result"- assert "[]" in batch_input, (- f"assemble_pipelex_bundle_spec.{batch_result_name} must be declared as a list since it receives batch_over output. Got: {batch_input}"- )diff --git a/tests/integration/pipelex/test_data.py b/tests/integration/pipelex/test_data.pyindex 99e07e7cb..fc8eeac40 100644--- a/tests/integration/pipelex/test_data.py+++ b/tests/integration/pipelex/test_data.py@@ -1,8 +1,5 @@from typing import ClassVar-from pipelex.builder.bundle_header_spec import BundleHeaderSpec-from pipelex.builder.concept.concept_spec import ConceptSpec-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpecfrom pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.pipes.variable_multiplicity import VariableMultiplicity@@ -416,38 +413,3 @@ Extract information from the following text:("Nested unions complex", NESTED_UNIONS_COMPLEX, "ConceptWithNestedUnions"),("Nested unions mixed", NESTED_UNIONS_MIXED, "ConceptWithNestedUnions"),]---class AssemblePipelexBundleSpecTestCases:- """Test data for assemble_pipelex_bundle_spec tests."""-- CONCEPT_SPECS: ClassVar[list[ConceptSpec]] = [- ConceptSpec(- the_concept_code="UserBrief",- description="A short, natural-language description of what the user wants.",- refines="Text",- ),- ConceptSpec(- the_concept_code="PlanDraft",- description="Natural-language pipeline plan text describing sequences, inputs, outputs.",- refines="Text",- ),- ]-- PIPE_SPECS: ClassVar[list[PipeLLMSpec]] = [- PipeLLMSpec(- pipe_code="generate_plan",- description="Generate a plan from a user brief.",- inputs={"brief": "UserBrief"},- output="PlanDraft",- model="$engineering-structured",- prompt="Generate a plan for: @brief",- ),- ]-- BUNDLE_HEADER = BundleHeaderSpec(- domain_code="test_domain",- description="A test domain for assembly testing.",- system_prompt=None,- main_pipe="generate_plan",- )diff --git a/tests/unit/pipelex/builder/test_builder_loop_multiplicity_fix.py b/tests/unit/pipelex/builder/test_builder_loop_multiplicity_fix.pydeleted file mode 100644index cfa203282..000000000--- a/tests/unit/pipelex/builder/test_builder_loop_multiplicity_fix.py+++ /dev/null@@ -1,407 +0,0 @@-from pipelex.builder.builder_loop import BuilderLoop-from pipelex.builder.bundle_spec import PipelexBundleSpec-from pipelex.builder.concept.concept_spec import ConceptSpec, ConceptStructureSpec, ConceptStructureSpecFieldType-from pipelex.builder.pipe.pipe_compose_spec import PipeComposeSpec-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec--ERROR_MESSAGE_TEMPLATE = (- "Dry run failed for pipe '{parent_pipe}': In pipe '{compose_pipe}' (output: {output_concept}): "- "Cannot validate {output_concept}: Validation error(s):\n"- "Other validation errors:\n"- "{field_name}: string_type: Input should be a valid string\n"- "Field type summary:\n"- " {field_name}: ListContent (expected str) <-- MISMATCH"-)--ERROR_MESSAGE_MULTI_MISMATCH_TEMPLATE = (- "Dry run failed for pipe 'main_sequence': In pipe 'compose_result' (output: ResultPackage): "- "Cannot validate ResultPackage: Validation error(s):\n"- "Other validation errors:\n"- "questions: string_type: Input should be a valid string\n"- "answers: string_type: Input should be a valid string\n"- "Field type summary:\n"- " title: str (expected str)\n"- " questions: ListContent (expected str) <-- MISMATCH\n"- " answers: ListContent (expected str) <-- MISMATCH"-)---def _make_bundle_with_compose(- compose_pipe_code: str = "compose_result",- output_concept_code: str = "ResultPackage",- field_name: str = "interview_questions",- input_variable: str = "interview_questions",- input_concept: str = "InterviewQuestion",- field_type: ConceptStructureSpecFieldType = ConceptStructureSpecFieldType.TEXT,- item_type: str | None = None,- item_concept_ref: str | None = None,-) -> PipelexBundleSpec:- """Create a minimal PipelexBundleSpec with a PipeCompose for testing."""- return PipelexBundleSpec(- domain="test",- main_pipe=compose_pipe_code,- concept={- "InterviewQuestion": ConceptSpec(- the_concept_code="InterviewQuestion",- description="An interview question",- refines="Text",- ),- output_concept_code: ConceptSpec(- the_concept_code=output_concept_code,- description="A result package",- structure={- "title": ConceptStructureSpec(- the_field_name="title",- description="A title",- type=ConceptStructureSpecFieldType.TEXT,- ),- field_name: ConceptStructureSpec(- the_field_name=field_name,- description="Some items",- type=field_type,- item_type=item_type,- item_concept_ref=item_concept_ref,- ),- },- ),- },- pipe={- compose_pipe_code: PipeComposeSpec(- pipe_code=compose_pipe_code,- description="Compose the result",- inputs={- "title": "Text",- input_variable: input_concept,- },- output=output_concept_code,- construct_spec={- "title": {"from": "title"},- field_name: {"from": input_variable},- },- ),- },- )---class TestBuilderLoopMultiplicityFix:- """Tests for _fix_dry_run_compose_multiplicity_mismatch in BuilderLoop."""-- def test_fix_list_content_to_str_mismatch(self):- """Fix ListContent vs str mismatch: adds [] to input and changes concept field to list."""- bundle_spec = _make_bundle_with_compose(- compose_pipe_code="compose_preparation_package",- output_concept_code="InterviewPreparationPackage",- field_name="interview_questions",- input_variable="interview_questions",- input_concept="InterviewQuestion",- )-- error_message = ERROR_MESSAGE_TEMPLATE.format(- parent_pipe="prepare_interview",- compose_pipe="compose_preparation_package",- output_concept="InterviewPreparationPackage",- field_name="interview_questions",- )-- builder_loop = BuilderLoop()- fixed_pipes = builder_loop._fix_dry_run_compose_multiplicity_mismatch( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]- dry_run_error_message=error_message,- pipelex_bundle_spec=bundle_spec,- )-- # Check a pipe was fixed- assert len(fixed_pipes) == 1-- # Check the pipe input was updated to add []- assert bundle_spec.pipe is not None- pipe_spec = bundle_spec.pipe["compose_preparation_package"]- assert isinstance(pipe_spec, PipeComposeSpec)- assert pipe_spec.inputs is not None- assert pipe_spec.inputs["interview_questions"] == "InterviewQuestion[]"-- # Check the concept structure field was updated to LIST- assert bundle_spec.concept is not None- concept_spec = bundle_spec.concept["InterviewPreparationPackage"]- assert isinstance(concept_spec, ConceptSpec)- assert concept_spec.structure is not None- field_spec = concept_spec.structure["interview_questions"]- assert field_spec.type == ConceptStructureSpecFieldType.LIST- assert field_spec.item_type == "concept"- assert field_spec.item_concept_ref == "InterviewQuestion"-- def test_fix_multiple_mismatches(self):- """Fix multiple mismatched fields in one error."""- bundle_spec = PipelexBundleSpec(- domain="test",- main_pipe="compose_result",- concept={- "Question": ConceptSpec(- the_concept_code="Question",- description="A question",- refines="Text",- ),- "Answer": ConceptSpec(- the_concept_code="Answer",- description="An answer",- refines="Text",- ),- "ResultPackage": ConceptSpec(- the_concept_code="ResultPackage",- description="A result package",- structure={- "title": ConceptStructureSpec(- the_field_name="title",- description="A title",- type=ConceptStructureSpecFieldType.TEXT,- ),- "questions": ConceptStructureSpec(- the_field_name="questions",- description="List of questions",- type=ConceptStructureSpecFieldType.TEXT,- ),- "answers": ConceptStructureSpec(- the_field_name="answers",- description="List of answers",- type=ConceptStructureSpecFieldType.TEXT,- ),- },- ),- },- pipe={- "compose_result": PipeComposeSpec(- pipe_code="compose_result",- description="Compose result",- inputs={- "title": "Text",- "questions": "Question",- "answers": "Answer",- },- output="ResultPackage",- construct_spec={- "title": {"from": "title"},- "questions": {"from": "questions"},- "answers": {"from": "answers"},- },- ),- },- )-- builder_loop = BuilderLoop()- fixed_pipes = builder_loop._fix_dry_run_compose_multiplicity_mismatch( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]- dry_run_error_message=ERROR_MESSAGE_MULTI_MISMATCH_TEMPLATE,- pipelex_bundle_spec=bundle_spec,- )-- assert len(fixed_pipes) == 1-- # Check both inputs were fixed- assert bundle_spec.pipe is not None- pipe_spec = bundle_spec.pipe["compose_result"]- assert isinstance(pipe_spec, PipeComposeSpec)- assert pipe_spec.inputs is not None- assert pipe_spec.inputs["questions"] == "Question[]"- assert pipe_spec.inputs["answers"] == "Answer[]"- # Title should remain unchanged- assert pipe_spec.inputs["title"] == "Text"-- # Check both concept structure fields were fixed- assert bundle_spec.concept is not None- concept_spec = bundle_spec.concept["ResultPackage"]- assert isinstance(concept_spec, ConceptSpec)- assert concept_spec.structure is not None- assert concept_spec.structure["questions"].type == ConceptStructureSpecFieldType.LIST- assert concept_spec.structure["questions"].item_concept_ref == "Question"- assert concept_spec.structure["answers"].type == ConceptStructureSpecFieldType.LIST- assert concept_spec.structure["answers"].item_concept_ref == "Answer"- # Title field should remain TEXT- assert concept_spec.structure["title"].type == ConceptStructureSpecFieldType.TEXT-- def test_skip_input_already_has_multiplicity(self):- """Skip fixing when the input already has multiplicity notation."""- bundle_spec = _make_bundle_with_compose(- compose_pipe_code="compose_preparation_package",- output_concept_code="InterviewPreparationPackage",- field_name="interview_questions",- input_variable="interview_questions",- input_concept="InterviewQuestion[]",- field_type=ConceptStructureSpecFieldType.LIST,- item_type="concept",- item_concept_ref="InterviewQuestion",- )-- error_message = ERROR_MESSAGE_TEMPLATE.format(- parent_pipe="prepare_interview",- compose_pipe="compose_preparation_package",- output_concept="InterviewPreparationPackage",- field_name="interview_questions",- )-- builder_loop = BuilderLoop()- fixed_pipes = builder_loop._fix_dry_run_compose_multiplicity_mismatch( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]- dry_run_error_message=error_message,- pipelex_bundle_spec=bundle_spec,- )-- # No pipes should be fixed since input already has multiplicity- assert len(fixed_pipes) == 0-- def test_fix_concept_field_when_input_already_has_multiplicity(self):- """Fix concept field even when the input already has multiplicity notation (e.g., InterviewQuestion[5])."""- bundle_spec = _make_bundle_with_compose(- compose_pipe_code="compose_final_report",- output_concept_code="InterviewPreparationReport",- field_name="interview_questions",- input_variable="interview_questions",- input_concept="InterviewQuestion[5]",- field_type=ConceptStructureSpecFieldType.TEXT,- )-- error_message = ERROR_MESSAGE_TEMPLATE.format(- parent_pipe="prepare_interview",- compose_pipe="compose_final_report",- output_concept="InterviewPreparationReport",- field_name="interview_questions",- )-- builder_loop = BuilderLoop()- fixed_pipes = builder_loop._fix_dry_run_compose_multiplicity_mismatch( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]- dry_run_error_message=error_message,- pipelex_bundle_spec=bundle_spec,- )-- # Pipe should be fixed (concept field changed)- assert len(fixed_pipes) == 1-- # Input should remain unchanged (already had multiplicity)- assert bundle_spec.pipe is not None- pipe_spec = bundle_spec.pipe["compose_final_report"]- assert isinstance(pipe_spec, PipeComposeSpec)- assert pipe_spec.inputs is not None- assert pipe_spec.inputs["interview_questions"] == "InterviewQuestion[5]"-- # Concept structure field should be updated to LIST- assert bundle_spec.concept is not None- concept_spec = bundle_spec.concept["InterviewPreparationReport"]- assert isinstance(concept_spec, ConceptSpec)- assert concept_spec.structure is not None- field_spec = concept_spec.structure["interview_questions"]- assert field_spec.type == ConceptStructureSpecFieldType.LIST- assert field_spec.item_type == "concept"- assert field_spec.item_concept_ref == "InterviewQuestion"-- def test_skip_non_pipe_compose(self):- """Skip fixing when the pipe is not a PipeComposeSpec."""- bundle_spec = PipelexBundleSpec(- domain="test",- main_pipe="some_llm_pipe",- concept={},- pipe={- "some_llm_pipe": PipeLLMSpec(- pipe_code="some_llm_pipe",- description="An LLM pipe",- inputs={"input_text": "Text"},- output="Text",- model="$retrieval",- prompt="Do something with @input_text",- ),- },- )-- error_message = (- "Dry run failed for pipe 'main': In pipe 'some_llm_pipe' (output: Text): "- "Cannot validate Text: Validation error(s):\n"- "Field type summary:\n"- " content: ListContent (expected str) <-- MISMATCH"- )-- builder_loop = BuilderLoop()- fixed_pipes = builder_loop._fix_dry_run_compose_multiplicity_mismatch( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]- dry_run_error_message=error_message,- pipelex_bundle_spec=bundle_spec,- )-- assert len(fixed_pipes) == 0-- def test_skip_no_mismatch_pattern(self):- """Skip fixing when the error message has no MISMATCH pattern."""- bundle_spec = _make_bundle_with_compose()-- error_message = "Some other dry run error without mismatch pattern"-- builder_loop = BuilderLoop()- fixed_pipes = builder_loop._fix_dry_run_compose_multiplicity_mismatch( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]- dry_run_error_message=error_message,- pipelex_bundle_spec=bundle_spec,- )-- assert len(fixed_pipes) == 0-- def test_skip_concept_not_in_bundle(self):- """Fix input but gracefully handle missing concept in bundle."""- bundle_spec = PipelexBundleSpec(- domain="test",- main_pipe="compose_result",- concept={- "InterviewQuestion": ConceptSpec(- the_concept_code="InterviewQuestion",- description="An interview question",- refines="Text",- ),- # Note: MissingConcept is NOT in the bundle concepts- },- pipe={- "compose_result": PipeComposeSpec(- pipe_code="compose_result",- description="Compose result",- inputs={"questions": "InterviewQuestion"},- output="MissingConcept",- construct_spec={"questions": {"from": "questions"}},- ),- },- )-- error_message = (- "Dry run failed for pipe 'main': In pipe 'compose_result' (output: MissingConcept): "- "Cannot validate MissingConcept: Validation error(s):\n"- "Field type summary:\n"- " questions: ListContent (expected str) <-- MISMATCH"- )-- builder_loop = BuilderLoop()- fixed_pipes = builder_loop._fix_dry_run_compose_multiplicity_mismatch( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]- dry_run_error_message=error_message,- pipelex_bundle_spec=bundle_spec,- )-- # Pipe input is still fixed even if concept structure can't be updated- assert len(fixed_pipes) == 1- assert bundle_spec.pipe is not None- pipe_spec = bundle_spec.pipe["compose_result"]- assert isinstance(pipe_spec, PipeComposeSpec)- assert pipe_spec.inputs is not None- assert pipe_spec.inputs["questions"] == "InterviewQuestion[]"-- def test_no_pipes_in_bundle(self):- """Handle empty pipe dict gracefully."""- # Use model_construct to bypass validation (PipelexBundleSpec requires main_pipe in pipes)- bundle_spec = PipelexBundleSpec.model_construct(- domain="test",- main_pipe="main",- concept={},- pipe={},- )-- error_message = ERROR_MESSAGE_TEMPLATE.format(- parent_pipe="main",- compose_pipe="compose_result",- output_concept="Result",- field_name="items",- )-- builder_loop = BuilderLoop()- fixed_pipes = builder_loop._fix_dry_run_compose_multiplicity_mismatch( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]- dry_run_error_message=error_message,- pipelex_bundle_spec=bundle_spec,- )-- assert len(fixed_pipes) == 0diff --git a/tests/unit/pipelex/builder/test_builder_loop_namespace_stripping.py b/tests/unit/pipelex/builder/test_builder_loop_namespace_stripping.pydeleted file mode 100644index 4fbabbdbc..000000000--- a/tests/unit/pipelex/builder/test_builder_loop_namespace_stripping.py+++ /dev/null@@ -1,568 +0,0 @@-import pytest--from pipelex.builder.builder_loop import BuilderLoop-from pipelex.builder.bundle_spec import PipelexBundleSpec-from pipelex.builder.pipe.pipe_batch_spec import PipeBatchSpec-from pipelex.builder.pipe.pipe_condition_spec import PipeConditionSpec-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpec-from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.builder.pipe.pipe_spec_union import PipeSpecUnion-from pipelex.builder.pipe.sub_pipe_spec import SubPipeSpec-from pipelex.pipe_controllers.condition.special_outcome import SpecialOutcome---def _make_bundle(- domain: str = "scoring",- main_pipe: str = "main",- pipes: dict[str, PipeSpecUnion] | None = None,-) -> PipelexBundleSpec:- """Create a minimal PipelexBundleSpec for namespace stripping tests."""- return PipelexBundleSpec.model_construct(- domain=domain,- main_pipe=main_pipe,- concept={},- pipe=pipes or {},- )---class TestBuilderLoopNamespaceStripping:- """Tests for _strip_namespace_from_pipe_codes and _strip_dotted_pipe_code in BuilderLoop."""-- # --- Tests for _strip_dotted_pipe_code ----- @pytest.mark.parametrize(- ("pipe_code", "expected"),- [- ("my_pipe", "my_pipe"),- ("foo.my_pipe", "my_pipe"),- ("a.b.my_pipe", "my_pipe"),- ("scoring.compute_score", "compute_score"),- ],- )- def test_strip_dotted_pipe_code(self, pipe_code: str, expected: str) -> None:- """Verify _strip_dotted_pipe_code extracts bare code after last dot."""- result = BuilderLoop._strip_dotted_pipe_code(pipe_code) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]- assert result == expected-- # --- Tests for pipe dict key stripping ----- def test_dotted_pipe_key_is_stripped(self) -> None:- """A dotted pipe dict key 'foo.my_pipe' should be stripped to 'my_pipe'."""- bundle = _make_bundle(- main_pipe="my_pipe",- pipes={- "foo.my_pipe": PipeLLMSpec.model_construct(- pipe_code="foo.my_pipe",- description="A pipe",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Do stuff",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.pipe is not None- assert "my_pipe" in result.pipe- assert "foo.my_pipe" not in result.pipe-- def test_multi_segment_dotted_key_is_stripped(self) -> None:- """A multi-segment dotted key 'a.b.my_pipe' should be stripped to 'my_pipe'."""- bundle = _make_bundle(- main_pipe="my_pipe",- pipes={- "a.b.my_pipe": PipeLLMSpec.model_construct(- pipe_code="a.b.my_pipe",- description="A pipe",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Do stuff",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.pipe is not None- assert "my_pipe" in result.pipe- assert "a.b.my_pipe" not in result.pipe-- def test_bare_snake_case_key_passes_through(self) -> None:- """A bare snake_case key should pass through unchanged."""- bundle = _make_bundle(- main_pipe="compute_score",- pipes={- "compute_score": PipeLLMSpec.model_construct(- pipe_code="compute_score",- description="A pipe",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Do stuff",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.pipe is not None- assert "compute_score" in result.pipe-- # --- Tests for main_pipe stripping ----- def test_main_pipe_with_dot_prefix_is_stripped(self) -> None:- """main_pipe with a dot prefix should be stripped."""- bundle = _make_bundle(- main_pipe="scoring.main_sequence",- pipes={- "main_sequence": PipeLLMSpec.model_construct(- pipe_code="main_sequence",- description="Main",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Do stuff",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.main_pipe == "main_sequence"-- # --- Tests for PipeSpec.pipe_code stripping ----- def test_pipe_code_field_with_dot_is_stripped(self) -> None:- """PipeSpec.pipe_code with a dot prefix should be stripped."""- bundle = _make_bundle(- main_pipe="my_pipe",- pipes={- "scoring.my_pipe": PipeLLMSpec.model_construct(- pipe_code="scoring.my_pipe",- description="A pipe",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Do stuff",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.pipe is not None- pipe_spec = result.pipe["my_pipe"]- assert pipe_spec.pipe_code == "my_pipe"-- # --- Tests for PipeBatchSpec.branch_pipe_code stripping ----- def test_batch_branch_pipe_code_with_dot_is_stripped(self) -> None:- """PipeBatchSpec.branch_pipe_code with a dot prefix should be stripped."""- bundle = _make_bundle(- main_pipe="batch_pipe",- pipes={- "batch_pipe": PipeBatchSpec.model_construct(- pipe_code="batch_pipe",- description="Batch",- type="PipeBatch",- pipe_category="PipeController",- inputs={"items": "Text[]"},- output="Text[]",- branch_pipe_code="scoring.process_item",- input_list_name="items",- input_item_name="item",- ),- "process_item": PipeLLMSpec.model_construct(- pipe_code="process_item",- description="Process",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={"item": "Text"},- output="Text",- model="$retrieval",- prompt="Process @item",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.pipe is not None- batch_spec = result.pipe["batch_pipe"]- assert isinstance(batch_spec, PipeBatchSpec)- assert batch_spec.branch_pipe_code == "process_item"-- # --- Tests for PipeSequenceSpec.steps stripping ----- def test_sequence_step_pipe_code_with_dot_is_stripped(self) -> None:- """PipeSequenceSpec.steps[*].pipe_code with a dot prefix should be stripped."""- bundle = _make_bundle(- main_pipe="main_seq",- pipes={- "main_seq": PipeSequenceSpec.model_construct(- pipe_code="main_seq",- description="Sequence",- type="PipeSequence",- pipe_category="PipeController",- inputs={},- output="Text",- steps=[- SubPipeSpec(pipe_code="scoring.step_one", result="result_one"),- SubPipeSpec(pipe_code="step_two", result="result_two"),- ],- ),- "step_one": PipeLLMSpec.model_construct(- pipe_code="step_one",- description="Step one",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Step 1",- ),- "step_two": PipeLLMSpec.model_construct(- pipe_code="step_two",- description="Step two",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Step 2",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.pipe is not None- seq_spec = result.pipe["main_seq"]- assert isinstance(seq_spec, PipeSequenceSpec)- assert seq_spec.steps[0].pipe_code == "step_one"- assert seq_spec.steps[1].pipe_code == "step_two"-- # --- Tests for PipeParallelSpec.branches stripping ----- def test_parallel_branch_pipe_code_with_dot_is_stripped(self) -> None:- """PipeParallelSpec.branches[*].pipe_code with a dot prefix should be stripped."""- bundle = _make_bundle(- main_pipe="main_par",- pipes={- "main_par": PipeParallelSpec.model_construct(- pipe_code="main_par",- description="Parallel",- type="PipeParallel",- pipe_category="PipeController",- inputs={},- output="Text",- branches=[- SubPipeSpec(pipe_code="scoring.branch_a", result="result_a"),- SubPipeSpec(pipe_code="branch_b", result="result_b"),- ],- add_each_output=True,- combined_output=None,- ),- "branch_a": PipeLLMSpec.model_construct(- pipe_code="branch_a",- description="Branch A",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Branch A",- ),- "branch_b": PipeLLMSpec.model_construct(- pipe_code="branch_b",- description="Branch B",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Branch B",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.pipe is not None- par_spec = result.pipe["main_par"]- assert isinstance(par_spec, PipeParallelSpec)- assert par_spec.branches[0].pipe_code == "branch_a"- assert par_spec.branches[1].pipe_code == "branch_b"-- # --- Tests for PipeConditionSpec stripping ----- def test_condition_outcomes_with_dot_are_stripped(self) -> None:- """PipeConditionSpec outcomes values with dot prefixes should be stripped."""- bundle = _make_bundle(- main_pipe="main_cond",- pipes={- "main_cond": PipeConditionSpec.model_construct(- pipe_code="main_cond",- description="Condition",- type="PipeCondition",- pipe_category="PipeController",- inputs={},- output="Text",- jinja2_expression_template="{{ status }}",- outcomes={- "good": "scoring.handle_good",- "bad": "scoring.handle_bad",- },- default_outcome="scoring.handle_default",- ),- "handle_good": PipeLLMSpec.model_construct(- pipe_code="handle_good",- description="Handle good",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Good",- ),- "handle_bad": PipeLLMSpec.model_construct(- pipe_code="handle_bad",- description="Handle bad",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Bad",- ),- "handle_default": PipeLLMSpec.model_construct(- pipe_code="handle_default",- description="Handle default",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Default",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.pipe is not None- cond_spec = result.pipe["main_cond"]- assert isinstance(cond_spec, PipeConditionSpec)- assert cond_spec.outcomes["good"] == "handle_good"- assert cond_spec.outcomes["bad"] == "handle_bad"- assert cond_spec.default_outcome == "handle_default"-- def test_condition_special_outcomes_are_left_intact(self) -> None:- """SpecialOutcome values ('fail', 'continue') in condition outcomes should not be stripped."""- bundle = _make_bundle(- main_pipe="main_cond",- pipes={- "main_cond": PipeConditionSpec.model_construct(- pipe_code="main_cond",- description="Condition",- type="PipeCondition",- pipe_category="PipeController",- inputs={},- output="Text",- jinja2_expression_template="{{ status }}",- outcomes={- "good": "scoring.handle_good",- "bad": SpecialOutcome.FAIL,- "neutral": SpecialOutcome.CONTINUE,- },- default_outcome=SpecialOutcome.FAIL,- ),- "handle_good": PipeLLMSpec.model_construct(- pipe_code="handle_good",- description="Handle good",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Good",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.pipe is not None- cond_spec = result.pipe["main_cond"]- assert isinstance(cond_spec, PipeConditionSpec)- assert cond_spec.outcomes["good"] == "handle_good"- assert cond_spec.outcomes["bad"] == SpecialOutcome.FAIL- assert cond_spec.outcomes["neutral"] == SpecialOutcome.CONTINUE- assert cond_spec.default_outcome == SpecialOutcome.FAIL-- # --- Tests for cross-domain references left intact ----- def test_cross_domain_sequence_step_not_stripped(self) -> None:- """A dotted reference whose bare code is NOT defined in the bundle should be left intact."""- bundle = _make_bundle(- main_pipe="main_seq",- pipes={- "main_seq": PipeSequenceSpec.model_construct(- pipe_code="main_seq",- description="Sequence",- type="PipeSequence",- pipe_category="PipeController",- inputs={},- output="Text",- steps=[- SubPipeSpec(pipe_code="other_domain.external_pipe", result="ext_result"),- SubPipeSpec(pipe_code="scoring.local_pipe", result="loc_result"),- ],- ),- "local_pipe": PipeLLMSpec.model_construct(- pipe_code="local_pipe",- description="Local",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Local",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.pipe is not None- seq_spec = result.pipe["main_seq"]- assert isinstance(seq_spec, PipeSequenceSpec)- # external_pipe is NOT defined in the bundle → reference left intact- assert seq_spec.steps[0].pipe_code == "other_domain.external_pipe"- # local_pipe IS defined in the bundle → reference stripped- assert seq_spec.steps[1].pipe_code == "local_pipe"-- def test_cross_domain_condition_outcome_not_stripped(self) -> None:- """A dotted condition outcome whose bare code is NOT in the bundle should be left intact."""- bundle = _make_bundle(- main_pipe="main_cond",- pipes={- "main_cond": PipeConditionSpec.model_construct(- pipe_code="main_cond",- description="Condition",- type="PipeCondition",- pipe_category="PipeController",- inputs={},- output="Text",- jinja2_expression_template="{{ status }}",- outcomes={- "local": "scoring.handle_local",- "external": "other_domain.handle_external",- },- default_outcome="other_domain.handle_fallback",- ),- "handle_local": PipeLLMSpec.model_construct(- pipe_code="handle_local",- description="Handle local",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Local",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.pipe is not None- cond_spec = result.pipe["main_cond"]- assert isinstance(cond_spec, PipeConditionSpec)- # handle_local IS in bundle → stripped- assert cond_spec.outcomes["local"] == "handle_local"- # handle_external is NOT in bundle → left intact- assert cond_spec.outcomes["external"] == "other_domain.handle_external"- # handle_fallback is NOT in bundle → left intact- assert cond_spec.default_outcome == "other_domain.handle_fallback"-- def test_cross_domain_batch_branch_not_stripped(self) -> None:- """A dotted batch branch_pipe_code whose bare code is NOT in the bundle should be left intact."""- bundle = _make_bundle(- main_pipe="batch_pipe",- pipes={- "batch_pipe": PipeBatchSpec.model_construct(- pipe_code="batch_pipe",- description="Batch",- type="PipeBatch",- pipe_category="PipeController",- inputs={"items": "Text[]"},- output="Text[]",- branch_pipe_code="other_domain.external_process",- input_list_name="items",- input_item_name="item",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.pipe is not None- batch_spec = result.pipe["batch_pipe"]- assert isinstance(batch_spec, PipeBatchSpec)- # external_process is NOT in the bundle → left intact- assert batch_spec.branch_pipe_code == "other_domain.external_process"-- # --- Test for no-op on clean bundle ----- def test_clean_bundle_passes_through_unchanged(self) -> None:- """A bundle with no dotted pipe codes should pass through unchanged."""- bundle = _make_bundle(- main_pipe="main_seq",- pipes={- "main_seq": PipeSequenceSpec.model_construct(- pipe_code="main_seq",- description="Sequence",- type="PipeSequence",- pipe_category="PipeController",- inputs={},- output="Text",- steps=[- SubPipeSpec(pipe_code="step_one", result="result_one"),- ],- ),- "step_one": PipeLLMSpec.model_construct(- pipe_code="step_one",- description="Step one",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Step 1",- ),- },- )-- result = BuilderLoop._strip_namespace_from_pipe_codes(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.main_pipe == "main_seq"- assert result.pipe is not None- assert set(result.pipe.keys()) == {"main_seq", "step_one"}- seq_spec = result.pipe["main_seq"]- assert isinstance(seq_spec, PipeSequenceSpec)- assert seq_spec.steps[0].pipe_code == "step_one"diff --git a/tests/unit/pipelex/builder/test_builder_loop_prune.py b/tests/unit/pipelex/builder/test_builder_loop_prune.pydeleted file mode 100644index bd529e7e0..000000000--- a/tests/unit/pipelex/builder/test_builder_loop_prune.py+++ /dev/null@@ -1,367 +0,0 @@-import logging--import pytest--from pipelex.builder.builder_loop import BuilderLoop-from pipelex.builder.bundle_spec import PipelexBundleSpec-from pipelex.builder.concept.concept_spec import ConceptSpec, ConceptStructureSpec, ConceptStructureSpecFieldType-from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec-from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.builder.pipe.pipe_spec_union import PipeSpecUnion-from pipelex.builder.pipe.sub_pipe_spec import SubPipeSpec---def _make_bundle_for_prune(- domain: str = "my_domain",- main_pipe: str = "main_sequence",- pipes: dict[str, PipeSpecUnion] | None = None,- concepts: dict[str, ConceptSpec | str] | None = None,-) -> PipelexBundleSpec:- """Create a minimal PipelexBundleSpec for testing _prune_unreachable_specs."""- return PipelexBundleSpec.model_construct(- domain=domain,- main_pipe=main_pipe,- concept=concepts or {},- pipe=pipes or {},- )---class TestBuilderLoopPruneUnreachableSpecs:- """Tests for _prune_unreachable_specs and _extract_local_bare_code in BuilderLoop."""-- # --- Tests for _extract_local_bare_code ----- @pytest.mark.parametrize(- ("concept_ref", "domain", "expected"),- [- ("Doc", "my_domain", "Doc"),- ("my_domain.Doc", "my_domain", "Doc"),- ("external.Doc", "my_domain", None),- ("other_lib.Foo", "my_domain", None),- ("my_domain.nested.Thing", "my_domain", None),- ],- )- def test_extract_local_bare_code(self, concept_ref: str, domain: str, expected: str | None) -> None:- """Verify _extract_local_bare_code returns bare code for local refs and None for external."""- result = BuilderLoop._extract_local_bare_code(concept_ref_or_code=concept_ref, domain=domain) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]- assert result == expected-- # --- Tests for domain filtering ----- def test_prune_external_ref_does_not_keep_local(self) -> None:- """An external reference like 'external.Document' should not prevent local 'Document' from being pruned."""- builder_loop = BuilderLoop()-- bundle = _make_bundle_for_prune(- domain="my_domain",- main_pipe="main_sequence",- pipes={- "main_sequence": PipeSequenceSpec.model_construct(- pipe_code="main_sequence",- description="Main",- type="PipeSequence",- pipe_category="PipeController",- inputs={},- output="Text",- steps=[SubPipeSpec(pipe_code="generate_text", result="text_output")],- ),- "generate_text": PipeLLMSpec.model_construct(- pipe_code="generate_text",- description="Generate text",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={"doc": "external.Document"},- output="Text",- model="$retrieval",- prompt="Process @doc",- ),- },- concepts={- "Document": ConceptSpec(- the_concept_code="Document",- description="A local document concept that should be pruned",- refines="Text",- ),- },- )-- result = builder_loop._prune_unreachable_specs(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- # Document should be pruned because 'external.Document' is an external ref- assert result.concept is not None- assert "Document" not in result.concept-- def test_prune_keeps_same_domain_prefixed(self) -> None:- """A same-domain prefixed reference like 'my_domain.Report' should keep local 'Report'."""- builder_loop = BuilderLoop()-- bundle = _make_bundle_for_prune(- domain="my_domain",- main_pipe="generate_report",- pipes={- "generate_report": PipeLLMSpec.model_construct(- pipe_code="generate_report",- description="Generate report",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="my_domain.Report",- model="$retrieval",- prompt="Generate a report",- ),- },- concepts={- "Report": ConceptSpec(- the_concept_code="Report",- description="A report concept",- refines="Text",- ),- },- )-- result = builder_loop._prune_unreachable_specs(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- # Report should NOT be pruned because 'my_domain.Report' is a local ref- assert result.concept is not None- assert "Report" in result.concept-- def test_prune_keeps_unprefixed_local(self) -> None:- """An unprefixed reference like 'Summary' should keep local 'Summary'."""- builder_loop = BuilderLoop()-- bundle = _make_bundle_for_prune(- domain="my_domain",- main_pipe="generate_summary",- pipes={- "generate_summary": PipeLLMSpec.model_construct(- pipe_code="generate_summary",- description="Generate summary",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Summary",- model="$retrieval",- prompt="Generate a summary",- ),- },- concepts={- "Summary": ConceptSpec(- the_concept_code="Summary",- description="A summary concept",- refines="Text",- ),- },- )-- result = builder_loop._prune_unreachable_specs(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.concept is not None- assert "Summary" in result.concept-- def test_prune_transitive_external_ref(self) -> None:- """A concept refining an external ref should not keep the local concept with the same bare name."""- builder_loop = BuilderLoop()-- bundle = _make_bundle_for_prune(- domain="my_domain",- main_pipe="generate_result",- pipes={- "generate_result": PipeLLMSpec.model_construct(- pipe_code="generate_result",- description="Generate result",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Result",- model="$retrieval",- prompt="Generate a result",- ),- },- concepts={- "Result": ConceptSpec(- the_concept_code="Result",- description="A result concept",- refines="external.Info",- ),- "Info": ConceptSpec(- the_concept_code="Info",- description="A local info concept that should be pruned",- refines="Text",- ),- },- )-- result = builder_loop._prune_unreachable_specs(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.concept is not None- # Result should be kept (referenced by pipe output)- assert "Result" in result.concept- # Info should be pruned because 'external.Info' is external- assert "Info" not in result.concept-- def test_prune_transitive_local_ref(self) -> None:- """A concept refining a local concept should keep that concept."""- builder_loop = BuilderLoop()-- bundle = _make_bundle_for_prune(- domain="my_domain",- main_pipe="generate_derived",- pipes={- "generate_derived": PipeLLMSpec.model_construct(- pipe_code="generate_derived",- description="Generate derived",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Derived",- model="$retrieval",- prompt="Generate derived content",- ),- },- concepts={- "Derived": ConceptSpec(- the_concept_code="Derived",- description="A derived concept",- refines="Base",- ),- "Base": ConceptSpec(- the_concept_code="Base",- description="A base concept",- refines="Text",- ),- },- )-- result = builder_loop._prune_unreachable_specs(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.concept is not None- assert "Derived" in result.concept- assert "Base" in result.concept-- def test_prune_transitive_structure_external_ref(self) -> None:- """A concept with a structure field referencing an external concept should not keep the local bare name."""- builder_loop = BuilderLoop()-- bundle = _make_bundle_for_prune(- domain="my_domain",- main_pipe="generate_container",- pipes={- "generate_container": PipeLLMSpec.model_construct(- pipe_code="generate_container",- description="Generate container",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Container",- model="$retrieval",- prompt="Generate container",- ),- },- concepts={- "Container": ConceptSpec(- the_concept_code="Container",- description="A container",- structure={- "items": ConceptStructureSpec(- the_field_name="items",- description="Items list",- type=ConceptStructureSpecFieldType.LIST,- item_type="concept",- item_concept_ref="other_lib.Widget",- ),- },- ),- "Widget": ConceptSpec(- the_concept_code="Widget",- description="A local widget that should be pruned",- refines="Text",- ),- },- )-- result = builder_loop._prune_unreachable_specs(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert result.concept is not None- assert "Container" in result.concept- # Widget should be pruned because 'other_lib.Widget' is external- assert "Widget" not in result.concept-- # --- Tests for pipe lookup masking ----- def test_prune_warns_missing_pipe(self, caplog: pytest.LogCaptureFixture) -> None:- """A sequence referencing a non-existent pipe should log a warning and not crash."""- builder_loop = BuilderLoop()-- bundle = _make_bundle_for_prune(- domain="my_domain",- main_pipe="main_sequence",- pipes={- "main_sequence": PipeSequenceSpec.model_construct(- pipe_code="main_sequence",- description="Main",- type="PipeSequence",- pipe_category="PipeController",- inputs={},- output="Text",- steps=[- SubPipeSpec(pipe_code="existing_pipe", result="result"),- SubPipeSpec(pipe_code="missing_pipe", result="other_result"),- ],- ),- "existing_pipe": PipeLLMSpec.model_construct(- pipe_code="existing_pipe",- description="Existing pipe",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Generate text",- ),- },- concepts={},- )-- with caplog.at_level(logging.WARNING):- builder_loop._prune_unreachable_specs(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- assert any("missing_pipe" in record.message and "not found" in record.message for record in caplog.records)-- def test_prune_missing_pipe_not_in_reachable(self) -> None:- """A non-existent pipe referenced by a sequence should not be in reachable_pipes, allowing orphan pipes to be pruned."""- builder_loop = BuilderLoop()-- bundle = _make_bundle_for_prune(- domain="my_domain",- main_pipe="main_sequence",- pipes={- "main_sequence": PipeSequenceSpec.model_construct(- pipe_code="main_sequence",- description="Main",- type="PipeSequence",- pipe_category="PipeController",- inputs={},- output="Text",- steps=[SubPipeSpec(pipe_code="missing_pipe", result="result")],- ),- "orphan_pipe": PipeLLMSpec.model_construct(- pipe_code="orphan_pipe",- description="Orphan pipe",- type="PipeLLM",- pipe_category="PipeOperator",- inputs={},- output="Text",- model="$retrieval",- prompt="Orphan",- ),- },- concepts={},- )-- result = builder_loop._prune_unreachable_specs(pipelex_bundle_spec=bundle) # noqa: SLF001 # pyright: ignore[reportPrivateUsage]-- # orphan_pipe should be pruned since it's not reachable from main- assert result.pipe is not None- assert "orphan_pipe" not in result.pipe- # main_sequence should remain- assert "main_sequence" in result.pipediff --git a/tests/unit/pipelex/builder/test_builder_manifest_generation.py b/tests/unit/pipelex/builder/test_builder_manifest_generation.pydeleted file mode 100644index 387dc6428..000000000--- a/tests/unit/pipelex/builder/test_builder_manifest_generation.py+++ /dev/null@@ -1,69 +0,0 @@-import shutil-from pathlib import Path--from mthds.package.discovery import MANIFEST_FILENAME-from mthds.package.manifest.parser import parse_methods_toml--from pipelex.builder.builder_loop import maybe_generate_manifest_for_output--# Path to the physical test data-PACKAGES_DATA_DIR = Path(__file__).resolve().parent.parent.parent.parent / "data" / "packages"---class TestBuilderManifestGeneration:- """Tests for post-build METHODS.toml generation."""-- def test_multiple_domains_generates_manifest(self, tmp_path: Path) -> None:- """Output dir with multiple domains -> METHODS.toml generated."""- # Copy two .mthds files with different domains- shutil.copy(PACKAGES_DATA_DIR / "legal_tools" / "legal" / "contracts.mthds", tmp_path / "contracts.mthds")- shutil.copy(PACKAGES_DATA_DIR / "legal_tools" / "scoring" / "scoring.mthds", tmp_path / "scoring.mthds")-- result = maybe_generate_manifest_for_output(output_dir=tmp_path)-- assert result is not None- manifest_path = tmp_path / MANIFEST_FILENAME- assert manifest_path.exists()-- content = manifest_path.read_text(encoding="utf-8")- manifest = parse_methods_toml(content)- assert manifest.version == "0.1.0"- assert len(manifest.exports) >= 2-- # Check that main_pipe entries are exported- exported_pipes: list[str] = []- for domain_export in manifest.exports.values():- exported_pipes.extend(domain_export.pipes)- assert "pkg_test_extract_clause" in exported_pipes- assert "pkg_test_compute_weighted_score" in exported_pipes-- def test_single_domain_no_manifest(self, tmp_path: Path) -> None:- """Output dir with single domain -> no METHODS.toml generated."""- shutil.copy(PACKAGES_DATA_DIR / "minimal_package" / "core.mthds", tmp_path / "core.mthds")-- result = maybe_generate_manifest_for_output(output_dir=tmp_path)-- assert result is None- manifest_path = tmp_path / MANIFEST_FILENAME- assert not manifest_path.exists()-- def test_exported_pipes_include_main_pipe(self, tmp_path: Path) -> None:- """Exported pipes include main_pipe entries from each bundle."""- shutil.copy(PACKAGES_DATA_DIR / "legal_tools" / "legal" / "contracts.mthds", tmp_path / "contracts.mthds")- shutil.copy(PACKAGES_DATA_DIR / "legal_tools" / "scoring" / "scoring.mthds", tmp_path / "scoring.mthds")-- maybe_generate_manifest_for_output(output_dir=tmp_path)-- manifest_path = tmp_path / MANIFEST_FILENAME- content = manifest_path.read_text(encoding="utf-8")- manifest = parse_methods_toml(content)-- # Build a lookup of domain -> pipes- domain_pipes: dict[str, list[str]] = {}- for domain_path, domain_export in manifest.exports.items():- domain_pipes[domain_path] = domain_export.pipes-- # contracts.mthds has main_pipe = "pkg_test_extract_clause"- assert "pkg_test_extract_clause" in domain_pipes.get("pkg_test_legal.contracts", [])- # scoring.mthds has main_pipe = "pkg_test_compute_weighted_score"- assert "pkg_test_compute_weighted_score" in domain_pipes.get("pkg_test_scoring", [])diff --git a/tests/unit/pipelex/pipe_controllers/condition/test_pipe_condition_needed_inputs.py b/tests/unit/pipelex/pipe_controllers/condition/test_pipe_condition_needed_inputs.pyindex b0b4b1efe..dc10eaa74 100644--- a/tests/unit/pipelex/pipe_controllers/condition/test_pipe_condition_needed_inputs.py+++ b/tests/unit/pipelex/pipe_controllers/condition/test_pipe_condition_needed_inputs.py@@ -355,7 +355,7 @@ class TestPipeConditionOutputValidation:concept_library.teardown()- @pytest.mark.xfail(reason="Anything output is allowed until we enable the pipe builder to auto-fix")+ @pytest.mark.xfail(reason="Anything output is currently allowed")def test_validate_output_all_pipes_same_output_anything_not_allowed(self, load_empty_library: Callable[[], None]):"""Test that using Anything output when all mapped pipes have the same output raises an error."""load_empty_library()