Skip to content

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.

Support recursive design: additive multi-file MTHDS libraries (#970)

Louis Choquel4f999776cb63
diff --git a/.claude/skills/temporal-e2e-validate/references/mode-2-tiers.md b/.claude/skills/temporal-e2e-validate/references/mode-2-tiers.md
index aef712df1..0b119a1b6 100644
--- a/.claude/skills/temporal-e2e-validate/references/mode-2-tiers.md
+++ b/.claude/skills/temporal-e2e-validate/references/mode-2-tiers.md
@@ -213,7 +213,7 @@ exit 0 with distinct `graph_id`s / status maps — no shared or merged trace eve
RED (prove it bites) — the fix is committed, so neutralize it in the working tree. Either arm:
-- **Drop the content-generator scope:** in `pipelex/pipe_run/dry_run_pipeline.py`
+- **Drop the content-generator scope:** in `pipelex/pipe_run/dry_run_in_process.py`
(`dry_run_pipe_in_process`), remove `scoped_content_generator(content_generator)` from the
`with` line. The DRY mock lives at the cogt leaf, so the leaf resolves the hub
`ContentGeneratorInWorkflow` and dies with `_NotInWorkflowEventLoopError` / the strong check shows
@@ -228,7 +228,7 @@ RED (prove it bites) — the fix is committed, so neutralize it in the working t
same regression is the Mode-1 companion `test_dry_run_graph_in_process.py` (it calls
`dry_run_pipe_in_process` directly and asserts a non-empty graph).
-**Restore immediately:** `git checkout -- pipelex/pipe_run/dry_run_pipeline.py`.
+**Restore immediately:** `git checkout -- pipelex/pipe_run/dry_run_in_process.py`.
**API arm (after Phase 4 — the real `/validate` route in `../pipelex-api`).** With the server +
split workers up, exercise the actual route code performing the real dispatch (the sibling repo's
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 260611da4..8be2ce23c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,8 +8,29 @@
- **Unit tests for inference plumbing, core runtime, and tools/config internals.** Offline coverage for the layers around inference and execution that can break independently of any provider: the structured-output ↔ instructor mode mapping, backend-credentials error messages, model-deck reference checks (presets/aliases/waterfalls/handles with fuzzy suggestions), the per-provider image-gen argument factory (Flux/Qwen/SDXL/GPT-image taxonomies), the LLM and image-gen worker routing factories (SDK dispatch, client caching, missing-dependency errors), gateway completions request-shaping and extract-output parsing (Azure/Mistral/Deepseek/Linkup), and the Mistral factory (messages, OCR extract output, document prep/upload). Core runtime: the local observer JSONL sink, the output renderer's Anything-concept resolution, the bundle-level graph rendering dispatch, the builder bundle-spec validation/`to_blueprint()`/pretty rendering and inputs operations, and the pipeline runner's error paths and MTHDS protocol surfaces (`validate`/`models`/`version`). Tools: the TOML config-sync engine (structure/comment preservation, dry-run, idempotency), document/image format enums, PIL image conversion, and the storage config validators.
- **Unit tests for the Temporal deploy-critical entry points.** Offline coverage for the operational surfaces that previously only failed inside a live cluster: the worker CLI (project resolution from pyproject, fast-fail task-queue validation before library load, worker-base library loading, forced `temporal.is_enabled`, full Typer arg wiring into the worker loop), the codec HTTP server for the Temporal Web UI (encode/decode round-trip over real HTTP, CORS preflight and origin gating, content-type/malformed-payload guards, storage-failure → HTTP status mapping), and the server connection logic (API-key resolution per secret method, TLS/RPC-metadata wiring, payload-codec converter selection, named server-config selection, SDK error wrapping).
+### Changed
+
+- **Canonical protocol validation report (breaking).** `PipelexValidationReport` is reworked into the canonical typed shape shared by every Pipelex backend and moved to `pipelex/pipeline/validation_report.py`: `bundle_blueprint` (the batch's primary blueprint — first declaring `main_pipe`, else first; replaces the untyped single-or-list `blueprint` dump), `pipe_io_contracts` keyed by namespaced `pipe_ref` with typed `PipeIOContract` entries (per-pipe input JSON Schemas + output concept/multiplicity — new module `pipelex/pipeline/pipe_io_contracts.py`, ported from the hosted API's route-local builder), `validated_pipes` (per-pipe sweep outcomes, the same entries as the agent-CLI envelope), plus the existing `pending_signatures` / `is_runnable` verdict. The report is assembled in exactly one place — `build_validation_report` — that every backend calls, and primary-blueprint selection is one shared rule (`select_primary_blueprint` in `pipelex/pipeline/blueprint_selection.py`, also folded into the Temporal validate activity).
+- **`validated_pipes` entry key `pipe_code` → `pipe_ref` (breaking).** The entry has always carried the namespaced `pipe_ref` (`domain.code`) under a key named for the wrong identity; the key now says what the value is. Applies to the agent-CLI / builder validate envelopes and the protocol report.
+- **Protocol `validate` now produces a best-effort `graph_spec` — the local runtime catches up with the hosted route.** When the validated batch declares a `main_pipe`, `PipelexMTHDSProtocol.validate` dry-runs it in-process via `dry_run_pipe_in_process` against the still-open validation library and ships the resulting `GraphSpec` on the report — the same single-library-load pattern and best-effort degrade contract as the Temporal validate activity, enforced by ONE shared implementation (`best_effort_graph_spec`) both backends call: a graph-arm domain failure (`PipelexError`, pydantic `ValidationError`, polyfactory `FactoryException`) yields `graph_spec=None` with validation still successful; no declared `main_pipe` means no graph. To make that wiring importable, `dry_run_pipe_in_process` moved to its own module `pipelex/pipe_run/dry_run_in_process.py`: its old home `dry_run_pipeline.py` imports the protocol runner, so sharing a module would have been an import cycle.
+- **The Temporal validate activity result carries the full worker-side artifact set.** `DryValidateResult` gains `pending_signatures` (the runnability verdict crosses the boundary at last) and `pipe_io_contracts` (typed `PipeIOContract` entries computed activity-side against the worker's loaded library — the API side never needs to re-acquire a library to render schemas). Both fields are required on the wire: a version-skewed worker that doesn't emit them fails loudly at deserialization instead of defaulting to a silently wrong runnability verdict. Breaking for the wire model; Temporal validate has never shipped to prod.
+- **`MTHDS_PROTOCOL_VERSION` is deleted (breaking).** The hardcoded duplicate of the protocol version is gone from `pipelex/pipeline/runner.py`; the SDK's `PROTOCOL_VERSION` (`mthds.protocol.protocol`) is the single source of truth and consumers (including the hosted API) import it directly.
+- **Additive multi-file library construction.** Merge-time rules now support building a same-domain `.mthds` library as separate, additive files (forward-declared headers + separate definitions), enabling parallel top-down method construction:
+ - A `PipeSignature` and a concrete pipe with the same code reconcile — the concrete pipe satisfies the signature instead of raising a duplicate-code error. `PipeSignature` works like a forward declaration ("header"), its concrete pipe like the definition; their `inputs`/`output` contracts must match. Contracts are compared by *normalized concept identity*, so a header's bare `Brief` reconciles with a definition's domain-qualified `thisdomain.Brief` (and native `Text` with `native.Text`); multiplicity is compared structurally. Two concrete pipes with the same code, or two declarations with genuinely different contracts, remain errors.
+ - Concept references resolve against the merged library instead of per file, so a concept declared once can be referenced by bare code from sibling files of the same domain — whether those files are loaded in the same directory batch or across separate load batches (e.g. a concept declared in a `-L` library directory referenced from a separately-loaded bundle). A concept declared twice remains a `ConceptLibraryError`, and a reference resolvable nowhere now surfaces as a structured validation error instead of a raw traceback.
+ - Domain `description` / `system_prompt` now merge order-independently across same-domain files: a membership-only file that omits them defers to whichever file declares them, instead of warning and racing on filesystem load order. The root's header therefore always wins over siblings that carry only `domain = "..."`. Two files declaring *different* non-empty values still keep the first and warn — a genuine double-declaration to resolve.
+ - **`pending_signatures` + `is_runnable` on the validate result.** A successful `validate bundle` (notably a lenient `--allow-signatures` run) now reports the library-wide set of pipes still declared as `PipeSignature` — the unimplemented headers left to satisfy. Surfaced as a `pending_signatures` array plus an `is_runnable` boolean on the agent-CLI / builder validate JSON envelope, and in markdown as an explicit runnability verdict: a complete bundle states it is runnable, while a bundle with pending signatures states it is not yet runnable immediately above the verbatim "Pending signatures" section — so a top-down build (and the LLM driving it) can see exactly what remains without inferring completeness from an absent section. The protocol-level `validate` (`PipelexMTHDSProtocol`) reports the same verdict: `pending_signatures` + `is_runnable` are now Pipelex extension fields on `PipelexValidationReport`, so a build driving the runtime through the MTHDS Protocol sees it too. (The hosted runner's `/validate` builds its own response envelope and needs its own change to surface the verdict — it does not inherit these fields.)
+- **`PipeSignature` evicted from the executable pipe taxonomy.** A signature is a contract, not a way of running, so it is no longer a `PipeType` / `PipeCategory` member: `PipeType.PIPE_SIGNATURE` and `PipeCategory.PIPE_SIGNATURE` are **removed** (breaking — any code matching on `PipeCategory.PIPE_SIGNATURE` must drop that arm). It stays a `PipeAbstract` subclass (the dry-run-only shim): a signature now carries `type = "PipeSignature"` with `pipe_category = None`, and `is_signature` is a class fact (base `False`, overridden to `True` on `PipeSignature` / `PipeSignatureBlueprint`) rather than an enum read. `signature_for` is retained for tooling; setting `signature_for = "PipeSignature"` is still rejected, now structurally (it is not a valid `PipeType`) rather than by a dedicated validator.
+
### Fixed
+- **The protocol model deck no longer loses aliases to cross-category collisions.** `PipelexModelDeck.aliases`/`waterfalls` were flat maps built by `update()`-ing the per-category maps together — the same alias name in several categories (e.g. `default-small` for both llm and extract) silently kept only the last category's entry, dropping aliases from the unfiltered deck. Both extensions are now keyed by model category (`aliases: {category: {alias: model}}`), preserving every entry; the protocol's flat `models` list is unchanged (each entry already carries its category as `type`). Breaking for the deck's extension shape.
+- **JSON-Schema rendering failures on the validate surfaces are now structured errors.** A pydantic schema-generation failure while building `pipe_io_contracts` (an unschematizable structure-class field) surfaced as a raw third-party exception — which the Temporal error boundary would not convert, so Temporal retried a deterministic failure and the caller got an opaque infra error instead of a validation-shaped one. `build_pipe_io_contracts` now converts it to the new `PipeIOContractError` (with the offending pipe/input/concept named), non-retryable at the validate workflow tier like `ValidateBundleError`.
+- **Protocol `validate`'s library teardown can no longer mask the real error.** If the body failed mid-window and the validation library's teardown then also raised, the teardown error replaced the in-flight one — the caller's failure named teardown instead of the actual problem. The wrapper now suppresses a teardown raise while a body error is propagating (and still raises it when the body succeeded), and captures the validation library id once — right after `validate_bundle` leaves it current — so the graph arm and the teardown always target the same library. Mirrors the Temporal validate activity's existing guards.
+- **Empty `mthds_contents` rejected with a structured error.** `validate_bundle` (and therefore protocol `validate`) accepted an empty `mthds_contents` list — it slipped past the provided-params check and crashed the canonical report's primary-blueprint selection with a raw `IndexError`. It now raises a `ValidateBundleError` at entry, and `select_primary_blueprint` itself guards the empty batch with the same structured error. The main-pipe selection rule is also now genuinely single-implementation: the hand-rolled first-declaring-`main_pipe` loops in `execution_seams`, `dry_run_pipeline`, and `inputs_ops` were folded into `select_primary_blueprint`.
+- **Additive multi-file libraries: qualified same-domain pipe references resolve across files.** A controller could reference a pipe in its own domain by qualified name (e.g. `research.find_key_findings`) only when that pipe was declared in the *same* file — the bare form already resolved across sibling files. Qualified same-domain references are now deferred to the merged library like bare ones, so a header file can reference a pipe whose concrete definition lives in a sibling file. A reference that no file in the merged library declares is still rejected at load.
+- **Concepts-only loading validates concept references.** Loading a bundle with concepts only (the `pipelex structures` path / `load_concepts_only`) skipped the cross-file concept-reference check that the full load runs, so a structure field pointing at an undeclared concept (`concept_ref` / `item_concept_ref`) was silently accepted, leaving an invalid schema in the library. It is now validated on the concepts-only path too, matching the full load. The concepts-only library-directory loader batches all sibling files into one validation pass (like the directory loader already did), so a structure field referencing a concept declared in a sibling resolves regardless of file load order.
+- **Multi-file dependency packages reconcile signatures with their definitions.** A dependency package split across files — a `PipeSignature` header plus its concrete sibling — collided on the duplicate pipe code and silently dropped one declaration (which one depended on load order). Dependencies now go through the same additive merge as the main library: the signature and its concrete reconcile to the concrete, same-domain concept references are validated, and a genuine duplicate definition raises instead of being swallowed as a warning.
- **OpenAI image moderation mapping was inverted.** `is_moderated = true` sent OpenAI's gpt-image `moderation="low"` (the LESS restrictive setting) and `false` sent `"auto"` (standard filtering) — the exact opposite of the documented "enable content moderation" intent. The mapping now matches the flag: enabled → `"auto"`, disabled → `"low"`. Alongside the mapping fix, `ImgGenSetting.is_moderated` now defaults to `None` ("no explicit choice") instead of `False`: workers omit the moderation/safety-checker parameter so the provider's own default applies (OpenAI's documented default is `auto`). Without this, model-deck alias/handle resolution — which builds settings without the field — would have started sending the less restrictive `low` by default once the mapping was corrected. For FAL models this also means `enable_safety_checker` is no longer explicitly disabled by default; the provider default applies there too.
- **Storage config validation now covers every provider and requires a real `{hash}` replacement field in `uri_format`.** GCP's `lazy_validate` accepted any uri_format containing the bare substring `hash` (e.g. `assets/myhash/file`), which has no substitution slot and would render the same URI for every stored object — silent storage-wide overwrites; the local and in-memory configs had no validation at all, leaving the same misconfiguration uncaught. The check parses the format string: every placeholder must be a plain `{name}` (escaped `{{hash}}`, format specs like `{hash:.0}` or `{primary_id:.0}`, conversions, and attribute/index access are all rejected — on any field they render constant, colliding, or oversized keys, so the rule is enforced uniformly rather than only on `{hash}`), placeholders outside the supported set (`{primary_id}`, `{secondary_id}`, `{hash}`, `{extension}`) are rejected at config time instead of crashing with `KeyError` at content-store time, a `{hash}` placeholder is required, a test rendering catches anything parsing can't, and bucket configs must set a positive `signed_urls_lifespan_seconds` (or `"disabled"`) so signed URLs can't be born dead. Operator note: this validation runs when the storage provider is constructed at Pipelex boot — a misconfigured `uri_format` (including for the default local method) now fails fast at startup rather than at the first content store. The per-provider checks and the operator-facing error message now live on a shared config base (so the providers can no longer drift apart), the storage provider factory validates local/in-memory configs the same way it already did S3/GCP, and `StorageProviderConfig.storage_path` dispatches on the configured method instead of blaming a missing local config when the method is S3/GCP.
- **Mistral chat requests now send the system message before the user message.** `MistralFactory.make_simple_messages` appended the system message after the user message, contradicting its own docstring and the OpenAI-typed sibling method.
@@ -53,7 +74,7 @@
### Added
-- **Protocol `validate` / `models` / `version` on `PipelexMTHDSProtocol`** — `validate` wraps `validate_bundle` (blueprints + per-pipe structures into the protocol `ValidationReport`); `models` wraps the builder's `list_models` into a `ModelDeck`; `version` reports `protocol_version` 0.1.0 with the installed pipelex version.
+- **Protocol `validate` / `models` / `version` on `PipelexMTHDSProtocol`** — `validate` wraps `validate_bundle` (blueprints + per-pipe structures into the protocol `ValidationReport`); `models` wraps the builder's `list_models` into a `ModelDeck`; `version` reports `protocol_version` 0.6.0 with the installed pipelex version.
- **Temporal test hang diagnostics (CI).** Setting `PIPELEX_HANG_DUMP_DIR` arms a per-test watchdog in the temporal integration suite that dumps every thread's stack to a file before pytest-timeout's thread-method kill destroys the process, and mirrors temporalio's failure logs (which carry the workflow-task traceback) to the same directory. The tests workflow prints these dumps when a job fails — pytest-xdist swallows worker stderr on a crash, so this is the only post-mortem signal for a hung test on a remote runner.
diff --git a/TODOS.md b/TODOS.md
index ee01eb54d..606fbf36d 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,50 +1,180 @@
-# Reviewer's guide — `feature/Add-tests`
+# PR guide — additive multi-file MTHDS libraries (recursive design) + canonical MTHDS-protocol validate surface
-This branch is a test-coverage grind over the offline-testable layers of pipelex, plus the source bugs that writing those tests surfaced. The diff is almost entirely new unit tests; the source changes are a small, deliberate set of bug fixes, each pinned by a test in the same branch. Overall coverage went from ~72% to ~78% (per-module before/after numbers live in [wip/tests/missing-tests-menu.md](wip/tests/missing-tests-menu.md)).
+> **For reviewers.** This branch (`feature/Support-recursive-design`) carries two related bodies of work, in landing order:
+>
+> 1. **Additive multi-file libraries** (Part I below): a same-domain `.mthds` library becomes buildable as **separate, additive files** instead of one monolithic file. That unblocks **parallel, top-down method construction**: a header file forward-declares the pipes (and the concepts they need), and definition files fill them in independently — no in-place overwrites, no transient collisions.
+> 2. **Canonical MTHDS-protocol validate surface** (Part II below): the runnability verdict from Part I is promoted onto the protocol level, and `PipelexMTHDSProtocol.validate`/`models` are reworked to produce ONE canonical, typed artifact shape that the hosted API (`pipelex-api`) and the Temporal worker arm reuse instead of re-implementing. Spec: workspace `docs/specs/pipelex-mthds-protocol.md`; plan + decision register: workspace `wip/mthds-protocol-surface-alignment.md` (decisions D1–D14).
+>
+> This document describes *what changed and why* so the diff can be reviewed against intent.
-## How to review this PR
+---
-Start with the source changes (next section) — they are the only behavior changes. Then sample the test modules with the conventions section in mind: several patterns that look unusual are deliberate and documented below, so check there before flagging.
+# Part I — additive multi-file MTHDS libraries
-## Source changes (the behavior diff)
+## What "additive" means
-Every fix below was found by writing a pinning test first, judging the pinned behavior wrong in a review pass, then fixing source and flipping the test. The investigation record is [wip/tests/deferred-source-bugs-pinned-by-tests.md](wip/tests/deferred-source-bugs-pinned-by-tests.md); user-facing wording is in `CHANGELOG.md` under `[Unreleased]`.
+A library author can split a domain across files:
-- `pipelex/plugins/openai/openai_img_gen_factory.py` + `pipelex/cogt/img_gen/img_gen_setting.py` — the image-moderation mapping was inverted: `is_moderated=true` sent OpenAI's *less* restrictive `"low"` and `false` sent `"auto"`. Now enabled → `"auto"`, disabled → `"low"`. To keep the corrected mapping from silently downgrading default runs (deck alias/handle resolution builds settings without the field, and the old `False` default would have started sending `"low"`), `ImgGenSetting.is_moderated` now defaults to `None` — workers omit the parameter and the provider default applies.
-- `pipelex/tools/storage/storage_config.py` + `storage_provider_factory.py` — the biggest source diff. GCP's `lazy_validate` accepted any `uri_format` containing the bare substring `hash` (no substitution slot → every object renders the same URI → silent storage-wide overwrites), and the local/in-memory configs had no validation at all. The per-provider checks and error-message assembly now live on a shared `StorageMethodConfig` base that parses the format string: every placeholder must be a plain `{name}` (a format spec, conversion, or attribute/index access is rejected on *any* supported field, not just `{hash}` — `{primary_id:.0}` truncates to a colliding key and `{primary_id:1000000000}` would balloon the test render, same hazard class as `{hash:.0}`), a `{hash}` placeholder is required, unknown placeholders are rejected against the supported set, a test rendering as backstop, positive signed-URL lifespans on bucket configs; the factory validates every method; `storage_path` dispatches on the configured method instead of blaming a missing local config.
-- `pipelex/builder/bundle_spec.py` + `pipelex/builder/concept/concept_spec.py` + `pipelex/core/concepts/concept_blueprint.py` — string concept values in bundle specs were unconstructible (a `mode="before"` validator assumed dict input and crashed on the `ConceptSpec | str` union) and `to_blueprint()` mapped the string into `structure`, where the loader rejects anything that isn't a registered structure class. Both before-validators (`ConceptSpec` and `ConceptBlueprint`) now fall through untouched on non-dict input, and the string passes through as the concept's description (matching `ConceptFactory.make_from_blueprint`, which treats a bare string as `ConceptDeclarationType.STRING`).
-- `pipelex/plugins/mistral/mistral_factory.py` — `make_simple_messages` appended the system message *after* the user message, contradicting its own docstring and the OpenAI-typed sibling. System now comes first.
-- `pipelex/observer/local_observer.py` — a payload carrying its own `event_type` key silently overwrote the lifecycle event name in the JSONL record; merge order flipped so the event name wins.
-- `pipelex/temporal/worker_cli.py` — startup log said `Starting worker for current project 'None'` when no project was given; it now omits the name.
-- `pipelex/core/pipes/output/output_renderer.py` — a `PipeCondition`'s possible outputs were collected by iterating a dependency *set*, so the user-facing `output_option_N` numbering was nondeterministic with two or more mapped pipes; now sorted by pipe code.
-- `pyproject.toml` — **pytest's default `norecursedirs` includes `build`**, so everything under `tests/unit/pipelex/cli/commands/build/` (mirroring the source layout) was silently never collected — including a pre-existing regression test. The config now overrides `norecursedirs` to the defaults minus `build`, plus `testpaths = ["tests"]` so bare runs never scan outside the test tree. This is load-bearing for the whole branch: without it a chunk of the new tests wouldn't run in CI.
+- a **root / header** file declares the domain header and forward-declares pipes as `PipeSignature` (a "header" with explicit `inputs`/`output` but no body), plus the concepts those contracts reference;
+- **definition** files supply the concrete pipes (and may declare more concepts), referencing sibling concepts by bare code.
-## Test layout
+Loading the whole set must produce the same library no matter the file order, with no spurious duplicate/undeclared errors. Three merge-time rules + one validate-surface addition make that work.
-Tests mirror the source tree under `tests/unit/pipelex/`. The grind covered five areas:
+---
-- **CLI internals** — `tests/unit/pipelex/cli/` and `tests/unit/pipelex/cli/commands/build/`: doctor checks, run core + wrapper, build codegen cores, readiness gate, show/which, error handlers.
-- **Temporal entry points** — `tests/unit/pipelex/temporal/`: worker CLI, codec HTTP server (driven over real HTTP via `aiohttp.test_utils`), server connection logic. These are deploy-critical surfaces whose bugs previously only showed inside a live cluster.
-- **Inference plumbing** — `tests/unit/pipelex/cogt/{llm,img_gen,models,model_backends}/` and `tests/unit/pipelex/plugins/{gateway,mistral}/`: structured-output mode mapping, credentials messages, model-deck reference checks, the per-provider img-gen args factory, both worker-routing factories, gateway request shaping + extract-output parsing, the Mistral factory. None of these tests touch a provider.
-- **Core runtime** — `tests/unit/pipelex/{observer,core/pipes/output,graph,builder,pipeline}/`: local observer JSONL sink, output renderer Anything-resolution, bundle-level graph dispatch, bundle-spec validation/`to_blueprint()`/pretty rendering, inputs ops, pipeline runner error paths and MTHDS protocol surfaces.
-- **Tools/config** — `tests/unit/pipelex/tools/{misc,storage}/`: the TOML config-sync engine (rewrites user config in place — tests pin the destroy-config guards: never creates keys, preserves comments/structure, dry-run is byte-identical, idempotent), format enums, PIL conversion, storage config validators.
+## The four changes
-## Conventions the tests follow (read before flagging)
+### 1. Pipe signature ↔ concrete reconciliation
-- **One test class per module** (house pytest standard) — that's why e.g. doctor coverage is split across several `test_doctor_*.py` files. pytest-mock (`MockerFixture`) only, never `unittest.mock` imports; strong value asserts; parametrization over copy-paste.
-- **The CLI *interface* is deliberately untested here.** Arg parsing, `--help`, Typer wrappers, agent JSON shapes are owned by the sibling `conformance` repo's spec suite. This branch tests the `do_*`/`_core` functions beneath them. Low coverage remaining on `*_cmd.py` wrapper lines is by design.
-- **Module-namespace patching, source-module patching for call-time imports.** Collaborators imported at a module's top are patched at the consuming module's namespace; classes imported *inside* functions (the deferred-import pattern in worker factories) are patched at their source module. Worker-factory tests use a fresh real `PluginSdkRegistry()` per test so the booted singleton is never mutated.
-- **Real collaborators where cheap, mocks where not:** real TOML files in `tmp_path`, real PIL images, real pydantic SDK models (Mistral OCR, Portkey `GenericResponse`), a real aiohttp server for the codec; AsyncMocks for inference/network/Temporal SDK boundaries.
-- **Recorded Rich consoles** (`Console(record=True, color_system=None)` + `export_text()`) for output-rendering asserts.
-- **Remaining uncovered lines are deliberate:** `TYPE_CHECKING` blocks, interface-layer wrappers (conformance-owned), lines already pinned by the integration suite (e.g. pipeline runner happy path), and live-call worker paths.
+When two declarations of the same `pipe_ref` collide in the library merge:
-## Known deferred items (not in this PR)
+| existing → incoming | result |
+| --- | --- |
+| concrete + concrete | **error** — genuine duplicate (unchanged) |
+| signature + concrete | **concrete wins** (definition satisfies the header) |
+| concrete + signature | **concrete wins** (header ignored) |
+| signature + signature | keep one via a deterministic, load-order-independent tie-break |
-[wip/tests/deferred-source-bugs-pinned-by-tests.md](wip/tests/deferred-source-bugs-pinned-by-tests.md) keeps two intentionally-deferred lists: a design tradeoff (LocalObserver's flat record namespace — nesting the payload is a breaking JSONL-shape change to decide deliberately) and test-quality cleanups (a Pipelex-boot opt-out conftest for pure test dirs, hoisting a few duplicated test scaffolds, minor in-file dedup). Don't treat their absence as gaps.
+Whenever at least one side is a signature, the two contracts **must agree**. Agreement is **normalized concept identity**, not raw-string equality: a header's bare `Brief` and a definition's `thisdomain.Brief` denote the same concept, as do `Text` and `native.Text`; structural multiplicity (`[]` vs `[1]`) stays distinct. Mismatched contracts are an error. Input *names* must match exactly (they are variable names, not concepts).
-## Verifying locally
+Conceptually this is **a contract fulfilled by an implementation**, not a swap between two pipe *types*: after the taxonomy eviction (below), `PipeSignature` is not a `PipeType`, so reconciliation keys off `blueprint.is_signature` (a class fact) — never an enum tag. `contracts_match()` is unchanged.
-```bash
-make agent-check # lint + typecheck gate
-make agent-test # full offline suite (the new build/ dirs collect thanks to the norecursedirs fix)
-```
+- `pipelex/libraries/library_crate_factory.py` — `_reconcile_pipe_collision` + the merge loop. Operates on a small `PipeDeclaration` (blueprint + source) record.
+- `pipelex/libraries/contract_match.py` — **NEW.** `contracts_match()` + `_canonical_concept_spec()`: normalization-for-identity only (NOT refinement substitutability — that stays the dry-run's job).
+- `pipelex/libraries/collision_messages.py` — **NEW.** `duplicate_ref_msg()`: shared same-file vs cross-file message for duplicate concept/pipe.
+
+### 2. Cross-file concept resolution
+
+Concept references resolve against the **merged library** instead of per file, so a concept declared once is referenceable by bare code from sibling files of the same domain — within one load batch **or across separate batches** (e.g. a concept loaded via a `-L` directory, then a root file referencing it loaded separately). A concept declared twice still raises `ConceptLibraryError`.
+
+The old per-file gate (`validate_local_concept_references` in `PipelexBundleBlueprint`) could not tell a typo from a valid cross-file ref, so it was removed; the check is reproduced where all declarations *and* the live library are visible — the loader.
+
+- `pipelex/core/bundles/pipelex_bundle_blueprint.py` — removed the per-file same-domain concept gate (and the symmetric per-file *pipe* gate, which was the existing asymmetry — bare pipe refs were already deferred to library-level resolution). Reference **collectors** stay; `collect_concept_references()` is now public, mirroring `collect_pipe_references()`.
+- `pipelex/libraries/concept_reference_validation.py` — **NEW.** Pure `validate_concept_references_in_blueprints(blueprints, already_loaded_concept_refs=None)`: membership against `batch ∪ already-loaded ∪ native`; the error message lists only the batch's own declarations; every unresolved ref is accumulated and reported together.
+- `pipelex/libraries/library_manager.py` — calls the validator from `load_from_blueprints` *and* `load_concepts_only_from_blueprints` (batch ∪ live-library concepts). `load_from_crate` derives its pipe-factory bare-concept guard (`domain_concept_codes`) from the **live library**, not just the crate — the pipe-factory counterpart to the cross-batch check, so bare cross-batch refs resolve end-to-end (relaxing-only; no-op for self-contained crates incl. the Temporal path). Dependency loading now routes multi-file packages through `LibraryCrateFactory.make_from_blueprints`, so a dependency package can itself be additive (signature + concrete).
+
+### 3. Order-independent domain-metadata merge
+
+Domain `description` / `system_prompt` merge order-independently across same-domain files. A membership-only sibling that declares only `domain = "..."` omits these — an omission contributes **no opinion** (it neither overrides nor warns), so whichever file declares the value wins regardless of filesystem load order. Two files declaring *different* non-empty values keep the first and **warn** (a real double-declaration). Same value → no warning.
+
+- `pipelex/libraries/domain/domain_metadata_merge.py` — **NEW.** `merge_domain_metadata_field()`, the single shared rule.
+- `pipelex/libraries/library_crate_factory.py` and `pipelex/libraries/domain/domain_library.py` — both wired to the shared helper (crate-merge path + runtime `DomainLibrary.add_domains`).
+
+### 4. `pending_signatures` on a successful validate
+
+A successful `validate bundle` (notably `--allow-signatures`) reports the library-wide set of pipes still declared as `PipeSignature` — so a top-down build sees exactly what remains to define.
+
+- `pipelex/pipeline/validate_bundle.py` — `build_pending_signatures()` + a `pending_signatures` field on the result.
+- `pipelex/builder/operations/validate_ops.py`, `pipelex/cli/agent_cli/commands/validate/_validate_core.py` — `pending_signatures` in the JSON envelope.
+- `pipelex/cli/agent_cli/commands/validate/_output_helpers.py` — a "Pending signatures" markdown section.
+
+---
+
+## Error surfacing
+
+`ConceptLibraryError` / `PipeLibraryError` were reparented from `PipelexError` directly to `LibraryError`, so a single `except LibraryError` arm in `_translate_to_validate_bundle_error` turns an unresolved cross-file ref (and the pre-existing raw duplicate-concept/pipe errors) into a clean structured `ValidateBundleError` instead of a raw traceback. `PipeNotFoundError` (also a `PipeLibraryError`) keeps its dedicated `--pipe`-slice handler via an `except PipeNotFoundError: raise` placed *before* the `LibraryError` arm. `_load_mthds_files_into_library` gained a surgical `(ConceptLibraryError, PipeLibraryError)` file-context arm (kept narrow so `LibraryLoadingError`'s structured fields survive).
+
+- `pipelex/libraries/concept/exceptions.py`, `pipelex/libraries/pipe/exceptions.py` — reparenting (class names / `type_uri` / doc slugs unchanged).
+- `pipelex/pipeline/validate_bundle.py` — the translate arms.
+
+---
+
+## Part I test coverage (what proves it)
+
+- `tests/unit/pipelex/libraries/test_library_crate.py` (+ `test_library_crate_data.py`) — signature/concrete reconciliation matrix (both orders, signature+signature match/mismatch, contract mismatch).
+- `tests/unit/pipelex/libraries/test_concept_reference_validation.py` — the pure validator, incl. the cross-batch (`already_loaded_concept_refs`) case and message format.
+- `tests/unit/pipelex/libraries/test_domain_library.py` — domain-metadata merge matrix (both orders, same-value, conflict; `description` + `system_prompt`; warnings asserted via `caplog`).
+- `tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py` — additive (signature + concrete) **dependency** packages.
+- `tests/unit/pipelex/cli/agent_cli/test_validate_output_helpers.py` — the "Pending signatures" markdown section.
+- `tests/unit/pipelex/core/.../test_pipelex_bundle_blueprint_concept_construction.py` — per-file construction smoke tests (replaces the relocated per-file validation tests).
+- `tests/integration/pipelex/libraries/test_additive_multi_file_library.py` — end-to-end `validate bundle <root> -L <dir>`: lenient passes with the signature, strict passes once the definition is present, concrete wins, cross-batch via `-L`, undeclared → clean `ValidateBundleError`.
+- `tests/integration/pipelex/libraries/test_cross_file_concept_references.py` — cross-batch + single-batch bare-ref resolve; undeclared → `ConceptLibraryError`.
+- `tests/integration/pipelex/pipeline/test_load_concepts_only.py` — concepts-only path incl. dangling `concept_ref`/`item_concept_ref` rejection and the **sibling cross-reference order-independence** regression test.
+
+Verification: `make agent-check` clean (ruff, plxt, pyright 0 errors, mypy success); `make agent-test` full suite green.
+
+---
+
+## Key design decisions
+
+- **Normalized identity at merge, substitutability at dry-run.** The merge runs at blueprint level (raw strings, before concepts resolve), so `contracts_match` normalizes *identity* (bare ≡ qualified, native spelling, multiplicity-as-text). Covariant-output / contravariant-input substitutability is deferred to the dry-run, which re-validates the parent against the concrete's real contract.
+- **Concept refs validate at the loader, not per file.** The one place holding both the raw blueprints (for messages + sources) and the live library (for already-loaded concepts). This makes `get_crate` and per-batch `load_from_blueprints` agree by construction.
+- **Reparent then catch once.** One `except LibraryError` arm covers the new undeclared-ref error and the pre-existing raw duplicate errors uniformly, rather than scattering catches.
+- **Per-file relaxation scope: concepts (and the already-deferred bare pipe refs).** Same-domain *qualified* cross-file refs are still not emitted by the recursive flow; not in scope.
+- **Exact-match contract requires explicit `inputs`/`output` on both header and definition.** `PipeLLM` does not infer `inputs` from prompt sigils, so a header with explicit `inputs` and a definition that omits them would mismatch — the additive flow must emit both explicitly (pinned by a test).
+
+See `wip/recursivity/` for the deeper records:
+
+- [`recursive-followups.md`](wip/recursivity/recursive-followups.md) — `pending_signatures` + normalized contract conformance (both shipped).
+- [`domain-metadata-merge.md`](wip/recursivity/domain-metadata-merge.md) — the metadata-merge rule (shipped).
+
+---
+
+## Deferred (intentionally out of scope)
+
+- **Partial-hierarchical same-domain typo skipped as external.** A ref like `legal.Foo` when the bundle domain is `legal.contracts` is treated as external (`QualifiedRef.is_external_to` uses exact-equality) and skipped, so the typo only fails later at resolution. Pre-existing — identical in the old per-file validator; fixing needs an ancestor/prefix notion of domain. Tracked in `wip/recursivity/`.
+- **P3 polish from the pre-landing `/review`** (docstring accuracy, an advisory-description silent-drop note, one low-confidence test-coverage gap) — none are bugs; recorded in [`review-followups.md`](wip/recursivity/review-followups.md).
+
+---
+
+---
+
+# Part II — canonical MTHDS-protocol validate surface
+
+The MTHDS Protocol (five routes: `execute`/`start`/`validate`/`models`/`version`) had **diverged between the local implementation and the hosted API**: same protocol operation, unrelated artifact shapes (the hosted `/validate` never called `PipelexMTHDSProtocol.validate` at all). This part makes pipelex the single owner of the canonical artifact shapes; the hosted `pipelex-api` rewires its routes through them in a companion branch (`pipelex-api@feature/Recursivity-and-protocols`). Principle: **backend overrides change backend, never shape; routes are thin wrappers adding wire-only extras** — exactly how `/execute`/`/start` already worked.
+
+## The canonical validation report
+
+`PipelexValidationReport` moved to its own module `pipelex/pipeline/validation_report.py` and is now fully **typed** (no `Any` dumps — the typed schemas flow into pipelex-api's committed OpenAPI artifact):
+
+- `bundle_blueprint: PipelexBundleBlueprint` — the batch's PRIMARY blueprint (first declaring `main_pipe`, else first). Renamed from the hosted side's `pipelex_bundle_blueprint`: blueprints are MTHDS-language artifacts, so no `pipelex_` prefix inside an already-Pipelex-branded envelope (the brand-boundaries principle in the workspace `CLAUDE.md`).
+- `pipe_io_contracts: dict[str, PipeIOContract]` — per-pipe IO contracts keyed by **namespaced `pipe_ref`** (`domain.code`), never bare code. The builder (`build_pipe_io_contracts`) is **ported from pipelex-api's route-local `_build_pipe_structures`** — it is runtime logic over `PipeAbstract`/`StuffSpec` the API repo should never have owned. New module `pipelex/pipeline/pipe_io_contracts.py` (`PipeIOContract`/`PipeInputContract`/`PipeOutputContract`, `IOMultiplicity = single|variable`); JSON-Schema rendering memoized per `(concept_ref, is_multiple)` within a call (deliberately not cross-call — stale-class hazard). A pydantic schema-generation failure raises a structured `PipeIOContractError` with pipe/input context (it must not cross the Temporal boundary as a raw retryable third-party error).
+- `graph_spec: GraphSpec | None` — **best-effort real graph on the local protocol too** (was always `None`): one shared `best_effort_graph_spec(pipe_ref, *, library_id, log_context)` in `pipelex/pipe_run/dry_run_in_process.py` runs `dry_run_pipe_in_process` against the **already-open validation library, before the lifecycle teardown** — the same single-load pattern as the Temporal activity, used by both backends. Degrade catch `(PipelexError, ValidationError, FactoryException)` → `None` with a warning.
+- `validated_pipes: list[ValidatedPipeEntry]` — per-pipe sweep outcomes, same entries as the agent-CLI envelope. **`ValidatedPipeEntry` key renamed `pipe_code` → `pipe_ref`** (the value always WAS the namespaced ref — a documented misnomer, fixed before the key gets canonized onto a protocol surface). `typing_extensions.TypedDict`, not `typing.TypedDict` (pydantic rejects the latter as a model field on Python < 3.12).
+- `pending_signatures: list[str]` + `is_runnable: bool` — the Part I runnability verdict, promoted onto the protocol report.
+
+One selection rule, one constructor, every backend: `select_primary_blueprint` (in its own `blueprint_selection.py`; also folds the previously-duplicated first-declaring-main_pipe loops in `execution_seams.py`, `dry_run_pipeline.py`, `inputs_ops.py`) and `build_validation_report(...)` (in `validation_report.py`) are the only way reports are assembled — `PipelexMTHDSProtocol.validate` locally, `ApiRunner.validate` hosted (companion branch).
+
+- `pipelex/pipeline/runner.py` — `validate` reworked: artifacts built inside the library window (the validation library id captured ONCE after `validate_bundle`; graph arm + `finally` target the same library; a teardown raise is suppressed while a body error propagates, mirroring the Temporal activity). Return annotations narrowed to the concrete `PipelexValidationReport`/`PipelexModelDeck` so typed consumers (ApiRunner, routes) get typed access. An empty `mthds_contents` list is a structured `ValidateBundleError`, not a raw `IndexError`.
+
+## Temporal wire (`DryValidateResult`)
+
+The worker computes everything with its already-loaded library and ships it across the boundary, so the API side never re-acquires a library: `DryValidateResult` gains `pending_signatures` and `pipe_io_contracts` as **required** wire fields (version-skewed workers fail loudly instead of silently yielding `is_runnable=True`). `PipeIOContractError` is non-retryable at the `wf_dry_validate` tier alongside `ValidateBundleError`. Integration test pins both fields crossing the in-process Temporal boundary. Size sanity-checked on a large structured bundle: `pipe_io_contracts` is an order of magnitude smaller than the `graph_spec` that already crossed the wire; the payload cap is far away.
+
+## Model deck
+
+`PipelexModelDeck.aliases`/`waterfalls` are now **keyed by category** (`{category: {alias: model}}`): the old flat maps were built by `update()`-ing per-category maps and silently dropped cross-category alias collisions (e.g. `default-small`/`best-gpt` exist per category — proven against captured baselines). The protocol's flat `models` list is unchanged.
+
+## Module moves (import-cycle breaks, mechanical)
+
+- `dry_run_pipe_in_process` → NEW `pipelex/pipe_run/dry_run_in_process.py` (its old home `dry_run_pipeline.py` imports the runner; the runner importing the graph arm from it would close a cycle).
+- `dry_run_pipeline` → `pipelex/pipeline/dry_run_pipeline.py` (layering follow-up; importers + docs re-pointed).
+- `select_primary_blueprint` lives in its own `blueprint_selection.py`, NOT `validate_bundle.py` — importing from `validate_bundle` in `execution_seams` closed a cycle through `bundle_validator`. (Split out of `pipe_io_contracts.py`, where it had been parked: the contracts module is the heavy JSON-Schema builder, the selection rule is light and consumed by callers that never need the contracts.)
+- `MTHDS_PROTOCOL_VERSION` deleted: `version()` reports the SDK's `PROTOCOL_VERSION` directly ("single source of truth … runners do not get to override it"); the temporary re-export staged for pipelex-api's import was removed once the companion branch imports the SDK constant.
+
+## Part II test coverage
+
+- `tests/integration/pipelex/pipeline/test_pipe_io_contracts.py` — the D6 builder: `PipeSignature` pipes in lenient batches, multiplicity entry shapes, memoization, the `PipeIOContractError` wrap. `select_primary_blueprint` first-declaring / none / multiple is covered separately in `tests/unit/pipelex/pipeline/test_select_primary_blueprint.py`.
+- `tests/integration/pipelex/pipeline/test_protocol_validate.py` — the canonical report shape + lifecycle: graph populated on main-pipe bundles, graph-failure-mid-window degrades to `None` while restore/teardown holds (asserted WITHOUT mocks on the real-graph case), strict-raise, empty-contents guard.
+- `tests/integration/pipelex/temporal/` — both new `DryValidateResult` fields cross the boundary.
+- Downstream proof (not in this repo): pipelex-api's suite runs against this branch via an editable pin — local↔hosted byte-identity per fixture class is pinned by its `tests/unit/test_protocol_parity.py`; the conformance repo pins the agent-CLI envelope against workspace `docs/specs/pipelex-mthds-protocol.md`.
+
+---
+
+## Downstream (separate effort, NOT in this PR)
+
+The pipelex runtime support is complete here. The recursive **orchestrator** (`mthds-vibe`) + **worker** (`mthds-signature-expander`) + the `--allow-signatures` hook change live in the sibling `mthds-plugins` repo, prescribed by its `wip/recursive/design.md` (flipped to the additive model). Those artifacts don't exist yet; building them is a fresh effort and depends on the pipelex release carrying this branch.
+
+On the protocol side (Part II), the companion consumers ship after this branch releases: `pipelex-api@feature/Recursivity-and-protocols` (routes through the canonical report; restores its PyPI pin at the release carrying this branch), `pipelex-app@feature/protocol-alignment` (renamed wire field + `pipe_ref` lookups), `conformance@feature/Pending-signatures` (envelope conformance tests — red against `dev` pipelex until this merges).
+
+---
+
+## CHANGELOG (under `[Unreleased]`)
+
+The `[Unreleased]` entry in `CHANGELOG.md` covers the additive multi-file construction (reconciliation, cross-file concept resolution, domain-metadata merge, `pending_signatures`), the `PipeSignature` taxonomy eviction (removed `PipeType`/`PipeCategory.PIPE_SIGNATURE`), and the Part II protocol rework (canonical typed report, `pipe_ref` re-keying + D7 rename, graph arm, Temporal wire fields, category-keyed deck extensions, module moves). It also corrects the v0.33.0 entry's `protocol_version` claim (0.1.0 → 0.6.0, a factual error).
+
+---
+
+## Pre-merge design change — DONE
+
+Review flagged that `PipeSignature` should not be a peer pipe type — it's a contract substrate of `PipeAbstract`, not a sibling of `PipeLLM`/`PipeSequence`. **Landed:** `PipeSignature` is evicted from the executable taxonomy. `PipeType.PIPE_SIGNATURE` and `PipeCategory.PIPE_SIGNATURE` are removed; `is_signature` is now a class fact (base returns `False`, `PipeSignature` / `PipeSignatureBlueprint` override to `True`) instead of an enum read; a signature carries `type = "PipeSignature"` with `pipe_category = None`, admitted by the shared validators via a `PIPE_SIGNATURE_TYPE_TAG` allowlist entry. It stays a `PipeAbstract` subclass (the dry-run shim) and keeps `signature_for` for mthds-plugins (its `reject_signature_for_pipe_signature` guards are gone — the rejection is now structural, since `PipeSignature` is no longer a `PipeType` the field can coerce). As-built plan: [`signature-taxonomy-refactor.md`](wip/recursivity/signature-taxonomy-refactor.md).
diff --git a/docs/building-methods/pipes/signature-pipes.md b/docs/building-methods/pipes/signature-pipes.md
index 6a75be12a..872f93007 100644
--- a/docs/building-methods/pipes/signature-pipes.md
+++ b/docs/building-methods/pipes/signature-pipes.md
@@ -4,7 +4,9 @@ description: "Declare contract-only pipes with PipeSignature. Mock dependencies
# Signature Pipes
-A `PipeSignature` is a contract-only pipe: it declares inputs, an output, and a purpose without providing an implementation. It is the placeholder you reach for when you want to design the shape of a pipeline (or one of its steps) before committing to the operator that will eventually do the work.
+Every pipe *has* a signature — its contract: the `inputs` it consumes, the `output` it promises, and a `description` of its purpose. A `PipeSignature` is that contract **alone**: a pipe declared by its signature with no implementation behind it. It is the placeholder you reach for when you want to design the shape of a pipeline (or one of its steps) before committing to the operator that will eventually do the work.
+
+Because a signature is a contract rather than a way of running, it sits **outside** the executable pipe taxonomy. That taxonomy has two levels: a `PipeCategory` (`PipeOperator` or `PipeController`) and, beneath it, a concrete `PipeType` (`PipeLLM`, `PipeSequence`, and the rest). A `PipeSignature` is neither — it is not a `PipeType` like `PipeLLM` or `PipeSequence`, and it belongs to no `PipeCategory`. Its runtime form is a dry-run-only shim — it can verify inputs and mock its declared output, but it never executes live. Implementing a signature is not swapping one pipe *type* for another; it is fulfilling a contract with a concrete pipe that satisfies it.
Signatures let an agent (or a human author) build a complete, dry-runnable bundle while leaving some pipes deliberately unimplemented. Strict validation refuses any pipeline that still depends on a signature; lenient mode (`--allow-signatures`) dry-runs them as mocks, so you can keep iterating on the structure of a method before writing every step.
@@ -134,6 +136,11 @@ pipelex validate --all --allow-signatures
When `--all` runs in strict mode, signature pipes themselves are skipped during the iteration (an unreached signature is fine). Strict mode only fires when a non-signature pipe *depends on* a signature.
+!!! note "Signatures and definitions can live in separate files"
+ A signature and the concrete pipe that implements it do not have to sit in the same `.mthds` file. A same-domain library can be split across sibling files in one directory: a header file forward-declares pipes as `PipeSignature` (plus the concepts those contracts reference), and definition files supply the concrete pipes. Loading the set merges them — a `PipeSignature` and a concrete pipe of the same code reconcile (the concrete satisfies the header), provided their `inputs`/`output` contracts match. Order does not matter.
+
+ On a successful lenient run, `validate bundle` reports `pending_signatures` — the headers still unimplemented across the *whole merged* library — and states explicitly whether the method is runnable (runnable once nothing remains, not yet runnable while headers are pending), so you can see exactly what is left to define. See [Validate Commands](../../tools/cli/validate.md) for the output surface. The same verdict is reported by the protocol-level `validate` (`PipelexMTHDSProtocol.validate`) as `pending_signatures` + `is_runnable` fields on its validation report, so a build driving the runtime through the MTHDS Protocol sees it too.
+
## Replacing a signature with a real implementation
When you are ready to implement, change the `type` of the pipe and add the operator-specific fields. The pipe code, `description`, `inputs`, and `output` typically carry over unchanged — that is the value of having declared the contract first.
diff --git a/docs/errors/concept-library-error.md b/docs/errors/concept-library-error.md
index 47de7aa3a..96e9fe75b 100644
--- a/docs/errors/concept-library-error.md
+++ b/docs/errors/concept-library-error.md
@@ -14,6 +14,6 @@ description: "Reference for the `ConceptLibraryError` Pipelex error class."
| `type_uri` | `https://docs.pipelex.com/latest/errors/concept-library-error/` |
| `error_domain` | _(inherited from parent)_ |
| Defined in | `pipelex.libraries.concept.exceptions` |
-| Parent class | [`PipelexError`](pipelex-error.md) |
+| Parent class | [`LibraryError`](library-error.md) |
[Back to Error Reference](index.md)
diff --git a/docs/errors/execution-and-runtime.md b/docs/errors/execution-and-runtime.md
index d8a3e24db..689fdb967 100644
--- a/docs/errors/execution-and-runtime.md
+++ b/docs/errors/execution-and-runtime.md
@@ -28,6 +28,7 @@ own page. Classes are grouped by subsystem.
- [`JobMetadataError`](job-metadata-error.md) — Job metadata
- [`PipeExecutionError`](pipe-execution-error.md) — Pipe execution
+- [`PipeIOContractError`](pipe-io-contract-error.md) — Pipe IO contract
- [`PipeStackOverflowError`](pipe-stack-overflow-error.md) — Pipe stack overflow
- [`PipelineExecutionError`](pipeline-execution-error.md) — Pipeline execution
- [`PipelineInputContentError`](pipeline-input-content-error.md) — Pipeline input content
diff --git a/docs/errors/pipe-io-contract-error.md b/docs/errors/pipe-io-contract-error.md
new file mode 100644
index 000000000..43e61336f
--- /dev/null
+++ b/docs/errors/pipe-io-contract-error.md
@@ -0,0 +1,21 @@
+---
+title: "Pipe IO contract"
+description: "Reference for the `PipeIOContractError` Pipelex error class."
+---
+
+<!-- pipelex:generated -->
+
+# Pipe IO contract
+
+Raised when projecting a validated pipe into its `pipe_io_contracts` IO contract fails.
+
+| Field | Value |
+|---|---|
+| `error_type` | `PipeIOContractError` |
+| `title` | Pipe IO contract |
+| `type_uri` | `https://docs.pipelex.com/latest/errors/pipe-io-contract-error/` |
+| `error_domain` | _(inherited from parent)_ |
+| Defined in | `pipelex.pipeline.exceptions` |
+| Parent class | [`PipelexError`](pipelex-error.md) |
+
+[Back to Error Reference](index.md)
diff --git a/docs/errors/pipe-library-error.md b/docs/errors/pipe-library-error.md
index 116816b13..d9d2b532f 100644
--- a/docs/errors/pipe-library-error.md
+++ b/docs/errors/pipe-library-error.md
@@ -14,6 +14,6 @@ description: "Reference for the `PipeLibraryError` Pipelex error class."
| `type_uri` | `https://docs.pipelex.com/latest/errors/pipe-library-error/` |
| `error_domain` | _(inherited from parent)_ |
| Defined in | `pipelex.libraries.pipe.exceptions` |
-| Parent class | [`PipelexError`](pipelex-error.md) |
+| Parent class | [`LibraryError`](library-error.md) |
[Back to Error Reference](index.md)
diff --git a/docs/tools/cli/agent-cli.md b/docs/tools/cli/agent-cli.md
index 690c34645..c3b6cd5b6 100644
--- a/docs/tools/cli/agent-cli.md
+++ b/docs/tools/cli/agent-cli.md
@@ -71,6 +71,8 @@ For `bundle`, additional options are available:
!!! note "Signature pipes"
`pipelex-agent validate` is strict by default — same as `pipelex validate`. A bundle whose dependency graph reaches a `PipeSignature` is rejected unless you pass `--allow-signatures`, which dry-runs signatures as mocks.
+ On a successful `validate bundle` run, the envelope also carries `pending_signatures` — the library-wide list of pipes still declared as `PipeSignature` (unimplemented forward declarations), each namespaced by `pipe_ref` (`domain.code`). It is a non-blocking nudge: in JSON it is a `pending_signatures` array, in markdown a "Pending signatures" section. A top-down build reads it to see exactly which headers remain to implement. The envelope also carries a derived `is_runnable` boolean (`true` ⇔ `pending_signatures` is empty), and the markdown states the runnability verdict in plain English — runnable when complete, NOT yet runnable above the "Pending signatures" section otherwise. Both are scoped to `validate bundle`; `validate all` / `validate pipe` omit them.
+
### Inputs
Generate example input JSON for a pipe, bundle, or method.
diff --git a/docs/under-the-hood/dry-run-mock-generation.md b/docs/under-the-hood/dry-run-mock-generation.md
index 07c864dce..06e91ebc3 100644
--- a/docs/under-the-hood/dry-run-mock-generation.md
+++ b/docs/under-the-hood/dry-run-mock-generation.md
@@ -309,7 +309,8 @@ class MySpec(StructuredContent):
| `pipelex/cogt/content_generation/dry_mock.py` | Leaf-level dry/mock helpers (`dry_llm_gen_*`, `build_mock_object`, `stamp_mock_main_coordination`) |
| `pipelex/core/memory/working_memory_factory.py` | `WorkingMemoryFactory.make_mock_content()` with field constraints |
| `pipelex/pipe_operators/compose/structured_content_composer.py` | Composes `StructuredContent` from working memory (no mocks) |
-| `pipelex/pipe_run/dry_run_pipeline.py` | `dry_run_pipeline()` / `dry_run_pipe_in_process()` orchestration |
+| `pipelex/pipeline/dry_run_pipeline.py` | `dry_run_pipeline()` orchestration |
+| `pipelex/pipe_run/dry_run_in_process.py` | `dry_run_pipe_in_process()` — the in-process, never-dispatching twin |
---
diff --git a/docs/under-the-hood/execution-graph-tracing.md b/docs/under-the-hood/execution-graph-tracing.md
index e277c8095..4dadf6451 100644
--- a/docs/under-the-hood/execution-graph-tracing.md
+++ b/docs/under-the-hood/execution-graph-tracing.md
@@ -83,7 +83,7 @@ graph_spec = response.pipe_output.graph_spec
```
!!! tip "Dry run from MTHDS content"
- To dry-run an entire bundle straight from MTHDS content and get back a `GraphSpec`, use `dry_run_pipeline(mthds_contents=...)` (`pipelex/pipe_run/dry_run_pipeline.py`) — the shared entrypoint behind the CLI graph commands and the API, which wires the same DRY-mode runner for you. It owns its graph transport (a scoped in-memory event log), so it produces the graph regardless of the host's `tracing_config` and never writes trace files as a side effect.
+ To dry-run an entire bundle straight from MTHDS content and get back a `GraphSpec`, use `dry_run_pipeline(mthds_contents=...)` (`pipelex/pipeline/dry_run_pipeline.py`) — the shared entrypoint behind the CLI graph commands, which wires the same DRY-mode runner for you. It owns its graph transport (a scoped in-memory event log), so it produces the graph regardless of the host's `tracing_config` and never writes trace files as a side effect.
### Outputs
@@ -269,7 +269,7 @@ Semantics:
- A set override **implies tracing-enabled**: it is honored even when `tracing_config.is_enabled` is `False`, on both the write side and the read side's early-return.
- Lifecycle: the read side does not `close()` the scoped instance and the machinery never calls `cleanup()` on it — but the write-side tracer DOES call `close()` on its event log at teardown, before the read side assembles. A scoped event log's `close()` must therefore be idempotent or a no-op (as `InMemoryEventLog`'s is); scoping a backend whose `close()` releases a real resource would break its own assembly read.
-This is what lets a graph-producing dry-run trace entirely in memory (no NDJSON file, no DynamoDB round-trip). Both dry-run entrypoints in `pipelex/pipe_run/dry_run_pipeline.py` rely on it: `dry_run_pipe_in_process` (validation and graph dry-run hosted inside a single Temporal activity) and `dry_run_pipeline` itself — these functions exist to produce a graph, so they install their own scoped `InMemoryEventLog` rather than depending on the host having tracing configured (a host with `tracing_config.is_enabled = false`, like pipelex-api's `/validate` in direct mode, still gets its graph). A run that nonetheless finishes without a graph raises the typed `DryRunGraphNotProducedError`.
+This is what lets a graph-producing dry-run trace entirely in memory (no NDJSON file, no DynamoDB round-trip). Both dry-run entrypoints rely on it: `dry_run_pipe_in_process` (`pipelex/pipe_run/dry_run_in_process.py` — the graph arm of protocol `validate` and of the single Temporal validation activity) and `dry_run_pipeline` (`pipelex/pipeline/dry_run_pipeline.py`) itself — these functions exist to produce a graph, so they install their own scoped `InMemoryEventLog` rather than depending on the host having tracing configured (a host with `tracing_config.is_enabled = false`, like pipelex-api's `/validate` in direct mode, still gets its graph). A run that nonetheless finishes without a graph raises the typed `DryRunGraphNotProducedError`.
### TraceContext Propagation
diff --git a/docs/under-the-hood/temporal-integration.md b/docs/under-the-hood/temporal-integration.md
index fa4f81e98..9979016f5 100644
--- a/docs/under-the-hood/temporal-integration.md
+++ b/docs/under-the-hood/temporal-integration.md
@@ -216,7 +216,7 @@ Both call `ContentGeneratorInWorkflow.make_templated_text` from inside `WfPipeRo
## Validation Dispatch: One In-Process Activity
-Pipeline *execution* fans out across workflows and activities as described above — but *validation* deliberately does the opposite. When Temporal is enabled, a `/validate` job (validation sweep + graph-producing dry-run) dispatches as the one-step wrapper workflow `wf_dry_validate`, which runs a single `act_dry_validate` activity and returns `{per-pipe status map, GraphSpec | None}` in one round-trip.
+Pipeline *execution* fans out across workflows and activities as described above — but *validation* deliberately does the opposite. When Temporal is enabled, a `/validate` job (validation sweep + graph-producing dry-run) dispatches as the one-step wrapper workflow `wf_dry_validate`, which runs a single `act_dry_validate` activity and returns everything the canonical validation report needs that must be computed worker-side, in one round-trip: the per-pipe status map, the best-effort `GraphSpec`, the library-wide `pending_signatures`, and the `pipe_io_contracts` IO contracts (built inside the worker's library window — their JSON-Schema rendering resolves bundle-defined structure classes through the loaded library's class registry, so the API side never needs to re-acquire a library).
Inside the activity everything is in-process and in-memory:
diff --git a/pipelex/builder/operations/inputs_ops.py b/pipelex/builder/operations/inputs_ops.py
index 4556c10b2..f280b4a97 100644
--- a/pipelex/builder/operations/inputs_ops.py
+++ b/pipelex/builder/operations/inputs_ops.py
@@ -13,6 +13,7 @@ from pipelex.hub import (
resolve_library_dirs,
set_current_library,
)
+from pipelex.pipeline.blueprint_selection import select_primary_blueprint
from pipelex.pipeline.validate_bundle import validate_bundle
if TYPE_CHECKING:
@@ -50,12 +51,8 @@ async def build_inputs_for_pipe(
validate_bundle_result = await validate_bundle(mthds_contents=mthds_contents, library_dirs=library_dirs, allow_signatures=True)
blueprints = validate_bundle_result.blueprints
if not pipe_code:
- # Find the first blueprint that declares a main_pipe, domain-qualified
- main_pipe_code: str | None = None
- for blueprint in blueprints:
- if blueprint.main_pipe:
- main_pipe_code = PipeFactory.make_pipe_ref_with_domain(domain_code=blueprint.domain, pipe_code=blueprint.main_pipe)
- break
+ # Domain-qualified main pipe of the primary blueprint — the one shared selection rule.
+ main_pipe_code = select_primary_blueprint(blueprints).main_pipe_ref
if not main_pipe_code:
msg = "Bundle does not declare a main_pipe. Specify a pipe code."
raise ValueError(msg)
diff --git a/pipelex/builder/operations/validate_ops.py b/pipelex/builder/operations/validate_ops.py
index 888ece92e..3c33ba7d3 100644
--- a/pipelex/builder/operations/validate_ops.py
+++ b/pipelex/builder/operations/validate_ops.py
@@ -39,6 +39,10 @@ async def validate_all(
library_dirs=[str(library_dir) for library_dir in library_dirs] if library_dirs else None,
)
+ # No `pending_signatures` here by design: it is a per-bundle, top-down-build nudge ("which headers
+ # are still unimplemented in this bundle"), surfaced only by `validate bundle`. The validate-all
+ # sweep is a whole-library check, not a build step — and `acquire_and_validate` tears its library
+ # down before returning, so the set could not be computed post-hoc without reshaping a shared method.
return {
"success": True,
"validated_pipes": build_validated_pipes(dry_run_results),
@@ -69,6 +73,8 @@ async def validate_bundle_file(
"bundle_path": str(bundle_path),
"validated_pipes": build_validated_pipes(result.dry_run_result),
"total_pipes": len(result.dry_run_result),
+ "pending_signatures": result.pending_signatures,
+ "is_runnable": not result.pending_signatures,
}
@@ -95,6 +101,8 @@ async def validate_bundle_content(
"pipelex_bundle_blueprint": [b.model_dump(mode="json") for b in blueprints],
"validated_pipes": build_validated_pipes(validate_bundle_result.dry_run_result),
"total_pipes": len(validate_bundle_result.dry_run_result),
+ "pending_signatures": validate_bundle_result.pending_signatures,
+ "is_runnable": not validate_bundle_result.pending_signatures,
}
@@ -178,4 +186,6 @@ async def validate_pipe_in_bundle(
"bundle_path": str(bundle_path),
"validated_pipes": build_validated_pipes(result.dry_run_result),
"total_pipes": len(result.dry_run_result),
+ "pending_signatures": result.pending_signatures,
+ "is_runnable": not result.pending_signatures,
}
diff --git a/pipelex/builder/pipe/pipe_signature_spec.py b/pipelex/builder/pipe/pipe_signature_spec.py
index c91b350dc..227a7a317 100644
--- a/pipelex/builder/pipe/pipe_signature_spec.py
+++ b/pipelex/builder/pipe/pipe_signature_spec.py
@@ -1,6 +1,6 @@
from typing import Literal
-from pydantic import Field, field_validator
+from pydantic import Field
from pydantic.json_schema import SkipJsonSchema
from rich.console import Group
from rich.markup import escape
@@ -40,24 +40,21 @@ class PipeSignatureSpec(PipeSpec):
Optional fields:
- `signature_for`: hint naming the downstream pipe type the signature stands in for
- (e.g. `PipeType.PIPE_LLM`). Tooling-only; cannot itself be `PipeSignature`.
+ (e.g. `PipeType.PIPE_LLM`). Tooling-only; `PipeSignature` is not a `PipeType`, so it
+ cannot be selected here.
"""
type: SkipJsonSchema[Literal["PipeSignature"]] = "PipeSignature"
+ # Spec-layer display/authoring tag only: NOT propagated by `to_blueprint()`, which leaves the
+ # blueprint (and runtime) at `pipe_category = None` because a signature is outside the executable
+ # taxonomy. Kept per the scope decision in wip/recursivity/signature-taxonomy-refactor.md; it only
+ # surfaces in `rendered_pretty` below.
pipe_category: SkipJsonSchema[Literal["PipeSignature"]] = "PipeSignature"
signature_for: PipeType | None = Field(
default=None,
description="Intended downstream pipe type when this signature is implemented (optional hint for agents).",
)
- @field_validator("signature_for", mode="after")
- @classmethod
- def reject_signature_for_pipe_signature(cls, value: PipeType | None) -> PipeType | None:
- if value is PipeType.PIPE_SIGNATURE:
- msg = "A PipeSignature cannot have signature_for=PipeSignature."
- raise ValueError(msg)
- return value
-
@override
def to_blueprint(self) -> PipeSignatureBlueprint:
return PipeSignatureBlueprint(
diff --git a/pipelex/builder/pipe/pipe_spec.py b/pipelex/builder/pipe/pipe_spec.py
index 97145571e..7b51bcc10 100644
--- a/pipelex/builder/pipe/pipe_spec.py
+++ b/pipelex/builder/pipe/pipe_spec.py
@@ -11,7 +11,7 @@ from pipelex import log
from pipelex.cogt.content_generation.dry_run_factory import MockFormat
from pipelex.core.concepts.exceptions import ConceptStringError
from pipelex.core.concepts.validation import validate_concept_ref_or_code
-from pipelex.core.pipes.pipe_blueprint import PipeBlueprint, PipeCategory, PipeType
+from pipelex.core.pipes.pipe_blueprint import PipeBlueprint, PipeCategory, PipeType, valid_pipe_type_tags
from pipelex.core.pipes.variable_multiplicity import MUTLIPLICITY_PATTERN, parse_concept_with_multiplicity
from pipelex.core.stuffs.structured_content import StructuredContent
from pipelex.tools.misc.pretty import PrettyPrintable
@@ -79,8 +79,9 @@ class PipeSpec(StructuredContent):
@field_validator("type", mode="after")
@classmethod
def validate_pipe_type(cls, value: Any) -> Any:
- if value not in PipeType.value_list():
- msg = f"Invalid pipe type '{value}'. Must be one of: {PipeType.value_list()}"
+ allowed = valid_pipe_type_tags()
+ if value not in allowed:
+ msg = f"Invalid pipe type '{value}'. Must be one of: {allowed}"
raise ValueError(msg)
return value
diff --git a/pipelex/cli/agent_cli/CLAUDE.md b/pipelex/cli/agent_cli/CLAUDE.md
index e6c7975a0..ff924c6ff 100644
--- a/pipelex/cli/agent_cli/CLAUDE.md
+++ b/pipelex/cli/agent_cli/CLAUDE.md
@@ -16,7 +16,7 @@ Only the error format is backed by a module-level `ContextVar` in `agent_output.
Markdown structure per command:
- `run`: `# Pipeline run complete`, a `## Result` section (the rendered `main_stuff` markdown with `--with-memory`, otherwise the concept JSON in a fenced block), and output / graph file paths. Cost is machine-first: on the local runner, when costs are on (`--costs`, the default) and the run did reportable work (any tokens or any cost), a best-effort `cost_report` object (`{total_cost, by_model: [...]}`, real USD) rides the JSON `--with-memory` envelope — there is **no** Rich cost table on stderr (unlike the human `pipelex run` CLI). The markdown renderer ignores the `cost_report` key, so it is JSON-only. A free/zero-price model still reports its token usage (with `total_cost` 0). The `cost_report` is **absent** when the run did no reportable work (dry runs), when `--no-costs` is passed, on the API-runner path (which does not assemble local usage), or if cost-summary aggregation fails (caught and skipped so it never fails an otherwise-successful run) — so consumers must treat it as optional.
-- `validate`: `# Validation passed`, the bundle path when relevant, and a list of validated pipes with their status. Every entry in `validated_pipes` (markdown and JSON) identifies its pipe by the namespaced `pipe_ref` (`domain.code`) — the same unambiguous identity across `validate all`, `validate bundle`, and `validate pipe`, so the same pipe is never reported under two identifiers.
+- `validate`: `# Validation passed`, the bundle path when relevant, and a list of validated pipes with their status. Every entry in `validated_pipes` (markdown and JSON) identifies its pipe by the namespaced `pipe_ref` (`domain.code`) — the same unambiguous identity across `validate all`, `validate bundle`, and `validate pipe`, so the same pipe is never reported under two identifiers. `validate bundle` additionally carries `pending_signatures` — the library-wide list of pipes still declared as `PipeSignature` (unimplemented forward declarations), namespaced by `pipe_ref` — a non-blocking nudge on a successful lenient (`--allow-signatures`) run, rendered as a "Pending signatures" section in markdown. It also carries a derived `is_runnable` boolean (`true` ⇔ `pending_signatures` is empty), and the markdown adds an explicit plain-English runnability verdict on the bundle surfaces: a complete bundle states it is runnable, while one with pending signatures states it is NOT yet runnable immediately above the verbatim "Pending signatures" heading. Both `is_runnable` and the verdict line are scoped to the bundle surfaces (which compute `pending_signatures`); `validate all` / `validate pipe` omit the key and emit no verdict.
- `init`: `# Pipelex initialized` with target directory, enabled backends, and routing profile.
- error path: `# Error: <error_type>`, the message, the hint as a `> 💡` callout, and a `## Details` section. `error_source` (internal stack frames) is omitted from markdown — it remains in the JSON envelope (`--error-format json`) for programmatic consumers.
diff --git a/pipelex/cli/agent_cli/commands/pipe_cmd.py b/pipelex/cli/agent_cli/commands/pipe_cmd.py
index 20b93700d..182968a85 100644
--- a/pipelex/cli/agent_cli/commands/pipe_cmd.py
+++ b/pipelex/cli/agent_cli/commands/pipe_cmd.py
@@ -22,11 +22,13 @@ from pipelex.builder.pipe.pipe_func_spec import PipeFuncSpec
from pipelex.builder.pipe.pipe_img_gen_spec import PipeImgGenSpec
from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec
from pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpec
+from pipelex.builder.pipe.pipe_search_spec import PipeSearchSpec
from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec
+from pipelex.builder.pipe.pipe_signature_spec import PipeSignatureSpec
from pipelex.builder.pipe.pipe_spec import PipeSpec
+from pipelex.builder.pipe.pipe_spec_map import pipe_type_to_spec_class
from pipelex.builder.pipe.pipe_structure_spec import PipeStructureSpec
from pipelex.cli.agent_cli.commands.agent_output import agent_error
-from pipelex.core.pipes.pipe_blueprint import PipeType
from pipelex.language.toml_string_utils import format_toml_string
from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error_for_agent
@@ -161,11 +163,30 @@ def _add_type_specific_fields(pipe_spec: PipeSpec, pipe_table: tomlkit.TOMLDocum
elif isinstance(pipe_spec, PipeFuncSpec):
pipe_table.add("function_name", pipe_spec.function_name)
+ elif isinstance(pipe_spec, PipeSearchSpec):
+ if pipe_spec.model:
+ pipe_table.add("model", pipe_spec.model)
+ pipe_table.add("prompt", format_toml_string(pipe_spec.prompt))
+ if pipe_spec.from_date is not None:
+ pipe_table.add("from_date", pipe_spec.from_date)
+ if pipe_spec.to_date is not None:
+ pipe_table.add("to_date", pipe_spec.to_date)
+ if pipe_spec.include_domains is not None:
+ pipe_table.add("include_domains", pipe_spec.include_domains)
+ if pipe_spec.exclude_domains is not None:
+ pipe_table.add("exclude_domains", pipe_spec.exclude_domains)
+ if pipe_spec.max_results is not None:
+ pipe_table.add("max_results", pipe_spec.max_results)
+
+ elif isinstance(pipe_spec, PipeSignatureSpec):
+ if pipe_spec.signature_for is not None:
+ pipe_table.add("signature_for", pipe_spec.signature_for)
+
def pipe_cmd(
pipe_type: Annotated[
str | None,
- typer.Option("--type", "--pipe-type", "--pipe_type", "-t", help=f"Pipe type. Must be one of: {PipeType.value_list()}"),
+ typer.Option("--type", "--pipe-type", "--pipe_type", "-t", help=f"Pipe type. Must be one of: {list(pipe_type_to_spec_class)}"),
] = None,
spec: Annotated[
str | None,
diff --git a/pipelex/cli/agent_cli/commands/validate/_output_helpers.py b/pipelex/cli/agent_cli/commands/validate/_output_helpers.py
index 16c12e8a7..e032a59c8 100644
--- a/pipelex/cli/agent_cli/commands/validate/_output_helpers.py
+++ b/pipelex/cli/agent_cli/commands/validate/_output_helpers.py
@@ -9,7 +9,7 @@ def format_validate_markdown(result: dict[str, Any]) -> str:
"""Render a validation result dict as agent-readable markdown.
Covers the success-path shape produced by the ``validate`` core helpers:
- ``validated_pipes`` (a list of ``{pipe_code, status}``), ``total_pipes``,
+ ``validated_pipes`` (a list of ``{pipe_ref, status}``), ``total_pipes``,
and an optional ``bundle_path``. ``validate bundle --graph`` / ``--view``
also merge ``graph_files`` / ``graphspec`` into the result — those are
surfaced too so markdown mode does not silently drop them.
@@ -31,7 +31,37 @@ def format_validate_markdown(result: dict[str, Any]) -> str:
lines.append(f"Validated {total_pipes} pipe(s):")
lines.append("")
for entry in validated_pipes:
- lines.append(f"- `{entry.get('pipe_code')}` — {entry.get('status')}")
+ lines.append(f"- `{entry.get('pipe_ref')}` — {entry.get('status')}")
+
+ # Runnability verdict — gated on key *presence*, not truthiness. Only the bundle-validate
+ # surfaces put `pending_signatures` in the result; `validate all` / `validate pipe` omit the key,
+ # so they get no verdict (claiming runnability there would be misleading). Present-and-empty is a
+ # complete bundle (runnable); present-and-non-empty still has forward declarations to implement.
+ if "pending_signatures" in result:
+ pending_signatures: list[str] = result["pending_signatures"] or []
+ if pending_signatures:
+ # Verdict line is emitted immediately above the verbatim "Pending signatures" heading —
+ # downstream consumers rely on that exact ordering (see agent_cli/CLAUDE.md).
+ lines += [
+ "",
+ (
+ f"⚠️ This method is NOT yet runnable — {len(pending_signatures)} pipe(s) are still "
+ "`PipeSignature` placeholders and must be implemented before running:"
+ ),
+ "",
+ f"## Pending signatures ({len(pending_signatures)})",
+ "",
+ ]
+ for pending_ref in pending_signatures:
+ lines.append(f"- `{pending_ref}`")
+ else:
+ lines += [
+ "",
+ (
+ "✅ All pipes are concretely implemented — no `PipeSignature` placeholders remain. "
+ "Strict validation will pass; this method is runnable."
+ ),
+ ]
graph_files = result.get("graph_files")
if isinstance(graph_files, dict):
diff --git a/pipelex/cli/agent_cli/commands/validate/_validate_core.py b/pipelex/cli/agent_cli/commands/validate/_validate_core.py
index 67d49f940..caed29298 100644
--- a/pipelex/cli/agent_cli/commands/validate/_validate_core.py
+++ b/pipelex/cli/agent_cli/commands/validate/_validate_core.py
@@ -44,6 +44,8 @@ async def validate_all_core(
allow_signatures=allow_signatures,
)
+ # No `pending_signatures` here by design — see validate_all in builder/operations/validate_ops.py:
+ # it is a per-bundle top-down-build nudge surfaced only by `validate bundle`, not the whole-library sweep.
return {
"success": True,
"validated_pipes": build_validated_pipes(dry_run_results),
@@ -77,12 +79,16 @@ async def validate_bundle_core(
)
# Consume the real per-pipe status from the sweep — a fixed all-"SUCCESS" list would hide allowed
- # failures and SKIPPED cross-package pipes the dry-run actually recorded (C-8).
+ # failures and SKIPPED cross-package pipes the dry-run actually recorded (C-8). pending_signatures
+ # is the library-wide set of still-unimplemented forward declarations — a non-blocking nudge on a
+ # successful lenient (--allow-signatures) run.
return {
"success": True,
"bundle_path": str(bundle_path),
"validated_pipes": build_validated_pipes(result.dry_run_result),
"total_pipes": len(result.dry_run_result),
+ "pending_signatures": result.pending_signatures,
+ "is_runnable": not result.pending_signatures,
}
@@ -174,10 +180,13 @@ async def validate_pipe_in_bundle_core(
)
# Consume the real per-pipe status from the sliced sweep — a fixed "SUCCESS" would hide an allowed
- # failure or a cross-package SKIPPED the dry-run actually recorded (C-8).
+ # failure or a cross-package SKIPPED the dry-run actually recorded (C-8). pending_signatures is the
+ # library-wide set of still-unimplemented forward declarations.
return {
"success": True,
"bundle_path": str(bundle_path),
"validated_pipes": build_validated_pipes(result.dry_run_result),
"total_pipes": len(result.dry_run_result),
+ "pending_signatures": result.pending_signatures,
+ "is_runnable": not result.pending_signatures,
}
diff --git a/pipelex/core/bundles/pipelex_bundle_blueprint.py b/pipelex/core/bundles/pipelex_bundle_blueprint.py
index ed34d198e..a7767c5f5 100644
--- a/pipelex/core/bundles/pipelex_bundle_blueprint.py
+++ b/pipelex/core/bundles/pipelex_bundle_blueprint.py
@@ -11,10 +11,8 @@ from pipelex.core.domains.exceptions import DomainCodeError
from pipelex.core.domains.validation import validate_domain_code
from pipelex.core.pipes.validation import is_pipe_code_valid
from pipelex.core.pipes.variable_multiplicity import parse_concept_with_multiplicity
-from pipelex.core.qualified_ref import QualifiedRef, QualifiedRefError
from pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprint
from pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprint
-from pipelex.pipe_controllers.condition.special_outcome import SpecialOutcome
from pipelex.pipe_controllers.parallel.pipe_parallel_blueprint import PipeParallelBlueprint
from pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint
from pipelex.pipe_operators.compose.pipe_compose_blueprint import PipeComposeBlueprint
@@ -25,7 +23,7 @@ from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint
from pipelex.pipe_operators.search.pipe_search_blueprint import PipeSearchBlueprint
from pipelex.pipe_operators.structure.pipe_structure_blueprint import PipeStructureBlueprint
from pipelex.pipe_signature.pipe_signature_blueprint import PipeSignatureBlueprint
-from pipelex.types import Self, StrEnum
+from pipelex.types import StrEnum
from pipelex.urls import URLs
PipeBlueprintUnion = Annotated[
@@ -142,102 +140,6 @@ class PipelexBundleBlueprint(BaseModel):
raise ValueError(msg)
return self
- @model_validator(mode="after")
- def validate_local_concept_references(self) -> Self:
- """Validate that local concept references are declared in this bundle or are native concepts.
-
- This validates two cases:
- 1. Concept codes without domain prefix (e.g., 'MyConceptName')
- 2. Concept refs with the same domain as this bundle (e.g., 'this_domain.MyConceptName')
-
- External references (concepts from other domains) are not validated here - they're
- assumed to be declared in their respective bundles and loaded via dependencies.
- """
- declared_concepts: set[str] = set(self.concept.keys()) if self.concept else set()
- native_codes = {native.value for native in NativeConceptCode.values_list()}
- all_refs = self._collect_local_concept_references()
-
- undeclared_refs: list[str] = []
- for concept_ref_or_code, context in all_refs:
- # Cross-package references are validated at package level, not bundle level
- if QualifiedRef.has_cross_package_prefix(concept_ref_or_code):
- continue
-
- # Parse the reference using QualifiedRef
- ref = QualifiedRef.parse(concept_ref_or_code)
-
- if ref.is_external_to(self.domain):
- # External reference - skip validation (will be validated when loading dependencies)
- continue
-
- # Local reference (bare code or same domain) - validate
- concept_code = ref.local_code
- if concept_code not in declared_concepts and concept_code not in native_codes:
- undeclared_refs.append(f"'{concept_ref_or_code}' in {context}")
-
- if undeclared_refs:
- msg = (
- f"The following local concept references are not declared in domain '{self.domain}' at '{self.source}' "
- f"and are not native concepts: {', '.join(undeclared_refs)}. "
- f"Declared concepts: {sorted(declared_concepts) if declared_concepts else '(none)'}. "
- f"Native concepts: {sorted(native_codes)}"
- )
- raise ValueError(msg)
- return self
-
- @model_validator(mode="after")
- def validate_local_pipe_references(self) -> Self:
- """Validate that domain-qualified pipe references pointing to this bundle's domain exist locally.
-
- Three categories:
- - Bare refs (no dot): no validation here (deferred to package-level resolution)
- - Domain-qualified, same domain: must exist in self.pipe
- - Domain-qualified, different domain: skip (external, validated at load time)
-
- Special outcomes ("fail", "continue") are excluded from validation.
- """
- declared_pipes: set[str] = set(self.pipe.keys()) if self.pipe else set()
- special_outcomes = SpecialOutcome.value_list()
- all_pipe_refs = self.collect_pipe_references()
-
- invalid_refs: list[str] = []
- for pipe_ref_str, context in all_pipe_refs:
- # Skip special outcomes
- if pipe_ref_str in special_outcomes:
- continue
-
- # Cross-package references are validated at package level, not bundle level
- if QualifiedRef.has_cross_package_prefix(pipe_ref_str):
- continue
-
- # Try to parse as a pipe ref
- try:
- ref = QualifiedRef.parse_pipe_ref(pipe_ref_str)
- except QualifiedRefError:
- # If it doesn't parse as a valid pipe ref, skip (will be caught elsewhere)
- continue
-
- if not ref.is_qualified:
- # Bare ref - no validation at bundle level
- continue
-
- if ref.is_external_to(self.domain):
- # External domain - skip
- continue
-
- # Same domain, qualified ref - must exist locally
- if ref.local_code not in declared_pipes:
- invalid_refs.append(f"'{pipe_ref_str}' in {context}")
-
- if invalid_refs:
- msg = (
- f"The following same-domain pipe references are not declared in domain '{self.domain}' "
- f"at '{self.source}': {', '.join(invalid_refs)}. "
- f"Declared pipes: {sorted(declared_pipes) if declared_pipes else '(none)'}"
- )
- raise ValueError(msg)
- return self
-
def get_elaboration_for(self, pipe_code: str) -> ElaborationMetadata | None:
"""Return the elaboration metadata for a synthetic pipe, or None if the pipe is user-authored."""
if not self.elaboration_metadata:
@@ -270,7 +172,18 @@ class PipelexBundleBlueprint(BaseModel):
return pipe_refs
- def _collect_local_concept_references(self) -> list[tuple[str, str]]:
+ def collect_concept_references(self) -> list[tuple[str, str]]:
+ """Collect all concept references from this bundle's concepts and pipes.
+
+ Mirrors collect_pipe_references(): returns every concept reference (bare code,
+ same-domain, external-domain, or cross-package) paired with a context path. The
+ caller decides which references to resolve and where. Reference resolution for
+ same-domain refs is performed at library level over the merged crate, not per file,
+ so a concept declared in one file can be referenced from a sibling file.
+
+ Returns:
+ List of (concept_ref_or_code, context_description) tuples
+ """
local_refs: list[tuple[str, str]] = []
# Collect from concepts
diff --git a/pipelex/core/pipes/output/output_renderer.py b/pipelex/core/pipes/output/output_renderer.py
index c133dfc83..582a7c4fe 100644
--- a/pipelex/core/pipes/output/output_renderer.py
+++ b/pipelex/core/pipes/output/output_renderer.py
@@ -29,6 +29,10 @@ def _collect_possible_outputs(
Returns:
A list of possible output dicts, each containing 'concept_ref' and 'content'
"""
+ if the_pipe.is_signature:
+ # A signature is outside the `PipeType` taxonomy (no executable kind) and contributes no
+ # concrete output options; short-circuit before the `PipeType(...)` coercion, which would raise.
+ return []
pipe_type = PipeType(the_pipe.type)
# Check if the pipe is a PipeCondition
@@ -107,7 +111,6 @@ def _collect_possible_outputs(
| PipeType.PIPE_STRUCTURE
| PipeType.PIPE_BATCH
| PipeType.PIPE_PARALLEL
- | PipeType.PIPE_SIGNATURE
):
return []
diff --git a/pipelex/core/pipes/pipe_abstract.py b/pipelex/core/pipes/pipe_abstract.py
index fdb55e719..359ecc4cc 100644
--- a/pipelex/core/pipes/pipe_abstract.py
+++ b/pipelex/core/pipes/pipe_abstract.py
@@ -14,7 +14,7 @@ from pipelex.core.memory.working_memory import WorkingMemory
from pipelex.core.pipes.exceptions import PipeValidationError, PipeValidationErrorType
from pipelex.core.pipes.inputs.exceptions import PipeRunInputsError
from pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecs
-from pipelex.core.pipes.pipe_blueprint import PipeCategory, PipeType
+from pipelex.core.pipes.pipe_blueprint import PipeCategory, PipeType, valid_pipe_type_tags
from pipelex.core.pipes.pipe_output import PipeOutput
from pipelex.core.pipes.stuff_spec.stuff_spec import StuffSpec
from pipelex.core.pipes.validation import is_variable_satisfied_by_inputs
@@ -70,7 +70,9 @@ class PipeAbstract(ABC, BaseModel):
@property
def is_signature(self) -> bool:
- return PipeCategory(self.pipe_category) is PipeCategory.PIPE_SIGNATURE
+ # Identity by class, not by enum field: the base is never a signature; `PipeSignature`
+ # overrides this to True. (`pipe_category` no longer encodes signature-ness.)
+ return False
def pipe_dependencies(self) -> set[str]:
"""Return the set of pipe codes that this pipe depends on.
@@ -147,21 +149,29 @@ class PipeAbstract(ABC, BaseModel):
@field_validator("type", mode="after")
@classmethod
def validate_pipe_type(cls, value: Any) -> Any:
- if value not in PipeType.value_list():
- msg = f"Invalid pipe type '{value}' for pipe '{cls.code}'. Must be one of: {PipeType.value_list()}"
+ allowed = valid_pipe_type_tags()
+ if value not in allowed:
+ msg = f"Invalid pipe type '{value}'. Must be one of: {allowed}"
raise ValueError(msg)
return value
@field_validator("pipe_category", mode="after")
@classmethod
def validate_pipe_category(cls, value: Any) -> Any:
- if value not in PipeCategory.value_list():
- msg = f"Invalid pipe category '{value}' for pipe '{cls.code}'. Must be one of: {PipeCategory.value_list()}"
+ # A signature carries `pipe_category = None` (no executable category); every executable pipe
+ # pins a `Literal["PipeOperator"|"PipeController"]`, so `None` unambiguously means "signature".
+ if value is not None and value not in PipeCategory.value_list():
+ msg = f"Invalid pipe category '{value}'. Must be one of: {PipeCategory.value_list()}"
raise ValueError(msg)
return value
@model_validator(mode="after")
def validate_pipe_category_based_on_type(self) -> Self:
+ if self.is_signature:
+ # Signatures sit outside the executable taxonomy: `type` is the signature tag (not a
+ # `PipeType`) and `pipe_category` is None, so the type↔category consistency check below
+ # (which coerces `PipeType(self.type)`) does not apply.
+ return self
try:
pipe_type = PipeType(self.type)
except ValueError as exc:
diff --git a/pipelex/core/pipes/pipe_blueprint.py b/pipelex/core/pipes/pipe_blueprint.py
index 7fb4fd1c0..9424c8cb4 100644
--- a/pipelex/core/pipes/pipe_blueprint.py
+++ b/pipelex/core/pipes/pipe_blueprint.py
@@ -10,11 +10,15 @@ from pipelex.core.pipes.validation import validate_input_name
from pipelex.core.pipes.variable_multiplicity import MUTLIPLICITY_PATTERN, PipeVariableMultiplicityError, parse_concept_with_multiplicity
from pipelex.types import Self, StrEnum
+# A signature is NOT an executable pipe kind: it is deliberately absent from `PipeType` and
+# `PipeCategory`. This is the one extra `type` tag the parse-time allowlists admit beyond the
+# executable kinds (a signature blueprint carries `type = "PipeSignature"`, `pipe_category = None`).
+PIPE_SIGNATURE_TYPE_TAG = "PipeSignature"
+
class PipeCategory(StrEnum):
PIPE_OPERATOR = "PipeOperator"
PIPE_CONTROLLER = "PipeController"
- PIPE_SIGNATURE = "PipeSignature"
@classmethod
def value_list(cls) -> list[str]:
@@ -25,7 +29,7 @@ class PipeCategory(StrEnum):
match self:
case PipeCategory.PIPE_CONTROLLER:
return True
- case PipeCategory.PIPE_OPERATOR | PipeCategory.PIPE_SIGNATURE:
+ case PipeCategory.PIPE_OPERATOR:
return False
@classmethod
@@ -51,7 +55,6 @@ class PipeType(StrEnum):
PIPE_CONDITION = "PipeCondition"
PIPE_PARALLEL = "PipeParallel"
PIPE_SEQUENCE = "PipeSequence"
- PIPE_SIGNATURE = "PipeSignature"
@classmethod
def value_list(cls) -> list[str]:
@@ -82,8 +85,15 @@ class PipeType(StrEnum):
return PipeCategory.PIPE_CONTROLLER
case PipeType.PIPE_SEQUENCE:
return PipeCategory.PIPE_CONTROLLER
- case PipeType.PIPE_SIGNATURE:
- return PipeCategory.PIPE_SIGNATURE
+
+
+def valid_pipe_type_tags() -> list[str]:
+ """Every legal `type` string under `[pipe.X]`: the executable `PipeType` kinds plus the signature
+ tag. A signature is not an executable kind (see `PIPE_SIGNATURE_TYPE_TAG`), so it is not a `PipeType`
+ member — but `type = "PipeSignature"` is still a real thing to write, so it belongs in the allowlist.
+ Single source of truth for the three layers (`PipeBlueprint`, `PipeAbstract`, `PipeSpec`) that gate it.
+ """
+ return [*PipeType.value_list(), PIPE_SIGNATURE_TYPE_TAG]
class PipeBlueprint(ABC, BaseModel):
@@ -106,7 +116,9 @@ class PipeBlueprint(ABC, BaseModel):
@property
def is_signature(self) -> bool:
- return PipeCategory(self.pipe_category) is PipeCategory.PIPE_SIGNATURE
+ # Identity by class, not by enum field: the base is never a signature; `PipeSignatureBlueprint`
+ # overrides this to True. (`pipe_category` no longer encodes signature-ness.)
+ return False
@property
def pipe_dependencies(self) -> set[str]:
@@ -135,21 +147,29 @@ class PipeBlueprint(ABC, BaseModel):
@field_validator("type", mode="after")
@classmethod
def validate_pipe_type(cls, value: Any) -> Any:
- if value not in PipeType.value_list():
- msg = f"Invalid pipe type '{value}'. Must be one of: {PipeType.value_list()}"
+ allowed = valid_pipe_type_tags()
+ if value not in allowed:
+ msg = f"Invalid pipe type '{value}'. Must be one of: {allowed}"
raise ValueError(msg)
return value
@field_validator("pipe_category", mode="after")
@classmethod
def validate_pipe_category(cls, value: Any) -> Any:
- if value not in PipeCategory.value_list():
+ # A signature carries `pipe_category = None` (no executable category); every executable pipe
+ # pins a `Literal["PipeOperator"|"PipeController"]`, so `None` unambiguously means "signature".
+ if value is not None and value not in PipeCategory.value_list():
msg = f"Invalid pipe category '{value}'. Must be one of: {PipeCategory.value_list()}"
raise ValueError(msg)
return value
@model_validator(mode="after")
def validate_pipe_category_based_on_type(self) -> Self:
+ if self.is_signature:
+ # Signatures sit outside the executable taxonomy: `type` is the signature tag (not a
+ # `PipeType`) and `pipe_category` is None, so the type↔category consistency check below
+ # (which coerces `PipeType(self.type)`) does not apply.
+ return self
try:
pipe_type = PipeType(self.type)
except ValueError as exc:
diff --git a/pipelex/core/pipes/pipe_factory.py b/pipelex/core/pipes/pipe_factory.py
index ae70f1a8e..4e0a5c86f 100644
--- a/pipelex/core/pipes/pipe_factory.py
+++ b/pipelex/core/pipes/pipe_factory.py
@@ -8,7 +8,7 @@ from pipelex.core.concepts.native.concept_native import NativeConceptCode
from pipelex.core.pipes.exceptions import PipeFactoryError, PipeFactoryErrorType
from pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecs
from pipelex.core.pipes.inputs.input_stuff_specs_factory import InputStuffSpecsFactory
-from pipelex.core.pipes.pipe_blueprint import PipeBlueprint, PipeType
+from pipelex.core.pipes.pipe_blueprint import PipeBlueprint, PipeCategory, PipeType
from pipelex.core.pipes.stuff_spec.exceptions import StuffSpecFactoryError
from pipelex.core.pipes.stuff_spec.stuff_spec import StuffSpec
from pipelex.core.pipes.stuff_spec.stuff_spec_factory import StuffSpecFactory
@@ -102,11 +102,17 @@ class PipeFactory(Generic[PipeAbstractType]):
blueprint=blueprint.inputs or {},
)
- pipe_type = PipeType(blueprint.type)
- pipe_category = pipe_type.category
-
- # The factory class name for that specific type of Pipe is the pipe class name with "Factory" suffix
- factory_class_name = f"{pipe_type.value}Factory"
+ # The factory class name for that specific type of Pipe is the pipe class name with "Factory" suffix.
+ # A signature is outside the executable taxonomy: its `type` ("PipeSignature") is not a `PipeType`
+ # member and it has no category, so resolve the factory by name from the tag and skip the coercion.
+ pipe_category: PipeCategory | None
+ if blueprint.is_signature:
+ pipe_category = None
+ factory_class_name = f"{blueprint.type}Factory" # "PipeSignatureFactory"
+ else:
+ pipe_type = PipeType(blueprint.type)
+ pipe_category = pipe_type.category
+ factory_class_name = f"{pipe_type.value}Factory"
try:
pipe_factory: type[PipeFactoryProtocol[Any, Any]] = get_class_registry().get_required_subclass(
name=factory_class_name,
diff --git a/pipelex/graph/graph_rendering.py b/pipelex/graph/graph_rendering.py
index e796a4bb1..80e25f047 100644
--- a/pipelex/graph/graph_rendering.py
+++ b/pipelex/graph/graph_rendering.py
@@ -11,7 +11,7 @@ from pipelex.config import get_config
from pipelex.graph.graph_config import GraphConfig
from pipelex.graph.graph_factory import GraphOutputs, generate_graph_outputs, save_graph_outputs_to_dir
from pipelex.graph.graphspec import GraphSpec
-from pipelex.pipe_run.dry_run_pipeline import dry_run_pipeline
+from pipelex.pipeline.dry_run_pipeline import dry_run_pipeline
from pipelex.tools.misc.chart_utils import FlowchartDirection
from pipelex.types import StrEnum
diff --git a/pipelex/libraries/collision_messages.py b/pipelex/libraries/collision_messages.py
new file mode 100644
index 000000000..69a437102
--- /dev/null
+++ b/pipelex/libraries/collision_messages.py
@@ -0,0 +1,30 @@
+def duplicate_ref_msg(
+ *,
+ ref_kind: str,
+ ref: str,
+ existing_source: str | None,
+ incoming_source: str | None,
+) -> str:
+ """Build the error message for a duplicate concept/pipe declaration in a merged library.
+
+ `ref_kind` is the singular noun ("concept" or "pipe"); the plural is formed by appending
+ "s". Whether the two declarations live in the same file or different files is derived from
+ the two sources, so callers do not pass a separate flag.
+
+ Args:
+ ref_kind: Singular noun for the kind of reference ("concept" or "pipe").
+ ref: The fully qualified ref that is declared twice (e.g. "scoring.compute_score").
+ existing_source: Source file of the already-seen declaration, or None if unknown.
+ incoming_source: Source file of the colliding declaration, or None if unknown.
+
+ Returns:
+ A human-readable error message naming the offending ref and source files.
+ """
+ noun = ref_kind.capitalize()
+ if existing_source is not None and existing_source == incoming_source:
+ return f"{noun} '{ref}' is declared twice in the same bundle file: '{existing_source}'. Please remove the duplicate declaration."
+ return (
+ f"{noun} '{ref}' is declared in two different bundle files: "
+ f"'{existing_source or 'unknown'}' and '{incoming_source or 'unknown'}'. "
+ f"Please remove one of the declarations or rename one of the {ref_kind}s."
+ )
diff --git a/pipelex/libraries/concept/exceptions.py b/pipelex/libraries/concept/exceptions.py
index 01972b31c..f0d412c31 100644
--- a/pipelex/libraries/concept/exceptions.py
+++ b/pipelex/libraries/concept/exceptions.py
@@ -1,5 +1,5 @@
-from pipelex.base_exceptions import PipelexError
+from pipelex.libraries.exceptions import LibraryError
-class ConceptLibraryError(PipelexError):
+class ConceptLibraryError(LibraryError):
pass
diff --git a/pipelex/libraries/concept_reference_validation.py b/pipelex/libraries/concept_reference_validation.py
new file mode 100644
index 000000000..4d76f16c6
--- /dev/null
+++ b/pipelex/libraries/concept_reference_validation.py
@@ -0,0 +1,78 @@
+from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
+from pipelex.core.concepts.concept_factory import ConceptFactory
+from pipelex.core.concepts.native.concept_native import NativeConceptCode
+from pipelex.core.qualified_ref import QualifiedRef
+from pipelex.libraries.concept.exceptions import ConceptLibraryError
+
+
+def validate_concept_references_in_blueprints(
+ blueprints: list[PipelexBundleBlueprint],
+ already_loaded_concept_refs: set[str] | None = None,
+) -> None:
+ """Validate that every same-domain concept reference resolves against the merged library.
+
+ Runs after the per-bundle structural merge, so a concept declared in one file can be
+ referenced by bare code from a sibling file of the same domain — whether that sibling is in
+ the same load batch or was loaded by a prior batch into the same library. References owned by
+ another layer are deferred: cross-package refs ('alias->...') resolve at dependency-load time,
+ and external-domain refs resolve when their own domain's bundles load. Native concepts are
+ always available. Every unresolved reference is accumulated and reported together so the
+ author sees all of them at once.
+
+ Args:
+ blueprints: The parsed bundles whose concept references are being checked. Their declared
+ concepts form the batch's own declarations.
+ already_loaded_concept_refs: Fully qualified concept refs already present in the live
+ library from prior load batches (e.g. concepts loaded via a ``-L`` library directory).
+ Adds the cross-batch context so a concept declared earlier still resolves. Native and
+ cross-package entries in this set never satisfy a same-domain reference, so passing the
+ whole library is harmless.
+
+ Raises:
+ ConceptLibraryError: If any same-domain/bare reference is neither declared (in this batch
+ or already in the library) nor native.
+ """
+ # The batch's own declarations drive the error message, so the author sees exactly what these
+ # files declare. The membership test additionally honors concepts loaded by prior batches.
+ batch_declared_concept_refs: set[str] = {
+ ConceptFactory.make_concept_ref_with_domain(domain_code=blueprint.domain, concept_code=concept_code)
+ for blueprint in blueprints
+ if blueprint.concept
+ for concept_code in blueprint.concept
+ }
+ resolvable_concept_refs = batch_declared_concept_refs | (already_loaded_concept_refs or set())
+
+ native_codes = {native.value for native in NativeConceptCode.values_list()}
+ undeclared: list[str] = []
+ for blueprint in blueprints:
+ domain_code = blueprint.domain
+ source = blueprint.source
+ for concept_ref_or_code, context in blueprint.collect_concept_references():
+ # Cross-package references are resolved at dependency-load time.
+ if QualifiedRef.has_cross_package_prefix(concept_ref_or_code):
+ continue
+ ref = QualifiedRef.parse(concept_ref_or_code)
+ # External-domain references resolve when their own domain's bundles load.
+ if ref.is_external_to(domain_code):
+ continue
+ # Native concepts are always available. Use the canonical check (bare `Text` or
+ # `native.Text` only) — not a bare local-code match — so a same-domain ref that merely
+ # *shares* a native local code (e.g. `mydomain.Text`) is NOT mistaken for native and still
+ # gets the membership check. This matches how the concept actually resolves
+ # (ConceptLibrary.get_required_concept_from_concept_ref_or_code) and contract_match.
+ if NativeConceptCode.is_native_concept_ref_or_code(concept_ref_or_code=concept_ref_or_code):
+ continue
+ concept_ref = ConceptFactory.make_concept_ref_with_domain(domain_code=domain_code, concept_code=ref.local_code)
+ if concept_ref not in resolvable_concept_refs:
+ undeclared.append(f"'{concept_ref_or_code}' in {context} is not declared in domain '{domain_code}' (source: '{source or 'unknown'}')")
+
+ if undeclared:
+ declared_list = sorted(batch_declared_concept_refs) if batch_declared_concept_refs else "(none)"
+ msg = (
+ "The following concept references could not be resolved against the merged library "
+ "and are not native concepts:\n - "
+ + "\n - ".join(undeclared)
+ + f"\nDeclared concepts: {declared_list}."
+ + f"\nNative concepts: {sorted(native_codes)}."
+ )
+ raise ConceptLibraryError(msg)
diff --git a/pipelex/libraries/contract_match.py b/pipelex/libraries/contract_match.py
new file mode 100644
index 000000000..5cc29c87c
--- /dev/null
+++ b/pipelex/libraries/contract_match.py
@@ -0,0 +1,71 @@
+"""Normalized contract conformance for the library merge.
+
+When a forward-declared header (a ``PipeSignature``) and its concrete definition collide in the
+library merge, their contracts must agree. The two declarations may spell the same concept
+differently — a header's bare ``Brief`` and a definition's domain-qualified ``thisdomain.Brief``
+denote the *same* concept, as do native ``Text`` and ``native.Text``. A raw-string comparison
+would reject these as a false mismatch.
+
+``contracts_match`` normalizes each concept reference to a canonical identity *string* before
+comparing, so equivalent spellings reconcile. This is normalization for *identity* only — it is NOT
+refinement substitutability (covariant output / contravariant inputs); that stays the dry-run's job,
+which re-validates the parent against the concrete's real contract.
+"""
+
+import re
+
+from pipelex.core.concepts.concept_factory import ConceptFactory
+from pipelex.core.concepts.native.concept_native import NativeConceptCode
+from pipelex.core.pipes.pipe_blueprint import PipeBlueprint
+from pipelex.core.pipes.variable_multiplicity import MUTLIPLICITY_PATTERN
+from pipelex.core.qualified_ref import QualifiedRef
+
+
+def _canonical_concept_spec(spec: str, *, domain_code: str) -> str:
+ """Normalize a raw concept spec to a canonical identity string.
+
+ The multiplicity suffix is preserved *verbatim as text* (``""`` / ``"[]"`` / ``"[N]"``), so
+ ``Brief[]`` (variable-length list) and ``Brief[1]`` (exactly one item) stay distinct. Comparing
+ the *parsed* multiplicity instead would conflate them: ``parse_concept_with_multiplicity`` maps
+ ``[]`` to ``True`` and ``[1]`` to ``int 1``, and Python evaluates ``True == 1`` as true. Keeping
+ the suffix as text also means a ``[0]`` spec compares as a literal rather than raising.
+
+ The concept part is canonicalized so equivalent spellings collapse to one identity:
+
+ - native (``Text`` or ``native.Text``) -> the bare native code (``Text``);
+ - external-domain qualified -> kept verbatim (belongs to another domain);
+ - bare / same-domain -> qualified to ``domain.Code`` so a header's ``Brief`` and a definition's
+ ``thisdomain.Brief`` compare equal.
+
+ A spec the multiplicity pattern does not cover (e.g. a cross-package ``alias->...`` ref, which
+ cannot appear in a blueprint's ``inputs``/``output`` but is handled defensively) is returned
+ verbatim — it is already unambiguous.
+ """
+ match = re.match(MUTLIPLICITY_PATTERN, spec)
+ if match is None:
+ return spec
+ concept_ref_or_code = match.group(1)
+ bracket_content = match.group(2) # None -> no brackets; "" -> "[]"; digits -> "[N]"
+ suffix = "" if bracket_content is None else f"[{bracket_content}]"
+
+ if NativeConceptCode.is_native_concept_ref_or_code(concept_ref_or_code):
+ return f"{QualifiedRef.parse(concept_ref_or_code).local_code}{suffix}"
+ ref = QualifiedRef.parse(concept_ref_or_code)
+ if ref.is_external_to(domain_code):
+ return f"{concept_ref_or_code}{suffix}"
+ return f"{ConceptFactory.make_concept_ref_with_domain(domain_code=domain_code, concept_code=ref.local_code)}{suffix}"
+
+
+def contracts_match(existing: PipeBlueprint, incoming: PipeBlueprint, *, domain_code: str) -> bool:
+ """True if two declarations of the same pipe denote the same contract after normalization.
+
+ Both declarations share ``domain_code`` (they collided on the same qualified ``pipe_ref``), so
+ same-domain bare and qualified spellings of a concept canonicalize to one identity. A missing
+ ``inputs`` and an empty ``inputs`` are treated alike. Input *names* must match exactly — they are
+ variable names, not concepts.
+ """
+ existing_inputs = {name: _canonical_concept_spec(spec, domain_code=domain_code) for name, spec in (existing.inputs or {}).items()}
+ incoming_inputs = {name: _canonical_concept_spec(spec, domain_code=domain_code) for name, spec in (incoming.inputs or {}).items()}
+ if existing_inputs != incoming_inputs:
+ return False
+ return _canonical_concept_spec(existing.output, domain_code=domain_code) == _canonical_concept_spec(incoming.output, domain_code=domain_code)
diff --git a/pipelex/libraries/domain/domain_library.py b/pipelex/libraries/domain/domain_library.py
index f4eee4c74..1f8cc2492 100644
--- a/pipelex/libraries/domain/domain_library.py
+++ b/pipelex/libraries/domain/domain_library.py
@@ -1,9 +1,9 @@
from pydantic import RootModel
from typing_extensions import override
-from pipelex import log
from pipelex.core.domains.domain import Domain
from pipelex.libraries.domain.domain_library_abstract import DomainLibraryAbstract
+from pipelex.libraries.domain.domain_metadata_merge import merge_domain_metadata_field
from pipelex.libraries.domain.exceptions import DomainLibraryError
from pipelex.types import Self
@@ -31,21 +31,28 @@ class DomainLibrary(RootModel[DomainLibraryRoot], DomainLibraryAbstract):
return self.root.get(domain_code)
def add_domain(self, domain: Domain):
- # TODO: resolve domain metadata conflicts properly — currently first-write-wins with a warning.
- # The system_prompt field is used as a PipeLLM fallback; it should be inlined at pipe factory time
- # before LibraryCrate construction so domain-level system_prompt becomes unnecessary.
+ # TODO: the system_prompt field is used as a PipeLLM fallback; it should be inlined at pipe factory
+ # time before LibraryCrate construction so domain-level system_prompt becomes unnecessary.
domain_code = domain.code
if domain_code in self.root:
+ # Fold the incoming domain's metadata into the established one: an omitted field defers to
+ # whichever same-domain file declared it, so the merge is order-independent and quiet on
+ # omissions; only a genuine double-declaration of two different non-empty values warns.
existing = self.root[domain_code]
- if existing.description != domain.description:
- log.warning(
- f"Domain '{domain_code}' declared with different descriptions: "
- f"'{existing.description}' vs '{domain.description}'. Keeping the first.",
- )
- if existing.system_prompt != domain.system_prompt:
- log.warning(
- f"Domain '{domain_code}' declared with different system_prompts. Keeping the first.",
- )
+ existing.description = merge_domain_metadata_field(
+ domain_code=domain_code,
+ field_label="description",
+ established=existing.description,
+ incoming=domain.description,
+ show_values_on_conflict=True,
+ )
+ existing.system_prompt = merge_domain_metadata_field(
+ domain_code=domain_code,
+ field_label="system_prompt",
+ established=existing.system_prompt,
+ incoming=domain.system_prompt,
+ show_values_on_conflict=False,
+ )
return
self.root[domain_code] = domain
diff --git a/pipelex/libraries/domain/domain_metadata_merge.py b/pipelex/libraries/domain/domain_metadata_merge.py
new file mode 100644
index 000000000..650569baf
--- /dev/null
+++ b/pipelex/libraries/domain/domain_metadata_merge.py
@@ -0,0 +1,53 @@
+from pipelex import log
+
+
+def merge_domain_metadata_field(
+ *,
+ domain_code: str,
+ field_label: str,
+ established: str | None,
+ incoming: str | None,
+ show_values_on_conflict: bool,
+) -> str | None:
+ """Order-independent, omission-quiet merge of one domain-metadata field across same-domain files.
+
+ Under the additive multi-file model a same-domain library is authored as one root file that carries
+ the full domain header (`description`, `system_prompt`, ...) and N membership-only sibling files that
+ declare only `domain = "<same_domain>"`. Those siblings omit `description` / `system_prompt`, and an
+ omitted value must contribute *no opinion*: it neither overrides an established non-empty value nor
+ warns. Whichever file declares the value therefore wins regardless of file load order (which, for a
+ `-L` directory, is filesystem sort order, not authoring intent).
+
+ Per field:
+
+ - established empty/None + incoming non-empty -> take incoming, no warning (root may arrive after a sibling).
+ - established non-empty + incoming empty/None -> keep established, no warning (sibling defers to root).
+ - both non-empty and equal -> keep, no warning.
+ - both non-empty and different -> keep the first, **warn** (a genuine double-declaration the author should resolve).
+
+ Args:
+ domain_code: The domain these values belong to (used in the warning message).
+ field_label: Singular human-readable field name used in the warning, pluralized with "s"
+ (e.g. "description" -> "descriptions", "system_prompt" -> "system_prompts").
+ established: The value already merged for this domain (may be empty/None).
+ incoming: The value from the file being merged now (may be empty/None).
+ show_values_on_conflict: Whether to include both values in the conflict warning. True for short
+ fields (description); False for long ones (system_prompt) whose contents would flood the log.
+
+ Returns:
+ The merged value (the established value wins on a genuine conflict).
+ """
+ if not incoming:
+ return established
+ if not established:
+ return incoming
+ if established != incoming:
+ if show_values_on_conflict:
+ log.warning(
+ f"Domain '{domain_code}' declared with different {field_label}s: '{established}' vs '{incoming}'. Keeping the first.",
+ )
+ else:
+ log.warning(
+ f"Domain '{domain_code}' declared with different {field_label}s. Keeping the first.",
+ )
+ return established
diff --git a/pipelex/libraries/library_crate_factory.py b/pipelex/libraries/library_crate_factory.py
index 22b4c51dc..f4bb65583 100644
--- a/pipelex/libraries/library_crate_factory.py
+++ b/pipelex/libraries/library_crate_factory.py
@@ -1,11 +1,13 @@
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, NamedTuple
-from pipelex import log
from pipelex.core.bundles.pipelex_bundle_blueprint import PipeBlueprintUnion, PipelexBundleBlueprint
from pipelex.core.concepts.concept_factory import ConceptFactory
from pipelex.core.domains.domain_blueprint import DomainBlueprint
from pipelex.core.pipes.pipe_factory import PipeFactory
+from pipelex.libraries.collision_messages import duplicate_ref_msg
from pipelex.libraries.concept.exceptions import ConceptLibraryError
+from pipelex.libraries.contract_match import contracts_match
+from pipelex.libraries.domain.domain_metadata_merge import merge_domain_metadata_field
from pipelex.libraries.library_crate import LibraryCrate
from pipelex.libraries.pipe.exceptions import PipeLibraryError
@@ -13,6 +15,17 @@ if TYPE_CHECKING:
from pipelex.core.concepts.concept_blueprint import ConceptBlueprint
+class PipeDeclaration(NamedTuple):
+ """One declaration of a pipe: its blueprint paired with the bundle file it came from.
+
+ Used by the library merge to reconcile two declarations of the same pipe_ref while keeping
+ the winning blueprint and its source together (so source_map always follows the winner).
+ """
+
+ blueprint: PipeBlueprintUnion
+ source: str | None
+
+
class LibraryCrateFactory:
"""Builds a LibraryCrate from parsed bundle blueprints."""
@@ -27,7 +40,7 @@ class LibraryCrateFactory:
1. Qualify concept codes with the bundle's domain -> concept_ref keys
2. Qualify pipe codes with the bundle's domain -> pipe_ref keys
3. Preserve string-described concepts as-is (no normalization to ConceptBlueprint)
- 4. Collect domain metadata (first-write-wins per domain code)
+ 4. Collect domain metadata (order-independent, omission-quiet merge per domain code)
5. Track source file for each concept_ref and pipe_ref
6. Detect duplicate refs across bundles (raise ConceptLibraryError / PipeLibraryError)
7. Compute SHA-256 fingerprint
@@ -47,7 +60,7 @@ class LibraryCrateFactory:
domain_code = blueprint.domain
source = blueprint.source
- # Domain metadata: first-write-wins
+ # Domain metadata: order-independent, omission-quiet merge (see merge_domain_metadata_field).
if domain_code not in domains:
domains[domain_code] = DomainBlueprint(
source=source,
@@ -57,36 +70,42 @@ class LibraryCrateFactory:
main_pipe=blueprint.main_pipe,
)
else:
+ # Fold this file's domain metadata into the established blueprint: an omitted field
+ # defers to whichever same-domain file declared it, so the root's header wins over
+ # membership-only siblings regardless of load order. `main_pipe` is intentionally not
+ # merged — it is dropped when the runtime Domain is built, so first-write-wins is inert.
existing = domains[domain_code]
- new_description = blueprint.description or ""
- if existing.description != new_description:
- log.warning(
- f"Domain '{domain_code}' declared with different descriptions: "
- f"'{existing.description}' vs '{new_description}'. Keeping the first.",
- )
- if existing.system_prompt != blueprint.system_prompt:
- log.warning(
- f"Domain '{domain_code}' declared with different system_prompts. Keeping the first.",
+ existing.description = (
+ merge_domain_metadata_field(
+ domain_code=domain_code,
+ field_label="description",
+ established=existing.description,
+ incoming=blueprint.description,
+ show_values_on_conflict=True,
)
+ or ""
+ )
+ existing.system_prompt = merge_domain_metadata_field(
+ domain_code=domain_code,
+ field_label="system_prompt",
+ established=existing.system_prompt,
+ incoming=blueprint.system_prompt,
+ show_values_on_conflict=False,
+ )
# Concepts
if blueprint.concept is not None:
for concept_code, value in blueprint.concept.items():
concept_ref = ConceptFactory.make_concept_ref_with_domain(domain_code=domain_code, concept_code=concept_code)
if concept_ref in concepts:
- existing_source = source_map.get(concept_ref)
- if existing_source is not None and existing_source == source:
- msg = (
- f"Concept '{concept_ref}' is declared twice in the same bundle file: '{existing_source}'. "
- "Please remove the duplicate declaration."
+ raise ConceptLibraryError(
+ duplicate_ref_msg(
+ ref_kind="concept",
+ ref=concept_ref,
+ existing_source=source_map.get(concept_ref),
+ incoming_source=source,
)
- else:
- msg = (
- f"Concept '{concept_ref}' is declared in two different bundle files: "
- f"'{existing_source or 'unknown'}' and '{source or 'unknown'}'. "
- "Please remove one of the declarations or rename one of the concepts."
- )
- raise ConceptLibraryError(msg)
+ )
concepts[concept_ref] = value
if source:
source_map[concept_ref] = source
@@ -96,23 +115,28 @@ class LibraryCrateFactory:
for pipe_code, pipe_blueprint in blueprint.pipe.items():
pipe_ref = PipeFactory.make_pipe_ref_with_domain(domain_code=domain_code, pipe_code=pipe_code)
if pipe_ref in pipes:
- existing_source = source_map.get(pipe_ref)
- if existing_source is not None and existing_source == source:
- msg = (
- f"Pipe '{pipe_ref}' is declared twice in the same bundle file: '{existing_source}'. "
- "Please remove the duplicate declaration."
- )
+ winner = cls._reconcile_pipe_collision(
+ pipe_ref=pipe_ref,
+ existing=PipeDeclaration(blueprint=pipes[pipe_ref], source=source_map.get(pipe_ref)),
+ incoming=PipeDeclaration(blueprint=pipe_blueprint, source=source),
+ domain_code=domain_code,
+ )
+ # source_map must always track the winner's file (or drop the entry when
+ # the winner has no source) so it never points at the discarded declaration.
+ pipes[pipe_ref] = winner.blueprint
+ if winner.source:
+ source_map[pipe_ref] = winner.source
else:
- msg = (
- f"Pipe '{pipe_ref}' is declared in two different bundle files: "
- f"'{existing_source or 'unknown'}' and '{source or 'unknown'}'. "
- "Please remove one of the declarations or rename one of the pipes."
- )
- raise PipeLibraryError(msg)
+ source_map.pop(pipe_ref, None)
+ continue
pipes[pipe_ref] = pipe_blueprint
if source:
source_map[pipe_ref] = source
+ # Concept-reference validation is NOT done here: this factory performs a world-agnostic
+ # structural merge. Same-domain concept references resolve against the live library (which
+ # may hold concepts from prior load batches), so that check lives in the loader
+ # (`LibraryManager.load_from_blueprints` -> `validate_concept_references_in_blueprints`).
fingerprint = LibraryCrate.compute_fingerprint_from_content(concepts=concepts, pipes=pipes)
return LibraryCrate(
concepts=concepts,
@@ -121,3 +145,65 @@ class LibraryCrateFactory:
source_map=source_map,
fingerprint=fingerprint,
)
+
+ @classmethod
+ def _reconcile_pipe_collision(
+ cls,
+ pipe_ref: str,
+ existing: PipeDeclaration,
+ incoming: PipeDeclaration,
+ domain_code: str,
+ ) -> PipeDeclaration:
+ """Resolve two declarations of the same pipe_ref into a single winning declaration.
+
+ A PipeSignature is a forward declaration ("header"); a concrete pipe is its
+ definition. A concrete beats a signature, and the contracts must agree whenever a
+ signature is involved. Two concrete pipes are a genuine duplicate (error). Two
+ matching signatures collapse to one via a deterministic, load-order-independent
+ tie-break. Returns the winning (blueprint, source) declaration.
+
+ Both declarations share ``domain_code`` (they collided on the same qualified ``pipe_ref``),
+ which the contract check uses to normalize bare and same-domain-qualified concept spellings
+ to one identity.
+ """
+ existing_is_signature = existing.blueprint.is_signature
+ incoming_is_signature = incoming.blueprint.is_signature
+
+ # Both concrete -> genuine duplicate (unchanged behavior).
+ if not existing_is_signature and not incoming_is_signature:
+ raise PipeLibraryError(
+ duplicate_ref_msg(
+ ref_kind="pipe",
+ ref=pipe_ref,
+ existing_source=existing.source,
+ incoming_source=incoming.source,
+ )
+ )
+
+ # At least one is a signature: the declarations' contracts must match (normalized identity).
+ if not contracts_match(existing.blueprint, incoming.blueprint, domain_code=domain_code):
+ raise PipeLibraryError(cls._contract_mismatch_msg(pipe_ref=pipe_ref, existing=existing, incoming=incoming))
+
+ # A concrete definition beats a forward declaration.
+ if existing_is_signature and not incoming_is_signature:
+ return incoming
+ if incoming_is_signature and not existing_is_signature:
+ return existing
+
+ # Two signatures with matching contracts: pick a deterministic winner so the merged
+ # crate (and therefore its fingerprint) does not depend on bundle load order.
+ return min(existing, incoming, key=cls._declaration_sort_key)
+
+ @staticmethod
+ def _declaration_sort_key(declaration: PipeDeclaration) -> tuple[str, str]:
+ """Order-independent key for tie-breaking two pipe signatures with matching contracts."""
+ return (declaration.blueprint.model_dump_json(), declaration.source or "")
+
+ @staticmethod
+ def _contract_mismatch_msg(pipe_ref: str, existing: PipeDeclaration, incoming: PipeDeclaration) -> str:
+ return (
+ f"Pipe '{pipe_ref}' is declared with mismatched contracts: "
+ f"'{existing.source or 'unknown'}' has inputs={existing.blueprint.inputs or {}}, output='{existing.blueprint.output}' "
+ f"while '{incoming.source or 'unknown'}' has inputs={incoming.blueprint.inputs or {}}, output='{incoming.blueprint.output}'. "
+ "A forward declaration (PipeSignature) and the matching declaration must agree on inputs and output."
+ )
diff --git a/pipelex/libraries/library_manager.py b/pipelex/libraries/library_manager.py
index 40bd4c535..abedeb300 100644
--- a/pipelex/libraries/library_manager.py
+++ b/pipelex/libraries/library_manager.py
@@ -29,7 +29,9 @@ from pipelex.core.qualified_ref import QualifiedRef
from pipelex.core.stuffs.structured_content import StructuredContent
from pipelex.core.validation import report_validation_error
from pipelex.hub import get_class_registry, get_current_library
+from pipelex.libraries.collision_messages import duplicate_ref_msg
from pipelex.libraries.concept.exceptions import ConceptLibraryError
+from pipelex.libraries.concept_reference_validation import validate_concept_references_in_blueprints
from pipelex.libraries.exceptions import (
LibraryError,
LibraryLoadingError,
@@ -400,7 +402,7 @@ class LibraryManager(LibraryManagerAbstract):
# Load MTHDS files as concepts only (no pipes)
log.debug(f"Loading concepts only from MTHDS files: {[str(p) for p in valid_mthds_paths]}")
library = self.get_library(library_id=library_id)
- all_concepts: list[Concept] = []
+ all_blueprints: list[PipelexBundleBlueprint] = []
for mthds_path in valid_mthds_paths:
# Track loaded path (resolve if possible)
try:
@@ -409,11 +411,13 @@ class LibraryManager(LibraryManagerAbstract):
resolved_path = mthds_path
library.loaded_mthds_paths.append(resolved_path)
- blueprint = PipelexInterpreter.make_pipelex_bundle_blueprint(bundle_path=mthds_path)
- concepts = self.load_concepts_only_from_blueprints(library_id=library_id, blueprints=[blueprint])
- all_concepts.extend(concepts)
+ all_blueprints.append(PipelexInterpreter.make_pipelex_bundle_blueprint(bundle_path=mthds_path))
- return all_concepts
+ # Load all sibling files as a single batch so same-domain concept references resolve against
+ # the merged set regardless of directory iteration order — mirroring load_concepts_only_from_directory.
+ # A one-file-at-a-time loop would make a valid additive concepts library fail based on file order
+ # (e.g. a file whose structure references a concept declared in a sibling that loads later).
+ return self.load_concepts_only_from_blueprints(library_id=library_id, blueprints=all_blueprints)
@override
def load_from_crate(self, library_id: str, crate: LibraryCrate) -> list[PipeAbstract]:
@@ -459,9 +463,18 @@ class LibraryManager(LibraryManagerAbstract):
# Detect cycles in concept references (A -> B -> A is forbidden)
self._detect_concept_cycles(all_concepts)
- # Precompute domain -> concept local codes mapping (avoids O(N*M) re-parsing per pipe)
+ # Precompute domain -> concept local codes mapping (avoids O(N*M) re-parsing per pipe).
+ # Sourced from the LIVE library (native concepts + concepts from prior load batches + this
+ # batch's concepts, already added above), not just this crate — so a pipe can reference, by
+ # bare code, a same-domain concept that a prior batch (e.g. a -L library directory) loaded.
+ # This is the pipe-factory counterpart to the loader's cross-batch concept-reference check:
+ # without it, that check would pass a bare cross-batch ref only for the factory to reject
+ # it. Cross-package aliased entries ('alias->...') are skipped — they resolve through the
+ # dependency resolver, not by bare code, and would not parse as a concept ref.
domain_concept_codes: dict[str, list[str]] = {}
- for concept_ref in crate.concepts:
+ for concept_ref in library.concept_library.root:
+ if QualifiedRef.has_cross_package_prefix(concept_ref):
+ continue
parsed_concept = QualifiedRef.parse_concept_ref(raw=concept_ref)
if parsed_concept.domain_path is not None:
domain_concept_codes.setdefault(parsed_concept.domain_path, []).append(parsed_concept.local_code)
@@ -527,6 +540,17 @@ class LibraryManager(LibraryManagerAbstract):
# Build the crate (merges, qualifies, detects duplicates)
crate = LibraryCrateFactory.make_from_blueprints(blueprints=blueprints)
+ # Validate same-domain concept references against the live library: the concepts declared
+ # in this batch plus those already loaded by prior batches (e.g. via a -L library
+ # directory). This is done in the loader, not the crate factory, so a bare concept ref can
+ # resolve across separate load batches into the same library. The batch's own concepts are
+ # not in the library yet (load_from_crate adds them below), so they come from `blueprints`.
+ library = self.get_library(library_id=library_id)
+ validate_concept_references_in_blueprints(
+ blueprints=blueprints,
+ already_loaded_concept_refs=set(library.concept_library.root.keys()),
+ )
+
# Load from crate (domains, concepts, pipes, validation)
return self.load_from_crate(library_id=library_id, crate=crate)
@@ -566,6 +590,16 @@ class LibraryManager(LibraryManagerAbstract):
all_domains.append(domain)
library.domain_library.add_domains(domains=all_domains)
+ # Validate same-domain concept references against the live library before adding this batch's
+ # concepts — mirrors load_from_blueprints so the lightweight concepts-only path rejects a
+ # dangling concept_ref / item_concept_ref instead of leaving an invalid schema behind. The
+ # batch's own concepts come from `blueprints` (not yet in the library); concepts loaded by
+ # prior batches resolve via already_loaded_concept_refs.
+ validate_concept_references_in_blueprints(
+ blueprints=blueprints,
+ already_loaded_concept_refs=set(library.concept_library.root.keys()),
+ )
+
# Load concepts (forward references resolved after all are loaded)
all_concepts = self._load_concepts_from_blueprints(blueprints)
library.concept_library.add_concepts(concepts=all_concepts)
@@ -613,18 +647,14 @@ class LibraryManager(LibraryManagerAbstract):
# Detect duplicate concept declarations across different bundles in the same library
if concept_ref in concept_source_in_this_load:
existing_source = concept_source_in_this_load[concept_ref]
- if existing_source == new_source:
- msg = (
- f"Concept '{concept_ref}' is declared twice in the same bundle file: '{existing_source}'. "
- "Please remove the duplicate declaration."
- )
- else:
- msg = (
- f"Concept '{concept_ref}' is declared in two different bundle files: "
- f"'{existing_source}' and '{new_source}'. "
- "Please remove one of the declarations or rename one of the concepts."
+ raise ConceptLibraryError(
+ duplicate_ref_msg(
+ ref_kind="concept",
+ ref=concept_ref,
+ existing_source=str(existing_source) if existing_source else None,
+ incoming_source=str(new_source) if new_source else None,
)
- raise ConceptLibraryError(msg)
+ )
concept_source_in_this_load[concept_ref] = new_source
ref_to_entry[concept_ref] = (
blueprint.domain,
@@ -794,6 +824,14 @@ class LibraryManager(LibraryManagerAbstract):
raise LibraryError(
message=msg,
) from validation_error
+ except (ConceptLibraryError, PipeLibraryError) as ref_error:
+ # Merge-time reference errors (undeclared cross-file concept refs, signature/concrete
+ # contract mismatches, duplicate refs) carry no structured validation payload — unlike
+ # LibraryLoadingError, which must propagate intact so its aggregated errors survive.
+ # Add the batch's file list as context, then let the outer
+ # _translate_to_validate_bundle_error LibraryError arm shape it into a ValidateBundleError.
+ msg = f"Could not load blueprints from {[str(pth) for pth in valid_mthds_paths]} because of: {ref_error}"
+ raise type(ref_error)(msg) from ref_error
def _warn_if_mthds_version_unsatisfied(
self,
@@ -973,6 +1011,15 @@ class LibraryManager(LibraryManagerAbstract):
package_address=resolved_dep.address,
)
+ # Merge the dependency's files into one crate so a multi-file package reconciles exactly like
+ # the main load path: a PipeSignature header and its concrete sibling collapse to a single
+ # pipe (concrete wins), and genuine duplicates / signature-concrete contract mismatches raise
+ # here rather than colliding later in add_new_pipe (which the per-pipe handler below would
+ # swallow as a warning, silently dropping one declaration). Same-domain concept references are
+ # validated across the merged files; cross-package and external-domain refs are deferred.
+ crate = LibraryCrateFactory.make_from_blueprints(blueprints=dep_blueprints)
+ validate_concept_references_in_blueprints(blueprints=dep_blueprints)
+
# Create isolated child library for this dependency
child_library = LibraryFactory.make_empty()
@@ -1038,27 +1085,37 @@ class LibraryManager(LibraryManagerAbstract):
library.concept_library.add_new_concept(concept=concept)
temp_concept_refs.append(concept.concept_ref)
- # Load exported pipes into child library, ensuring temp concepts are
- # always cleaned up even if an unexpected exception occurs
+ # Per-domain concept codes let a pipe resolve a same-domain concept by bare code, mirroring
+ # load_from_crate. A multi-file dependency may span several domains.
+ domain_concept_codes: dict[str, list[str]] = {}
+ for concept in dep_concepts:
+ parsed_concept = QualifiedRef.parse_concept_ref(raw=concept.concept_ref)
+ if parsed_concept.domain_path is not None:
+ domain_concept_codes.setdefault(parsed_concept.domain_path, []).append(parsed_concept.local_code)
+
+ # Load exported pipes (reconciled by the crate) into child library, ensuring temp concepts
+ # are always cleaned up even if an unexpected exception occurs
try:
- concept_codes = [concept.code for concept in dep_concepts]
- for blueprint in dep_blueprints:
- if blueprint.pipe is None:
+ for pipe_ref, pipe_blueprint in crate.pipes.items():
+ parsed_pipe = QualifiedRef.parse_pipe_ref(raw=pipe_ref)
+ if parsed_pipe.domain_path is None:
+ msg = f"Crate pipe_ref '{pipe_ref}' must be domain-qualified"
+ raise PipeLibraryError(msg)
+ domain_code = parsed_pipe.domain_path
+ pipe_code = parsed_pipe.local_code
+ # If manifest has exports, only load exported pipes
+ if has_exports and pipe_code not in all_exported:
continue
- for pipe_code, pipe_blueprint in blueprint.pipe.items():
- # If manifest has exports, only load exported pipes
- if has_exports and pipe_code not in all_exported:
- continue
- try:
- pipe = PipeFactory[PipeAbstract].make_from_blueprint(
- domain_code=blueprint.domain,
- pipe_code=pipe_code,
- blueprint=pipe_blueprint,
- concept_codes_from_the_same_domain=concept_codes,
- )
- child_library.pipe_library.add_new_pipe(pipe=pipe)
- except (PipeLibraryError, ValidationError) as exc:
- log.warning(f"Could not load dependency '{alias}' pipe '{pipe_code}': {exc}")
+ try:
+ pipe = PipeFactory[PipeAbstract].make_from_blueprint(
+ domain_code=domain_code,
+ pipe_code=pipe_code,
+ blueprint=pipe_blueprint,
+ concept_codes_from_the_same_domain=domain_concept_codes.get(domain_code, []),
+ )
+ child_library.pipe_library.add_new_pipe(pipe=pipe)
+ except ValidationError as exc:
+ log.warning(f"Could not load dependency '{alias}' pipe '{pipe_code}': {exc}")
finally:
# Remove temporary concept entries from main library
library.concept_library.remove_concepts_by_concept_refs(concept_refs=temp_concept_refs)
diff --git a/pipelex/libraries/pipe/exceptions.py b/pipelex/libraries/pipe/exceptions.py
index b463b893b..96c4b90f4 100644
--- a/pipelex/libraries/pipe/exceptions.py
+++ b/pipelex/libraries/pipe/exceptions.py
@@ -1,7 +1,7 @@
-from pipelex.base_exceptions import PipelexError
+from pipelex.libraries.exceptions import LibraryError
-class PipeLibraryError(PipelexError):
+class PipeLibraryError(LibraryError):
pass
diff --git a/pipelex/pipe_run/dry_run_pipeline.py b/pipelex/pipe_run/dry_run_in_process.py
similarity index 54%
rename from pipelex/pipe_run/dry_run_pipeline.py
rename to pipelex/pipe_run/dry_run_in_process.py
index b58623e49..067c1359c 100644
--- a/pipelex/pipe_run/dry_run_pipeline.py
+++ b/pipelex/pipe_run/dry_run_in_process.py
@@ -1,18 +1,24 @@
-"""Pipeline-level dry run with graph generation.
-
-Provides a single entrypoint to dry-run an entire pipeline from MTHDS content,
-producing a GraphSpec. Used by both the CLI graph commands and the API.
+"""In-process, in-memory graph-producing dry run against an already-open library.
+
+`dry_run_pipe_in_process` is the in-process twin of `dry_run_pipeline`
+(`pipelex.pipeline.dry_run_pipeline`): it dry-runs ONE pipe against a library the caller
+already opened, never dispatches (even under a Temporal-enabled hub), and traces the graph
+into an in-memory event log. It lives in its own module — not in `dry_run_pipeline` —
+because `dry_run_pipeline` imports `PipelexMTHDSProtocol` from `pipelex.pipeline.runner`,
+and the protocol's `validate` graph arm calls this function: sharing a module would close
+an import cycle through `runner`.
"""
+from polyfactory.exceptions import FactoryException
+
+from pipelex import log
+from pipelex.base_exceptions import PipelexError
from pipelex.cogt.content_generation.content_generator import ContentGenerator
from pipelex.config import get_config
-from pipelex.core.interpreter.exceptions import PipelexInterpreterError
-from pipelex.core.interpreter.interpreter import PipelexInterpreter
from pipelex.core.pipes.pipe_abstract import PipeAbstract
-from pipelex.core.pipes.pipe_factory import PipeFactory
from pipelex.graph.graph_tracer_manager import GraphTracerManager
from pipelex.graph.graphspec import GraphSpec
-from pipelex.hub import scoped_content_generator, scoped_event_log, scoped_pipe_router
+from pipelex.hub import get_library_manager, scoped_content_generator, scoped_event_log, scoped_pipe_router
from pipelex.observer.observer_protocol import ObserverNoOp
from pipelex.pipe_run.exceptions import DryRunGraphNotProducedError
from pipelex.pipe_run.pipe_router import PipeRouter
@@ -20,96 +26,54 @@ from pipelex.pipe_run.pipe_run import PipeRun
from pipelex.pipe_run.pipe_run_mode import PipeRunMode
from pipelex.pipeline.execution_seams import prepare_pipe_job
from pipelex.pipeline.pipeline_factory import PipelineFactory
-from pipelex.pipeline.runner import PipelexMTHDSProtocol
from pipelex.system.telemetry.otel_constants import OTelConstants
from pipelex.tracing.in_memory_event_log import InMemoryEventLog
-async def dry_run_pipeline(
- mthds_contents: list[str] | None = None,
- bundle_uris: list[str] | None = None,
- library_dirs: list[str] | None = None,
-) -> tuple[GraphSpec, str]:
- """Dry-run a full pipeline from MTHDS content, producing a GraphSpec.
-
- Parses the content, identifies the main pipe, and executes the pipeline
- in dry-run mode with graph tracing enabled and mock inputs.
+async def best_effort_graph_spec(pipe_ref: str | None, *, library_id: str | None, log_context: str) -> GraphSpec | None:
+ """Best-effort graph arm of the validate surfaces: dry-run ``pipe_ref`` for its graph, or degrade to None.
- All contents are parsed into blueprints and loaded together; the main_pipe
- is found from the first blueprint that declares one.
+ The ONE implementation of the validate graph-arm contract, shared by every backend
+ (`PipelexMTHDSProtocol.validate` and the Temporal validate activity) so they answer
+ identically for the same bundle: no target or no library means no graph; pipe
+ resolution targets the EXPLICIT ``library_id`` (never the ambient current-library
+ contextvar — the caller captured the validation library once and the graph must come
+ from that same library) and sits INSIDE the catch on purpose (an unknown ``pipe_ref``
+ degrades like any other graph-arm domain failure); an expected dry-run domain
+ failure — ``PipelexError``, polyfactory ``FactoryException``, or any ``ValueError``
+ (covers pydantic ``ValidationError`` and the ValueError-family domain errors such as
+ ``ConceptValueError``, all reachable from the mock-input mint and schema resolution) —
+ degrades to ``None`` with a warning. Only non-Pipelex programming bugs propagate.
Args:
- mthds_contents: List of MTHDS bundle contents as strings.
- bundle_uris: Optional list of URIs for the bundles (used by runner for dedup).
- library_dirs: Optional library directories for pipe resolution.
+ pipe_ref: The namespaced ref of the pipe to dry-run, or ``None`` for no graph.
+ library_id: The id of the already-open library to run against, or ``None`` for no graph.
+ log_context: Caller tag prefixed to the degrade warning (e.g. ``"act_dry_validate"``).
Returns:
- Tuple of (GraphSpec, pipe_code).
-
- Raises:
- PipelexInterpreterError: If content parsing fails or main_pipe is missing.
- DryRunGraphNotProducedError: If pipeline execution does not produce a graph spec.
- PipelineExecutionError: If dry-run execution fails.
+ The assembled GraphSpec, or ``None`` when skipped or degraded.
"""
- if not mthds_contents:
- msg = "mthds_contents must be provided"
- raise ValueError(msg)
-
- # Pre-parse contents to extract main_pipe_code.
- # Note: pipeline_run_setup will re-parse these contents. The double-parse is
- # accepted because the runner interface requires pipe_code upfront and does not
- # expose the internally-resolved pipe code in its response.
- main_pipe_code: str | None = None
-
- for content in mthds_contents:
- bundle_blueprint = PipelexInterpreter.make_pipelex_bundle_blueprint(mthds_content=content)
- if bundle_blueprint.main_pipe and main_pipe_code is None:
- # Domain-qualify to avoid ambiguity across multiple domains
- main_pipe_code = PipeFactory.make_pipe_ref_with_domain(domain_code=bundle_blueprint.domain, pipe_code=bundle_blueprint.main_pipe)
-
- if not main_pipe_code:
- msg = "Bundle does not declare a main_pipe, cannot generate graph"
- raise PipelexInterpreterError(msg)
-
- pipe_code: str = main_pipe_code
-
- execution_config = get_config().pipelex.pipeline_execution_config.with_execution_overrides(
- generate_graph=True,
- mock_inputs=True,
- )
-
- runner = PipelexMTHDSProtocol(
- bundle_uris=bundle_uris,
- pipe_run_mode=PipeRunMode.DRY,
- execution_config=execution_config,
- library_dirs=library_dirs or [],
- )
- # This function's whole purpose is the graph, so it owns the graph transport: the scoped
- # in-memory event log is the run's emit AND assemble channel (see hub.scoped_event_log, D1),
- # making graph generation independent of the host's tracing_config — a host with tracing
- # disabled (e.g. pipelex-api's /validate in direct mode) still gets its graph, and a host
- # with a configured backend doesn't get trace files written as a side effect of validation.
- with scoped_event_log(InMemoryEventLog()):
- response = await runner.execute(
- pipe_code=pipe_code,
- mthds_contents=mthds_contents,
+ if not pipe_ref or not library_id:
+ return None
+ try:
+ pipe = get_library_manager().get_library(library_id=library_id).pipe_library.get_required_pipe(pipe_code=pipe_ref)
+ return await dry_run_pipe_in_process(pipe=pipe, library_id=library_id)
+ except (PipelexError, FactoryException, ValueError) as graph_error:
+ log.warning(
+ f"{log_context}: graph dry-run of '{pipe_ref}' did not produce a graph "
+ f"({type(graph_error).__name__}: {graph_error}); returning validation result without graph_spec"
)
- pipe_output = response.pipe_output
-
- if not pipe_output.graph_spec:
- msg = "Pipeline execution did not produce a graph spec"
- raise DryRunGraphNotProducedError(msg)
-
- return pipe_output.graph_spec, pipe_code
+ return None
async def dry_run_pipe_in_process(pipe: PipeAbstract, *, library_id: str) -> GraphSpec:
"""Dry-run ``pipe`` against an already-open library fully in-process, tracing the graph in memory.
- The in-process twin of :func:`dry_run_pipeline` for hosts where the hub is Temporal-enabled
- but the run must NOT dispatch anything — e.g. the body of the dry-run/validation Temporal
- activity. Three contextvar scopes pin the whole run (root pipe + nested controller sub-pipes
- + inference leaves) to in-process execution:
+ The in-process twin of :func:`pipelex.pipeline.dry_run_pipeline.dry_run_pipeline` for hosts
+ where the hub is Temporal-enabled but the run must NOT dispatch anything — e.g. the body of
+ the dry-run/validation Temporal activity, or the protocol `validate` graph arm. Three
+ contextvar scopes pin the whole run (root pipe + nested controller sub-pipes + inference
+ leaves) to in-process execution:
- ``scoped_event_log(InMemoryEventLog())`` — emit and assemble share one in-memory transport
(no NDJSON file, no DynamoDB round-trip); the ``GraphSpec`` rides back on ``PipeOutput``.
diff --git a/pipelex/pipe_signature/pipe_signature.py b/pipelex/pipe_signature/pipe_signature.py
index b4cfc4ecc..c67df2a6f 100644
--- a/pipelex/pipe_signature/pipe_signature.py
+++ b/pipelex/pipe_signature/pipe_signature.py
@@ -25,9 +25,16 @@ class PipeSignature(PipeAbstract):
"""
type: Literal["PipeSignature"] = "PipeSignature"
- pipe_category: Literal["PipeSignature"] = "PipeSignature"
+ # A signature is outside the executable taxonomy: it has no `PipeCategory`. `type` stays the
+ # discriminator tag; `pipe_category` is None (the base validator admits None only for signatures).
+ pipe_category: None = None
signature_for: PipeType | None = None
+ @property
+ @override
+ def is_signature(self) -> bool:
+ return True
+
@override
def validate_inputs_static(self) -> None:
pass
diff --git a/pipelex/pipe_signature/pipe_signature_blueprint.py b/pipelex/pipe_signature/pipe_signature_blueprint.py
index 54e30a369..e3a5c3531 100644
--- a/pipelex/pipe_signature/pipe_signature_blueprint.py
+++ b/pipelex/pipe_signature/pipe_signature_blueprint.py
@@ -1,6 +1,6 @@
from typing import Literal
-from pydantic import Field, field_validator
+from pydantic import Field
from typing_extensions import override
from pipelex.core.pipes.pipe_blueprint import PipeBlueprint, PipeType
@@ -15,19 +15,20 @@ class PipeSignatureBlueprint(PipeBlueprint):
"""
type: Literal["PipeSignature"] = "PipeSignature"
- pipe_category: Literal["PipeSignature"] = "PipeSignature"
+ # Outside the executable taxonomy: no `PipeCategory`. Keep `exclude=True` (overriding the field
+ # type drops the base's `Field(exclude=True)` unless re-specified) so it never serializes into `.mthds`.
+ pipe_category: None = Field(default=None, exclude=True)
+ # `signature_for=PipeSignature` is now rejected structurally: `PipeSignature` is no longer a
+ # `PipeType` member, so Pydantic cannot coerce it into this field — no guard validator needed.
signature_for: PipeType | None = Field(
default=None,
description="Intended downstream pipe type when this signature is implemented (optional hint for agents).",
)
- @field_validator("signature_for", mode="after")
- @classmethod
- def reject_signature_for_pipe_signature(cls, value: PipeType | None) -> PipeType | None:
- if value is PipeType.PIPE_SIGNATURE:
- msg = "A PipeSignature blueprint cannot have signature_for=PipeSignature."
- raise ValueError(msg)
- return value
+ @property
+ @override
+ def is_signature(self) -> bool:
+ return True
@override
def validate_inputs(self) -> None:
diff --git a/pipelex/pipeline/blueprint_selection.py b/pipelex/pipeline/blueprint_selection.py
new file mode 100644
index 000000000..1908e6a92
--- /dev/null
+++ b/pipelex/pipeline/blueprint_selection.py
@@ -0,0 +1,53 @@
+"""Primary-blueprint selection for a validated batch.
+
+One selection rule shared by every surface that needs a batch's main pipe (the canonical
+report's ``bundle_blueprint``, the graph arm's target derivation, the Temporal activity,
+library acquisition, dry-run and inputs derivation) — one rule, one implementation.
+
+Lives in its own dedicated module (not next to ``validate_bundle``) so that callers below
+the validation layer (``execution_seams``, ``dry_run_pipeline``, ``inputs_ops``) can use it
+without an import cycle through ``bundle_validator``.
+"""
+
+from typing import NamedTuple, Sequence
+
+from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
+from pipelex.core.pipes.pipe_factory import PipeFactory
+from pipelex.pipeline.exceptions import ValidateBundleError
+
+
+class PrimaryBlueprintSelection(NamedTuple):
+ """The primary blueprint of a validated batch and its domain-qualified main-pipe ref (if any)."""
+
+ blueprint: PipelexBundleBlueprint
+ main_pipe_ref: str | None
+
+
+def select_primary_blueprint(blueprints: Sequence[PipelexBundleBlueprint]) -> PrimaryBlueprintSelection:
+ """Select the primary blueprint of a batch: first declaring ``main_pipe``, else first.
+
+ The single selection rule shared by every surface that needs a batch's main pipe (the
+ canonical report's ``bundle_blueprint``, the graph arm's target derivation, the Temporal
+ activity, library acquisition, dry-run and inputs derivation) — one rule, one
+ implementation. ``main_pipe_ref`` is the domain-qualified ref of the primary blueprint's
+ ``main_pipe``, or ``None`` when no blueprint in the batch declares one.
+
+ Args:
+ blueprints: The batch's blueprints, in declaration order.
+
+ Returns:
+ The primary blueprint and its qualified main-pipe ref.
+
+ Raises:
+ ValidateBundleError: When ``blueprints`` is empty — a caller error (e.g. an empty
+ ``mthds_contents`` array reaching a hosted runner), surfaced as the structured
+ input-error class every validate surface already maps, never a bare IndexError.
+ """
+ if not blueprints:
+ msg = "Cannot select a primary blueprint from an empty batch: no MTHDS contents were provided."
+ raise ValidateBundleError(message=msg)
+ for blueprint in blueprints:
+ if blueprint.main_pipe:
+ main_pipe_ref = PipeFactory.make_pipe_ref_with_domain(domain_code=blueprint.domain, pipe_code=blueprint.main_pipe)
+ return PrimaryBlueprintSelection(blueprint=blueprint, main_pipe_ref=main_pipe_ref)
+ return PrimaryBlueprintSelection(blueprint=blueprints[0], main_pipe_ref=None)
diff --git a/pipelex/pipeline/dry_run_pipeline.py b/pipelex/pipeline/dry_run_pipeline.py
new file mode 100644
index 000000000..908808acb
--- /dev/null
+++ b/pipelex/pipeline/dry_run_pipeline.py
@@ -0,0 +1,96 @@
+"""Pipeline-level dry run with graph generation.
+
+Provides a single entrypoint to dry-run an entire pipeline from MTHDS content,
+producing a GraphSpec. Used by the CLI graph commands.
+
+It lives at the pipeline altitude — it instantiates the protocol runner
+(`PipelexMTHDSProtocol`) and runs a whole bundle — unlike its in-process twin
+`dry_run_pipe_in_process` (`pipelex.pipe_run.dry_run_in_process`), which dry-runs ONE pipe
+against an already-open library without dispatching. The twin's callers (the protocol
+`validate` graph arm among them) cannot share a module with the runner import without a
+cycle, which is why the two entrypoints are separate modules at separate altitudes.
+"""
+
+from pipelex.config import get_config
+from pipelex.core.interpreter.exceptions import PipelexInterpreterError
+from pipelex.core.interpreter.interpreter import PipelexInterpreter
+from pipelex.graph.graphspec import GraphSpec
+from pipelex.hub import scoped_event_log
+from pipelex.pipe_run.exceptions import DryRunGraphNotProducedError
+from pipelex.pipe_run.pipe_run_mode import PipeRunMode
+from pipelex.pipeline.blueprint_selection import select_primary_blueprint
+from pipelex.pipeline.runner import PipelexMTHDSProtocol
+from pipelex.tracing.in_memory_event_log import InMemoryEventLog
+
+
+async def dry_run_pipeline(
+ mthds_contents: list[str] | None = None,
+ bundle_uris: list[str] | None = None,
+ library_dirs: list[str] | None = None,
+) -> tuple[GraphSpec, str]:
+ """Dry-run a full pipeline from MTHDS content, producing a GraphSpec.
+
+ Parses the content, identifies the main pipe, and executes the pipeline
+ in dry-run mode with graph tracing enabled and mock inputs.
+
+ All contents are parsed into blueprints and loaded together; the main_pipe
+ is found from the first blueprint that declares one.
+
+ Args:
+ mthds_contents: List of MTHDS bundle contents as strings.
+ bundle_uris: Optional list of URIs for the bundles (used by runner for dedup).
+ library_dirs: Optional library directories for pipe resolution.
+
+ Returns:
+ Tuple of (GraphSpec, pipe_code).
+
+ Raises:
+ PipelexInterpreterError: If content parsing fails or main_pipe is missing.
+ DryRunGraphNotProducedError: If pipeline execution does not produce a graph spec.
+ PipelineExecutionError: If dry-run execution fails.
+ """
+ if not mthds_contents:
+ msg = "mthds_contents must be provided"
+ raise ValueError(msg)
+
+ # Pre-parse contents to extract main_pipe_code via the one shared selection rule.
+ # Note: pipeline_run_setup will re-parse these contents. The double-parse is
+ # accepted because the runner interface requires pipe_code upfront and does not
+ # expose the internally-resolved pipe code in its response.
+ blueprints = [PipelexInterpreter.make_pipelex_bundle_blueprint(mthds_content=content) for content in mthds_contents]
+ main_pipe_code = select_primary_blueprint(blueprints).main_pipe_ref
+
+ if not main_pipe_code:
+ msg = "Bundle does not declare a main_pipe, cannot generate graph"
+ raise PipelexInterpreterError(msg)
+
+ pipe_code: str = main_pipe_code
+
+ execution_config = get_config().pipelex.pipeline_execution_config.with_execution_overrides(
+ generate_graph=True,
+ mock_inputs=True,
+ )
+
+ runner = PipelexMTHDSProtocol(
+ bundle_uris=bundle_uris,
+ pipe_run_mode=PipeRunMode.DRY,
+ execution_config=execution_config,
+ library_dirs=library_dirs or [],
+ )
+ # This function's whole purpose is the graph, so it owns the graph transport: the scoped
+ # in-memory event log is the run's emit AND assemble channel (see hub.scoped_event_log, D1),
+ # making graph generation independent of the host's tracing_config — a host with tracing
+ # disabled (e.g. pipelex-api's /validate in direct mode) still gets its graph, and a host
+ # with a configured backend doesn't get trace files written as a side effect of validation.
+ with scoped_event_log(InMemoryEventLog()):
+ response = await runner.execute(
+ pipe_code=pipe_code,
+ mthds_contents=mthds_contents,
+ )
+ pipe_output = response.pipe_output
+
+ if not pipe_output.graph_spec:
+ msg = "Pipeline execution did not produce a graph spec"
+ raise DryRunGraphNotProducedError(msg)
+
+ return pipe_output.graph_spec, pipe_code
diff --git a/pipelex/pipeline/exceptions.py b/pipelex/pipeline/exceptions.py
index cbea02dac..b15a1976c 100644
--- a/pipelex/pipeline/exceptions.py
+++ b/pipelex/pipeline/exceptions.py
@@ -127,6 +127,17 @@ class ValidateBundleError(PipelexError):
return self.pipe_validation_errors + self.pipe_concept_instantiation_errors
+class PipeIOContractError(PipelexError):
+ """Raised when projecting a validated pipe into its `pipe_io_contracts` IO contract fails.
+
+ Wraps a JSON-Schema rendering failure (a pydantic schema-generation error on a
+ structure class) into a structured Pipelex error, so every validate surface —
+ direct and Temporal alike — reports it identically instead of leaking a raw
+ third-party exception (which the Temporal error boundary would not convert and
+ Temporal would pointlessly retry).
+ """
+
+
class PipelineInputContentError(PipelexError):
"""A pipeline input's content reference (url) is unusable.
diff --git a/pipelex/pipeline/execution_seams.py b/pipelex/pipeline/execution_seams.py
index 190d3ef1f..5ee28e333 100644
--- a/pipelex/pipeline/execution_seams.py
+++ b/pipelex/pipeline/execution_seams.py
@@ -29,7 +29,6 @@ from pipelex.core.interpreter.interpreter import PipelexInterpreter
from pipelex.core.memory.working_memory import WorkingMemory
from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory
from pipelex.core.pipes.pipe_abstract import PipeAbstract
-from pipelex.core.pipes.pipe_factory import PipeFactory
from pipelex.hub import (
clear_current_library,
get_current_library_id_or_none,
@@ -42,6 +41,7 @@ from pipelex.pipe_run.pipe_job_factory import PipeJobFactory
from pipelex.pipe_run.pipe_run_mode import PipeRunMode
from pipelex.pipe_run.pipe_run_params import VariableMultiplicity
from pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactory
+from pipelex.pipeline.blueprint_selection import select_primary_blueprint
from pipelex.pipeline.input_normalizer import normalize_data_urls_to_storage
from pipelex.pipeline.job_metadata import JobMetadata, OtelContext
from pipelex.system.configuration.configs import PipelineExecutionConfig
@@ -112,12 +112,9 @@ def acquire_library(
if blueprints_to_load:
library_manager.load_from_blueprints(library_id=library_id, blueprints=blueprints_to_load)
- # Qualify main_pipe with domain to avoid ambiguity when multiple domains define pipes with the
- # same code. main_pipe is validated as snake_case (no dots), so it is always a bare code.
- for blueprint in all_blueprints:
- if blueprint.main_pipe:
- qualified_main_pipe = PipeFactory.make_pipe_ref_with_domain(domain_code=blueprint.domain, pipe_code=blueprint.main_pipe)
- break
+ # Qualify main_pipe with domain to avoid ambiguity when multiple domains define pipes with
+ # the same code — via the one shared selection rule (first declaring main_pipe, else first).
+ qualified_main_pipe = select_primary_blueprint(all_blueprints).main_pipe_ref
success = True
return library_id, qualified_main_pipe
diff --git a/pipelex/pipeline/pipe_io_contracts.py b/pipelex/pipeline/pipe_io_contracts.py
new file mode 100644
index 000000000..5bc104b41
--- /dev/null
+++ b/pipelex/pipeline/pipe_io_contracts.py
@@ -0,0 +1,117 @@
+"""Per-pipe input/output contracts (`pipe_io_contracts`) for the validate surfaces.
+
+This is the canonical builder for the `pipe_io_contracts` artifact reported by the MTHDS
+Protocol `validate` operation (local runtime and hosted API alike). It projects loaded
+pipes into typed `PipeIOContract` entries — for each pipe, the JSON-Schema view of its
+declared inputs and the concept/multiplicity of its output — keyed by the namespaced
+`pipe_ref` (`domain.code`), the one identity convention shared by every validate artifact
+(`validated_pipes`, `pending_signatures`).
+
+The JSON-Schema rendering resolves each concept's structure class through the GLOBAL
+class registry. Bundle-defined structure classes are registered there during library
+load and are NOT unregistered at teardown (the registry has no unregister mechanism) —
+so a call after teardown does not fail loudly: it silently renders against whatever
+classes the registry last held, which may be stale or belong to a different bundle.
+Callers must therefore invoke the builder against loaded pipes INSIDE the validation
+library's window, before teardown. (Registry teardown hygiene is tracked in the
+workspace-root `wip/library-lifecycle-hygiene.md`.)
+"""
+
+from typing import Any, Sequence
+
+from pydantic import BaseModel, Field, PydanticUndefinedAnnotation, PydanticUserError
+
+from pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormat
+from pipelex.core.concepts.exceptions import ConceptValueError
+from pipelex.core.pipes.pipe_abstract import PipeAbstract
+from pipelex.pipeline.exceptions import PipeIOContractError
+from pipelex.types import StrEnum
+
+
+class IOMultiplicity(StrEnum):
+ """Wire value for an output's multiplicity: one item, or a list of them.
+
+ Any multiple output — variable-length or fixed-count — reports `variable`; the
+ distinction the contract carries is "one vs many", not the exact count.
+ """
+
+ SINGLE = "single"
+ VARIABLE = "variable"
+
+
+class PipeInputContract(BaseModel):
+ """One declared input: the concept it expects and the JSON Schema of its content."""
+
+ concept_code: str
+ json_schema: dict[str, Any] = Field(default_factory=dict)
+
+
+class PipeOutputContract(BaseModel):
+ """The pipe's output: the concept it produces and whether it is one item or a list."""
+
+ concept_code: str
+ multiplicity: IOMultiplicity
+
+
+class PipeIOContract(BaseModel):
+ """The input/output contract of one pipe — a `pipe_io_contracts` entry."""
+
+ inputs: dict[str, PipeInputContract] = Field(default_factory=dict)
+ output: PipeOutputContract
+
+
+def build_pipe_io_contracts(pipes: Sequence[PipeAbstract]) -> dict[str, PipeIOContract]:
+ """Project loaded pipes into `pipe_io_contracts` entries keyed by namespaced `pipe_ref`.
+
+ Works on any loaded `PipeAbstract` — including `PipeSignature` placeholders, whose
+ declared contract is exactly what a top-down build needs to see. Must run while the
+ validation library is still loaded: bundle-defined structure classes resolve through
+ the global class registry and a post-teardown call silently uses stale classes
+ instead of failing (see the module docstring).
+
+ Args:
+ pipes: The loaded pipes to project (typically `ValidateBundleResult.pipes`).
+
+ Returns:
+ `pipe_ref` → `PipeIOContract` for every given pipe.
+
+ Raises:
+ PipeIOContractError: When a pipe input's JSON-Schema rendering fails — a pydantic
+ schema-generation error on a structure class, a structure class missing from
+ the registry (`ConceptValueError`), or a render-shape drift — converted here
+ so every validate surface reports the same structured error.
+ """
+ # Per-call memo: pipes routinely share input concepts, and the JSON-Schema rendering
+ # (pydantic's model_json_schema, uncached) would otherwise be regenerated once per
+ # occurrence. Deliberately NOT a module-level cache — bundle-defined structure classes
+ # vary per loaded library, so a cross-call cache would serve stale schemas.
+ schema_memo: dict[tuple[str, bool], dict[str, Any]] = {}
+ io_contracts: dict[str, PipeIOContract] = {}
+ for pipe in pipes:
+ pipe_inputs: dict[str, PipeInputContract] = {}
+ for var_name, stuff_spec in pipe.inputs.root.items():
+ memo_key = (stuff_spec.concept.concept_ref, stuff_spec.is_multiple())
+ json_schema = schema_memo.get(memo_key)
+ if json_schema is None:
+ try:
+ # Indexing (not .get with a default) is deliberate: a render-shape drift
+ # must surface as the structured error below, never ship a silently
+ # empty schema on the wire.
+ json_schema = stuff_spec.render_stuff_spec(ConceptRepresentationFormat.SCHEMA)["content"]
+ except (ConceptValueError, KeyError, PydanticUserError, PydanticUndefinedAnnotation) as exc:
+ msg = (
+ f"Failed to render the JSON Schema for input '{var_name}' of pipe "
+ f"'{pipe.pipe_ref}' (concept '{stuff_spec.concept.concept_ref}'): {exc}"
+ )
+ raise PipeIOContractError(message=msg) from exc
+ schema_memo[memo_key] = json_schema
+ pipe_inputs[var_name] = PipeInputContract(
+ concept_code=stuff_spec.concept.concept_ref,
+ json_schema=json_schema,
+ )
+ pipe_output = PipeOutputContract(
+ concept_code=pipe.output.concept.concept_ref,
+ multiplicity=IOMultiplicity.VARIABLE if pipe.output.is_multiple() else IOMultiplicity.SINGLE,
+ )
+ io_contracts[pipe.pipe_ref] = PipeIOContract(inputs=pipe_inputs, output=pipe_output)
+ return io_contracts
diff --git a/pipelex/pipeline/runner.py b/pipelex/pipeline/runner.py
index 859db0d5a..faa4d48cb 100644
--- a/pipelex/pipeline/runner.py
+++ b/pipelex/pipeline/runner.py
@@ -9,11 +9,12 @@ from mthds.protocol.exceptions import PipelineRequestError
from mthds.protocol.models import ModelCategory as MthdsModelCategory
from mthds.protocol.models import ModelDeck as MthdsModelDeck
from mthds.protocol.models import ModelInfo as MthdsModelInfo
-from mthds.protocol.models import ValidationReport, VersionInfo
-from mthds.protocol.protocol import MTHDSProtocol
+from mthds.protocol.models import VersionInfo
+from mthds.protocol.protocol import PROTOCOL_VERSION, MTHDSProtocol
from pydantic import Field, ValidationError
from typing_extensions import override
+from pipelex import log
from pipelex.base_exceptions import PipelexError
from pipelex.builder.operations.models_ops import ModelCategory, list_models
from pipelex.config import get_config
@@ -28,11 +29,15 @@ from pipelex.hub import (
get_telemetry_manager,
set_current_library,
)
+from pipelex.pipe_run.dry_run_in_process import best_effort_graph_spec
from pipelex.pipe_run.exceptions import PipeRouterError
+from pipelex.pipeline.blueprint_selection import select_primary_blueprint
from pipelex.pipeline.exceptions import PipeExecutionError, PipelineExecutionError
+from pipelex.pipeline.pipe_io_contracts import PipeIOContract, build_pipe_io_contracts
from pipelex.pipeline.pipeline_response import PipelexRunResultExecute, PipelexRunResultStart, RunState
from pipelex.pipeline.pipeline_run_setup import pipeline_run_setup
from pipelex.pipeline.validate_bundle import validate_bundle
+from pipelex.pipeline.validation_report import PipelexValidationReport, build_validation_report
from pipelex.system.telemetry.events import EventName, EventProperty, Outcome
from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error
@@ -45,33 +50,25 @@ if TYPE_CHECKING:
from pipelex.core.memory.working_memory import WorkingMemory
from pipelex.core.pipes.pipe_output import PipeOutput
+ from pipelex.graph.graphspec import GraphSpec
from pipelex.pipe_run.delivery_assignment import DeliveryAssignment
from pipelex.pipe_run.pipe_job import PipeJob
from pipelex.pipe_run.pipe_run_mode import PipeRunMode
from pipelex.pipe_run.pipe_run_protocol import PipeRunProtocol
from pipelex.system.configuration.configs import PipelineExecutionConfig
-# The MTHDS Protocol version this runtime implements (mthds-protocol.openapi.yaml).
-MTHDS_PROTOCOL_VERSION = "0.6.0"
-
-
-class PipelexValidationReport(ValidationReport):
- """Pipelex's validation artifacts — this implementation's extensions on the
- protocol's `ValidationReport` (which declares no body fields).
- """
-
- blueprint: Any = None
- graph_spec: Any = None
- pipe_structures: Any = None
-
class PipelexModelDeck(MthdsModelDeck):
"""Pipelex's model deck — the protocol base plus this implementation's
- routing metadata (aliases, waterfalls).
+ routing metadata (aliases, waterfalls), keyed by model category.
+
+ The routing extensions are category-scoped on purpose: the same alias name
+ (e.g. `default-small`) legitimately exists in several categories pointing at
+ different models, so a flat map would silently lose entries on collision.
"""
- aliases: dict[str, str] = Field(default_factory=dict)
- waterfalls: dict[str, list[str]] = Field(default_factory=dict)
+ aliases: dict[str, dict[str, str]] = Field(default_factory=dict)
+ waterfalls: dict[str, dict[str, list[str]]] = Field(default_factory=dict)
class PipelexVersionInfo(VersionInfo):
@@ -343,20 +340,37 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):
self,
mthds_contents: list[str],
allow_signatures: bool = False,
- ) -> ValidationReport:
+ ) -> PipelexValidationReport:
"""Parse, validate, and dry-run MTHDS bundles — protocol `validate`.
- Wraps `validate_bundle` and maps its result onto the protocol's
- `ValidationReport`: the parsed blueprint(s) and per-pipe structures are
- reported; `graph_spec` stays None (the dry run validates the graph
- without materializing a spec artifact).
+ Wraps `validate_bundle` and assembles its result into the canonical
+ `PipelexValidationReport` via `build_validation_report`: the primary
+ `bundle_blueprint`, `pipe_io_contracts` keyed by namespaced `pipe_ref`,
+ the per-pipe `validated_pipes` sweep outcomes, and the runnability
+ verdict — `pending_signatures` (qualified refs of pipes still declared
+ as `PipeSignature` in the assembled library) plus
+ `is_runnable = not pending_signatures`, the same convention as the
+ agent-CLI / builder validate envelopes. The verdict only matters on the
+ lenient `allow_signatures=True` path: in strict mode an unsatisfied
+ signature makes `validate_bundle` raise instead.
+
+ `graph_spec` is best-effort: when the batch declares a `main_pipe`
+ (primary-selection rule: first blueprint declaring one), it is dry-run
+ in-process via `dry_run_pipe_in_process` against the validation library
+ and the resulting graph rides on the report. A graph-arm domain failure
+ (`PipelexError`, polyfactory `FactoryException`, or any `ValueError` —
+ covering pydantic `ValidationError` and the ValueError-family domain
+ errors of the mock-input mint and schema resolution) degrades to
+ `graph_spec=None` with validation still successful — the same contract
+ as the Temporal validate activity, so every backend answers identically
+ for the same bundle. No declared `main_pipe` means no graph.
Args:
mthds_contents: MTHDS contents to load (always a list, even for one file).
allow_signatures: Tolerate unimplemented pipe signatures (strict by default).
Returns:
- ValidationReport with the structural artifacts of a valid bundle.
+ PipelexValidationReport with the structural artifacts of a valid bundle.
Raises:
PipelexError: When the bundle is invalid (parse, static validation, or dry-run failure).
@@ -366,60 +380,92 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):
# current on success (the CLI surfaces consume it before process exit).
# This protocol wrapper is a long-lived entry point, so restore the
# caller's current-library and tear the validation library down on the
- # way out — on failure `validate_bundle` already did both, making the
- # cleanup below a no-op.
+ # way out — on failure `validate_bundle` already did both, so
+ # `validation_library_id` stays None and the cleanup below is a no-op.
+ # Artifacts that need the open validation library are built INSIDE the
+ # window, before the `finally` tears the library down:
+ # `pipe_io_contracts`'s JSON-Schema rendering resolves bundle-defined
+ # structure classes through the class registry, and the graph arm
+ # dry-runs the main pipe against the loaded library.
prev_library_id = get_current_library_id_or_none()
+ validation_library_id: str | None = None
+ # Explicit body-success flag — NOT sys.exc_info() in the finally, which also sees an
+ # exception the CALLER is currently handling (validate awaited inside an except block)
+ # and would wrongly suppress a genuine teardown failure after a successful body.
+ body_succeeded = False
try:
result = await validate_bundle(
mthds_contents=mthds_contents,
library_dirs=library_dirs,
allow_signatures=allow_signatures,
)
- finally:
+ # Capture the validation library id ONCE, right after validate_bundle leaves
+ # it current — the graph arm and the finally must target the SAME library
+ # even if something inside the window later moves the contextvar.
validation_library_id = get_current_library_id_or_none()
+ pipe_io_contracts: dict[str, PipeIOContract] = build_pipe_io_contracts(result.pipes)
+ graph_spec: GraphSpec | None = await best_effort_graph_spec(
+ pipe_ref=select_primary_blueprint(result.blueprints).main_pipe_ref,
+ library_id=validation_library_id,
+ log_context="Protocol validate",
+ )
+ body_succeeded = True
+ finally:
if validation_library_id is not None and validation_library_id != prev_library_id:
+ # Restore the caller's outer current-library FIRST so the guarantee
+ # survives a teardown raise — mirrors act_dry_validate.
if prev_library_id is not None:
set_current_library(library_id=prev_library_id)
else:
clear_current_library()
- get_library_manager().teardown(library_id=validation_library_id)
- blueprints_dump: list[dict[str, Any]] = [blueprint.model_dump(mode="json") for blueprint in result.blueprints]
- pipe_structures: dict[str, Any] = {pipe.code: pipe.model_dump(mode="json") for pipe in result.pipes}
- return PipelexValidationReport(
- blueprint=blueprints_dump[0] if len(blueprints_dump) == 1 else blueprints_dump,
- graph_spec=None,
- pipe_structures=pipe_structures,
+ try:
+ get_library_manager().teardown(library_id=validation_library_id)
+ except PipelexError as teardown_error:
+ # A teardown failure must not REPLACE the body's in-flight error (the
+ # caller's error would name the teardown instead of the actual problem) —
+ # suppress it and let the primary propagate; raise it only when the body
+ # succeeded. Mirrors act_dry_validate's finally.
+ if body_succeeded:
+ raise
+ log.error(
+ f"Protocol validate: library teardown also failed after a body error; "
+ f"raising the original error. Suppressed teardown error: {teardown_error}"
+ )
+ return build_validation_report(
+ blueprints=result.blueprints,
+ pipe_io_contracts=pipe_io_contracts,
+ dry_run_result=result.dry_run_result,
+ pending_signatures=result.pending_signatures,
+ graph_spec=graph_spec,
)
@override
- async def models(self, category: MthdsModelCategory | None = None) -> MthdsModelDeck:
+ async def models(self, category: MthdsModelCategory | None = None) -> PipelexModelDeck:
"""The model deck this runtime can route to — protocol `models`.
- Wraps the builder's `list_models` and shapes its per-category payload
- into the protocol `ModelDeck`.
+ Wraps the builder's `list_models`: presets project into the protocol's flat
+ `models` list (each entry carries its category as `type`); the aliases and
+ waterfalls routing extensions stay keyed by category — the same alias name
+ exists in several categories pointing at different models, so flattening
+ them would silently drop entries on collision.
Args:
category: Optional deck filter (`llm`, `extract`, `img_gen`, `search`).
Returns:
- ModelDeck with presets, aliases, and routing waterfalls.
+ PipelexModelDeck with the flat model list and the category-keyed
+ aliases and routing waterfalls.
"""
categories = [ModelCategory(category)] if category is not None else None
deck_raw = list_models(categories=categories)
models: list[MthdsModelInfo] = []
- aliases: dict[str, str] = {}
- waterfalls: dict[str, list[str]] = {}
presets_by_category: dict[str, list[dict[str, Any]]] = deck_raw["presets"]
aliases_by_category: dict[str, dict[str, str]] = deck_raw["aliases"]
waterfalls_by_category: dict[str, dict[str, list[str]]] = deck_raw["waterfalls"]
for category_key, category_presets in presets_by_category.items():
for preset in category_presets:
models.append(MthdsModelInfo(name=preset["name"], type=MthdsModelCategory(category_key)))
- for category_aliases in aliases_by_category.values():
- aliases.update(category_aliases)
- for category_waterfalls in waterfalls_by_category.values():
- waterfalls.update(category_waterfalls)
- return PipelexModelDeck(models=models, aliases=aliases, waterfalls=waterfalls)
+ return PipelexModelDeck(models=models, aliases=aliases_by_category, waterfalls=waterfalls_by_category)
@override
async def version(self) -> VersionInfo:
@@ -437,7 +483,7 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):
# the runtime still works, so version() must not fail.
pipelex_version = "unknown"
return PipelexVersionInfo(
- protocol_version=MTHDS_PROTOCOL_VERSION,
+ protocol_version=PROTOCOL_VERSION,
runner_version=pipelex_version,
implementation="pipelex",
implementation_version=pipelex_version,
diff --git a/pipelex/pipeline/validate_bundle.py b/pipelex/pipeline/validate_bundle.py
index fb2776791..c1340d71f 100644
--- a/pipelex/pipeline/validate_bundle.py
+++ b/pipelex/pipeline/validate_bundle.py
@@ -2,10 +2,13 @@ import asyncio
from collections.abc import Generator
from contextlib import contextmanager
from pathlib import Path
-from typing import Literal, Sequence, TypedDict
+from typing import Literal, Sequence
from pydantic import BaseModel, ValidationError
-from typing_extensions import assert_never
+
+# TypedDict from typing_extensions, not typing: pydantic rejects typing.TypedDict as a model
+# field on Python < 3.12, and ValidatedPipeEntry is a field of PipelexValidationReport.
+from typing_extensions import TypedDict, assert_never
from pipelex import log
from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
@@ -19,6 +22,7 @@ from pipelex.core.pipes.handle_pipe_errors import (
categorize_pipe_validation_with_libraries_error,
)
from pipelex.core.pipes.pipe_abstract import PipeAbstract
+from pipelex.core.qualified_ref import QualifiedRef
from pipelex.core.validation import report_validation_error
from pipelex.hub import (
clear_current_library,
@@ -27,6 +31,7 @@ from pipelex.hub import (
resolve_library_dirs,
set_current_library,
)
+from pipelex.libraries.exceptions import LibraryError, LibraryLoadingError
from pipelex.libraries.library_utils import get_pipelex_mthds_files_from_dirs
from pipelex.libraries.pipe.exceptions import PipeNotFoundError
from pipelex.pipe_run.exceptions import DryRunError, PipeRunError
@@ -39,17 +44,24 @@ class ValidateBundleResult(BaseModel):
blueprints: list[PipelexBundleBlueprint]
pipes: list[PipeAbstract]
dry_run_result: dict[str, DryRunOutput]
+ pending_signatures: list[str]
+ """Qualified refs of pipes still declared as ``PipeSignature`` in the assembled library.
+
+ These are the unimplemented headers left after the merge: a forward-declared pipe that no
+ concrete definition has satisfied yet. Computed library-wide (not just from the triggering
+ file's pipes), so a lenient ``--allow-signatures`` success can report exactly what remains to
+ be implemented even when validating one file of a multi-file library at a time.
+ """
class ValidatedPipeEntry(TypedDict):
"""One entry in the ``validated_pipes`` JSON envelope returned by the validate surfaces.
- The ``pipe_code`` key carries the namespaced ``pipe_ref`` (``domain.code``) — the key name is
- kept for the published JSON contract, but the value is the qualified ref, never the bare code.
+ The ``pipe_ref`` key carries the namespaced ``pipe_ref`` (``domain.code``) — never the bare code.
``status`` is a ``DryRunStatus`` (a ``StrEnum``), so it serializes to its plain string value.
"""
- pipe_code: str
+ pipe_ref: str
status: DryRunStatus
@@ -61,7 +73,22 @@ def build_validated_pipes(dry_run_result: dict[str, DryRunOutput]) -> list[Valid
``pipe_ref`` (``domain.code``) on every surface — one unambiguous identity that cannot collide
across domains, so the same pipe is never reported under two identifiers by different commands.
"""
- return [ValidatedPipeEntry(pipe_code=output.pipe_ref, status=output.status) for output in dry_run_result.values()]
+ return [ValidatedPipeEntry(pipe_ref=output.pipe_ref, status=output.status) for output in dry_run_result.values()]
+
+
+def build_pending_signatures(pipes_by_ref: dict[str, PipeAbstract]) -> list[str]:
+ """Qualified refs of pipes still declared as ``PipeSignature`` (unsatisfied forward declarations).
+
+ Once a concrete pipe reconciles with a signature, the concrete replaces it in the merged
+ library (Part A), so the unsatisfied set is exactly the pipes still typed ``PipeSignature`` —
+ no ``{signatures} - {concretes}`` arithmetic needed. Pass the assembled library's pipe map
+ (``pipe_library.get_pipes_dict()``, not a single file's pipes) to get the library-wide set.
+
+ Cross-package dependency pipes (keyed ``alias->...`` by the loader) are excluded: another
+ package's unimplemented headers are not the caller's to satisfy, so they must not appear in the
+ "what remains to implement" nudge.
+ """
+ return sorted(pipe.pipe_ref for ref_key, pipe in pipes_by_ref.items() if pipe.is_signature and not QualifiedRef.has_cross_package_prefix(ref_key))
@contextmanager
@@ -129,6 +156,31 @@ def _translate_to_validate_bundle_error(category: Literal["pipe", "concept"]) ->
message=msg,
pipe_validation_errors=pipe_validation_errors,
) from validation_error
+ except PipeNotFoundError:
+ # PipeNotFoundError is a PipeLibraryError (hence a LibraryError), but it is NOT a bundle
+ # merge/load failure: it means a requested --pipe slice names a pipe absent from the bundle.
+ # It has its own dedicated CLI handler (execute_validate's `except PipeNotFoundError`), so it
+ # must propagate raw rather than be folded into a ValidateBundleError by the arm below.
+ raise
+ except LibraryError as library_error:
+ # Library merge / load failures that are NOT pydantic ValidationErrors: undeclared
+ # cross-file concept references (ConceptLibraryError), signature/concrete contract
+ # mismatches and duplicate concept/pipe refs (ConceptLibraryError / PipeLibraryError), and
+ # the structured LibraryLoadingError aggregate (concept cycles, reserved-domain
+ # violations, factory failures). Surface them as a clean ValidateBundleError instead of a
+ # raw traceback. LibraryLoadingError carries blueprint- and pipe/concept-validation errors;
+ # forward them so the CLI renders the same structured detail it does for the other arms.
+ if isinstance(library_error, LibraryLoadingError):
+ blueprint_validation_errors = library_error.blueprint_validation_errors
+ pipe_concept_validation_errors = library_error.pipe_concept_validation_errors
+ else:
+ blueprint_validation_errors = None
+ pipe_concept_validation_errors = None
+ raise ValidateBundleError(
+ message=library_error.message,
+ pipelex_bundle_blueprint_validation_errors=blueprint_validation_errors,
+ pipe_validation_errors=pipe_concept_validation_errors,
+ ) from library_error
except PipeRunError as pipe_run_error:
raise ValidateBundleError(
message=pipe_run_error.message,
@@ -194,6 +246,12 @@ async def validate_bundle(
if provided_params > 1:
msg = "Only one of mthds_contents or mthds_file_path can be provided to validate_bundle, not both"
raise ValidateBundleError(message=msg)
+ if mthds_contents is not None and not mthds_contents:
+ # An EMPTY list is not None, so it passes the provided-params check above — without this
+ # guard it would yield a blueprint-less result that downstream consumers (the canonical
+ # report's primary-blueprint selection) cannot represent.
+ msg = "mthds_contents must not be empty: provide at least one MTHDS content to validate"
+ raise ValidateBundleError(message=msg)
library_manager = get_library_manager()
library_id, library = library_manager.open_library()
@@ -223,7 +281,12 @@ async def validate_bundle(
dry_run_results = await BundleValidator().validate_pipes(
pipes=_pipes_to_dry_run(loaded_pipes, dry_run_pipe_codes), library_id=library_id, allow_signatures=allow_signatures
)
- result = ValidateBundleResult(blueprints=loaded_blueprints, pipes=loaded_pipes, dry_run_result=dry_run_results)
+ result = ValidateBundleResult(
+ blueprints=loaded_blueprints,
+ pipes=loaded_pipes,
+ dry_run_result=dry_run_results,
+ pending_signatures=build_pending_signatures(library.pipe_library.get_pipes_dict()),
+ )
else:
assert mthds_file_path is not None
@@ -241,7 +304,12 @@ async def validate_bundle(
dry_run_results = await BundleValidator().validate_pipes(
pipes=_pipes_to_dry_run(loaded_pipes, dry_run_pipe_codes), library_id=library_id, allow_signatures=allow_signatures
)
- result = ValidateBundleResult(blueprints=loaded_blueprints, pipes=loaded_pipes, dry_run_result=dry_run_results)
+ result = ValidateBundleResult(
+ blueprints=loaded_blueprints,
+ pipes=loaded_pipes,
+ dry_run_result=dry_run_results,
+ pending_signatures=build_pending_signatures(library.pipe_library.get_pipes_dict()),
+ )
success = True
return result
finally:
@@ -264,7 +332,7 @@ async def validate_bundles_from_directory(directory: Path, allow_signatures: boo
all_blueprints: list[PipelexBundleBlueprint] = []
library_manager = get_library_manager()
- library_id, _ = library_manager.open_library()
+ library_id, library = library_manager.open_library()
success = False
prev_library_id = get_current_library_id_or_none()
try:
@@ -276,7 +344,12 @@ async def validate_bundles_from_directory(directory: Path, allow_signatures: boo
loaded_pipes = library_manager.load_libraries(library_id=library_id, library_dirs=[Path(directory)])
dry_run_results = await BundleValidator().validate_pipes(pipes=loaded_pipes, library_id=library_id, allow_signatures=allow_signatures)
- result = ValidateBundleResult(blueprints=all_blueprints, pipes=loaded_pipes, dry_run_result=dry_run_results)
+ result = ValidateBundleResult(
+ blueprints=all_blueprints,
+ pipes=loaded_pipes,
+ dry_run_result=dry_run_results,
+ pending_signatures=build_pending_signatures(library.pipe_library.get_pipes_dict()),
+ )
success = True
return result
finally:
diff --git a/pipelex/pipeline/validation_report.py b/pipelex/pipeline/validation_report.py
new file mode 100644
index 000000000..a79f69207
--- /dev/null
+++ b/pipelex/pipeline/validation_report.py
@@ -0,0 +1,88 @@
+"""Canonical MTHDS Protocol validation report for the Pipelex family.
+
+`PipelexValidationReport` is the one report shape every Pipelex backend produces for the
+protocol `validate` operation — the local runtime (`PipelexMTHDSProtocol.validate`) and the
+hosted API (`ApiRunner.validate`, direct and Temporal alike). All fields are typed models,
+not raw dumps, so the schemas flow into the hosted API's committed OpenAPI artifact.
+
+`build_validation_report` is the single assembly point: both backends construct the report
+through it from the same ingredients, so a future report field is populated everywhere or
+nowhere. Primary-blueprint selection (`bundle_blueprint`) goes through
+`select_primary_blueprint` — the same rule the graph arm uses for its target.
+"""
+
+from collections.abc import Sequence
+
+from mthds.protocol.models import ValidationReport
+from pydantic import Field
+
+from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
+from pipelex.graph.graphspec import GraphSpec
+from pipelex.pipeline.blueprint_selection import select_primary_blueprint
+from pipelex.pipeline.bundle_validator import DryRunOutput
+from pipelex.pipeline.pipe_io_contracts import PipeIOContract
+from pipelex.pipeline.validate_bundle import ValidatedPipeEntry, build_validated_pipes
+from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
+
+
+class PipelexValidationReport(ValidationReport):
+ """Pipelex's validation artifacts — this implementation's extensions on the
+ protocol's `ValidationReport` (which declares no body fields).
+
+ Field naming follows the brand boundary: blueprints are MTHDS-language artifacts
+ (the parsed form of `.mthds` content), so the field is `bundle_blueprint` — no
+ `pipelex_` prefix inside this already-Pipelex-branded envelope.
+ """
+
+ bundle_blueprint: PipelexBundleBlueprint
+ """The batch's primary blueprint: first declaring `main_pipe`, else first."""
+
+ pipe_io_contracts: dict[str, PipeIOContract] = Field(default_factory=dict)
+ """Per-pipe input/output contracts, keyed by namespaced `pipe_ref` (`domain.code`)."""
+
+ graph_spec: GraphSpec | None = None
+ """Best-effort execution graph of the declared main pipe; `None` when the batch
+ declares no `main_pipe` or the graph dry-run degrades."""
+
+ validated_pipes: list[ValidatedPipeEntry] = Field(default_factory=empty_list_factory_of(ValidatedPipeEntry))
+ """Per-pipe sweep outcomes (`{pipe_ref, status}`) — the same entries as the agent-CLI envelope."""
+
+ pending_signatures: list[str] = Field(default_factory=list)
+ """Qualified refs of pipes still declared as `PipeSignature` in the assembled library."""
+
+ is_runnable: bool = True
+ """`not pending_signatures` — whether the validated library is complete enough to run."""
+
+
+def build_validation_report(
+ *,
+ blueprints: Sequence[PipelexBundleBlueprint],
+ pipe_io_contracts: dict[str, PipeIOContract],
+ dry_run_result: dict[str, DryRunOutput],
+ pending_signatures: list[str],
+ graph_spec: GraphSpec | None = None,
+) -> PipelexValidationReport:
+ """Assemble the canonical `PipelexValidationReport` from its ingredients.
+
+ The single constructor every backend calls — local protocol `validate` and the hosted
+ API's Temporal mapping. Selects the primary blueprint, projects the dry-run status map
+ into `validated_pipes`, and derives the `is_runnable` verdict.
+
+ Args:
+ blueprints: The validated batch's blueprints, in declaration order (non-empty).
+ pipe_io_contracts: Per-pipe contracts from `build_pipe_io_contracts`, keyed by `pipe_ref`.
+ dry_run_result: The sweep's per-pipe status map (`ValidateBundleResult.dry_run_result`).
+ pending_signatures: Library-wide unsatisfied signature refs.
+ graph_spec: Best-effort graph of the declared main pipe, when one was produced.
+
+ Returns:
+ The canonical report.
+ """
+ return PipelexValidationReport(
+ bundle_blueprint=select_primary_blueprint(blueprints).blueprint,
+ pipe_io_contracts=pipe_io_contracts,
+ graph_spec=graph_spec,
+ validated_pipes=build_validated_pipes(dry_run_result),
+ pending_signatures=pending_signatures,
+ is_runnable=not pending_signatures,
+ )
diff --git a/pipelex/temporal/tprl_pipe/act_dry_validate.py b/pipelex/temporal/tprl_pipe/act_dry_validate.py
index 931daa9c2..5e07ca95d 100644
--- a/pipelex/temporal/tprl_pipe/act_dry_validate.py
+++ b/pipelex/temporal/tprl_pipe/act_dry_validate.py
@@ -18,8 +18,13 @@ Library lifecycle (D4): the library is loaded ONCE — ``validate_bundle`` loads
current on success (its D6 loaded-on-success contract; it owns teardown on failure), the graph
runs against the same library, and this activity tears it down once in its ``finally``.
-Error contract (D3): the output carries the success-only status map + the best-effort
-``GraphSpec``. Validation failures (blueprint/factory/wiring errors, unexpected pipe failures,
+The activity result carries everything the canonical validation report needs that must be
+computed worker-side, against the worker's loaded library (D10): the success-only status map,
+the best-effort ``GraphSpec``, the library-wide ``pending_signatures``, and the
+``pipe_io_contracts`` IO contracts (built inside the library window — their JSON-Schema rendering
+needs the loaded library's class registry, so the API side never needs to re-acquire one).
+
+Error contract (D3): validation failures (blueprint/factory/wiring errors, unexpected pipe failures,
strict-mode signature refusals) RAISE out of ``validate_bundle`` as ``ValidateBundleError`` and
cross the boundary as structured ``ErrorReport``s via ``convert_pipelex_errors`` — the API
renders them as the same RFC 7807 422 the direct path produces (identical ``error_type``,
@@ -34,26 +39,22 @@ same bundle. Only non-Pipelex programming bugs propagate and fail the activity,
``assemble_tracing``'s bug-propagation policy.
"""
-import sys
-
-from polyfactory.exceptions import FactoryException
-from pydantic import BaseModel, ValidationError
+from pydantic import BaseModel
from temporalio import activity
from pipelex import log
from pipelex.base_exceptions import PipelexError
-from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
-from pipelex.core.pipes.pipe_factory import PipeFactory
from pipelex.graph.graphspec import GraphSpec
from pipelex.hub import (
clear_current_library,
get_current_library_id_or_none,
get_library_manager,
- get_required_pipe,
set_current_library,
)
-from pipelex.pipe_run.dry_run_pipeline import dry_run_pipe_in_process
+from pipelex.pipe_run.dry_run_in_process import best_effort_graph_spec
+from pipelex.pipeline.blueprint_selection import select_primary_blueprint
from pipelex.pipeline.bundle_validator import DryRunOutput
+from pipelex.pipeline.pipe_io_contracts import PipeIOContract, build_pipe_io_contracts
from pipelex.pipeline.validate_bundle import validate_bundle
from pipelex.temporal.tprl.activity_error_boundary import convert_pipelex_errors
@@ -70,10 +71,27 @@ class DryValidateArg(BaseModel):
class DryValidateResult(BaseModel):
- """Output of the dry-run+validation activity: success-only status map + best-effort graph (D3)."""
+ """Output of the dry-run+validation activity — everything the canonical validation report
+ needs that must be computed worker-side, against the worker's loaded library (D10):
+
+ - ``dry_run_outputs``: the success-only per-pipe status map (D3) that
+ ``build_validated_pipes`` projects into ``validated_pipes``.
+ - ``graph_spec``: the best-effort graph of the main pipe.
+ - ``pending_signatures``: qualified refs of pipes still declared as ``PipeSignature`` in
+ the assembled library — the runnability verdict's input.
+ - ``pipe_io_contracts``: per-pipe IO contracts keyed by ``pipe_ref``, built via
+ ``build_pipe_io_contracts`` inside the worker's library window (JSON-Schema rendering
+ resolves bundle-defined structure classes through the loaded library's class registry,
+ so the API side never needs to re-acquire a library).
+ """
dry_run_outputs: dict[str, DryRunOutput]
graph_spec: GraphSpec | None = None
+ # Deliberately REQUIRED (no wire default): a version-skewed worker that doesn't emit
+ # these fields must fail loudly at deserialization, not default to "nothing pending"
+ # and yield a silently wrong is_runnable verdict.
+ pending_signatures: list[str]
+ pipe_io_contracts: dict[str, PipeIOContract]
@activity.defn(name="act_dry_validate")
@@ -85,6 +103,8 @@ async def act_dry_validate(arg: DryValidateArg) -> DryValidateResult:
ValidateBundleError: any validation failure — blueprint/factory/wiring errors, unexpected
dry-run pipe failures, strict-mode signature refusals (the same categorized cascade
the direct-mode route surfaces).
+ PipeIOContractError: a JSON-Schema rendering failure while building `pipe_io_contracts`
+ (non-retryable at the workflow tier, like ValidateBundleError — deterministic).
PipelexError: non-validation failures (config, library, tracing infra).
"""
prev_library_id = get_current_library_id_or_none()
@@ -95,27 +115,35 @@ async def act_dry_validate(arg: DryValidateArg) -> DryValidateResult:
allow_signatures=arg.allow_signatures,
)
library_id = get_current_library_id_or_none()
+ # Explicit body-success flag — NOT sys.exc_info() in the finally, which also sees an
+ # exception the CALLER is currently handling and would wrongly suppress a genuine
+ # teardown failure after a successful body.
+ body_succeeded = False
try:
- # Graph: best-effort (D5), against the SAME loaded library. Pipe resolution sits INSIDE
- # the catch on purpose: an unknown explicit pipe_code degrades to graph_spec=None just
- # like any other graph-arm domain failure — same answer the direct route gives.
- graph_spec: GraphSpec | None = None
- graph_pipe_ref = arg.pipe_code or _qualified_main_pipe(validate_result.blueprints)
- if graph_pipe_ref and library_id:
- try:
- main_pipe = get_required_pipe(pipe_code=graph_pipe_ref)
- graph_spec = await dry_run_pipe_in_process(pipe=main_pipe, library_id=library_id)
- except (PipelexError, ValidationError, FactoryException) as graph_error:
- log.warning(
- f"act_dry_validate: graph dry-run of '{graph_pipe_ref}' did not produce a graph "
- f"({type(graph_error).__name__}); returning validation result without graph_spec"
- )
-
- return DryValidateResult(dry_run_outputs=validate_result.dry_run_result, graph_spec=graph_spec)
+ # Pipe IO contracts: built INSIDE the library window (D10) — the JSON-Schema rendering
+ # resolves bundle-defined structure classes through the loaded library's class registry.
+ pipe_io_contracts = build_pipe_io_contracts(validate_result.pipes)
+
+ # Graph: best-effort (D5), against the SAME loaded library, via the ONE shared
+ # graph-arm implementation — an unknown explicit pipe_code degrades to
+ # graph_spec=None just like any other graph-arm domain failure.
+ graph_spec: GraphSpec | None = await best_effort_graph_spec(
+ pipe_ref=arg.pipe_code or select_primary_blueprint(validate_result.blueprints).main_pipe_ref,
+ library_id=library_id,
+ log_context="act_dry_validate",
+ )
+
+ result = DryValidateResult(
+ dry_run_outputs=validate_result.dry_run_result,
+ graph_spec=graph_spec,
+ pending_signatures=validate_result.pending_signatures,
+ pipe_io_contracts=pipe_io_contracts,
+ )
+ body_succeeded = True
+ return result
finally:
# Restore the caller's outer current-library FIRST so the guarantee survives a teardown
# raise, then tear the validated library down once — mirrors acquire_and_validate.
- primary_error = sys.exc_info()[1]
if prev_library_id is not None and prev_library_id != library_id:
set_current_library(library_id=prev_library_id)
else:
@@ -128,17 +156,9 @@ async def act_dry_validate(arg: DryValidateArg) -> DryValidateResult:
# 422 would name the teardown instead of the user's actual problem) — suppress
# it and let the primary propagate; raise it only when the body succeeded.
# Mirrors PipeRun.run's close_tracer handling.
- if primary_error is None:
+ if body_succeeded:
raise
log.error(
f"act_dry_validate: library teardown also failed after a body error; "
f"raising the original error. Suppressed teardown error: {teardown_error}"
)
-
-
-def _qualified_main_pipe(blueprints: list[PipelexBundleBlueprint]) -> str | None:
- """Return the domain-qualified main_pipe of the first blueprint declaring one, else None."""
- for blueprint in blueprints:
- if blueprint.main_pipe:
- return PipeFactory.make_pipe_ref_with_domain(domain_code=blueprint.domain, pipe_code=blueprint.main_pipe)
- return None
diff --git a/pipelex/temporal/tprl_pipe/dry_validate_dispatch.py b/pipelex/temporal/tprl_pipe/dry_validate_dispatch.py
index bcb2d9776..b03c03cb4 100644
--- a/pipelex/temporal/tprl_pipe/dry_validate_dispatch.py
+++ b/pipelex/temporal/tprl_pipe/dry_validate_dispatch.py
@@ -2,8 +2,10 @@
The single round-trip a Temporal-enabled ``/validate`` caller awaits: dispatch
``WfDryValidate`` (which runs the one ``act_dry_validate`` activity in-process on a worker)
-and get back the per-pipe status map + the best-effort ``GraphSpec``. Used by the API route
-(cross-repo, ``pipelex-api``) and by the Tier-2d e2e submitter script.
+and get back the full worker-computed ``DryValidateResult`` — per-pipe status map,
+best-effort ``GraphSpec``, ``pending_signatures``, and the ``pipe_io_contracts`` IO contracts
+(D10). Used by the API route (cross-repo, ``pipelex-api``) and by the Tier-2d e2e
+submitter script.
"""
from datetime import timedelta
@@ -23,7 +25,7 @@ async def dispatch_dry_validate(
task_queue: str | None = None,
should_auto_connect_temporal: bool = True,
) -> DryValidateResult:
- """Dispatch ``WfDryValidate`` to a worker and await ``{status map, GraphSpec}``.
+ """Dispatch ``WfDryValidate`` to a worker and await the full ``DryValidateResult``.
A validation failure (strict-mode signature refusal, unexpected pipe failure) comes back
as ``WorkflowExecutionError`` carrying the structured ``ErrorReport`` recovered by
@@ -36,7 +38,9 @@ async def dispatch_dry_validate(
should_auto_connect_temporal: Whether the executor may auto-connect the Temporal client.
Returns:
- The activity result: per-pipe status map + best-effort GraphSpec.
+ The activity result: per-pipe status map, best-effort GraphSpec, pending_signatures,
+ and the pipe_io_contracts IO contracts — everything the canonical validation report
+ needs that must be computed worker-side (D10).
"""
worker_config = get_config().temporal.worker_config
executor = WorkflowExecutorFactory[DryValidateArg, DryValidateResult]().create_executor(
diff --git a/pipelex/temporal/tprl_pipe/wf_dry_validate.py b/pipelex/temporal/tprl_pipe/wf_dry_validate.py
index 7862512fa..65aecc31e 100644
--- a/pipelex/temporal/tprl_pipe/wf_dry_validate.py
+++ b/pipelex/temporal/tprl_pipe/wf_dry_validate.py
@@ -26,20 +26,21 @@ class WfDryValidate(WorkflowClass[DryValidateArg, DryValidateResult]):
@workflow.run
async def run(self, workflow_arg: DryValidateArg) -> DryValidateResult:
# D-C5: explicit timeout + retry bounds, deterministic in workflow code (no config reads).
- # Validation is deterministic — its failures must NOT retry. The whole sweep cascade
- # crosses the boundary as ONE type: validate_bundle wraps SignaturesNotAllowedError /
- # DryRunError / PipelexInterpreterError into ValidateBundleError before they escape, and
- # the activity-boundary TemporalError carries the OUTER PipelexError class name as the
- # ApplicationError type (which is what non_retryable_error_types matches). The graph arm
- # never raises domain errors (it degrades to graph_spec=None), so ValidateBundleError is
- # the entire deterministic-failure surface. Everything else (worker crash, transient
- # infra) gets one retry.
+ # Validation is deterministic — its failures must NOT retry. The deterministic-failure
+ # surface crosses the boundary as TWO types: validate_bundle wraps
+ # SignaturesNotAllowedError / DryRunError / PipelexInterpreterError into
+ # ValidateBundleError before they escape, and build_pipe_io_contracts wraps a
+ # JSON-Schema rendering failure into PipeIOContractError; the activity-boundary
+ # TemporalError carries the OUTER PipelexError class name as the ApplicationError
+ # type (which is what non_retryable_error_types matches). The graph arm never raises
+ # domain errors (it degrades to graph_spec=None). Everything else (worker crash,
+ # transient infra) gets one retry.
return await workflow.execute_activity(
act_dry_validate,
arg=workflow_arg,
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(
maximum_attempts=2,
- non_retryable_error_types=["ValidateBundleError"],
+ non_retryable_error_types=["ValidateBundleError", "PipeIOContractError"],
),
)
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/cross_batch_library/library/concepts.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/cross_batch_library/library/concepts.mthds
new file mode 100644
index 000000000..5b5dd9461
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/cross_batch_library/library/concepts.mthds
@@ -0,0 +1,5 @@
+domain = "research"
+description = "Research method domain"
+
+[concept]
+KeyFinding = "A key finding extracted from a source document"
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/cross_batch_library/root.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/cross_batch_library/root.mthds
new file mode 100644
index 000000000..cfab9091f
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/cross_batch_library/root.mthds
@@ -0,0 +1,13 @@
+domain = "research"
+description = "Research root referencing a library concept by bare code"
+
+# `KeyFinding` is declared in `library/concepts.mthds`, loaded as a separate `-L` library directory
+# (a separate load batch). Concept references resolve against the merged library, so the bare code
+# resolves here even though no sibling in this bundle's own batch declares it.
+[pipe.extract_finding]
+type = "PipeLLM"
+description = "Extract a key finding from a document."
+inputs = { doc = "Text" }
+output = "KeyFinding"
+model = "$quick-reasoning"
+prompt = "Extract a key finding from $doc."
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/header_and_definition/concepts.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/header_and_definition/concepts.mthds
new file mode 100644
index 000000000..5b5dd9461
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/header_and_definition/concepts.mthds
@@ -0,0 +1,5 @@
+domain = "research"
+description = "Research method domain"
+
+[concept]
+KeyFinding = "A key finding extracted from a source document"
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/header_and_definition/definition.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/header_and_definition/definition.mthds
new file mode 100644
index 000000000..ad116c8eb
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/header_and_definition/definition.mthds
@@ -0,0 +1,13 @@
+domain = "research"
+description = "Research method definitions"
+
+# Concrete definition of the same pipe code, satisfying the header. The contracts are written with
+# the *qualified* spellings (`native.Text`, `research.KeyFinding`) yet still reconcile with the
+# header's bare spellings — contracts are compared by normalized concept identity, not by string.
+[pipe.find_key_findings]
+type = "PipeLLM"
+description = "Find the key findings in a document."
+inputs = { doc = "native.Text" }
+output = "research.KeyFinding"
+model = "$quick-reasoning"
+prompt = "List the key findings in $doc."
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/header_and_definition/header.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/header_and_definition/header.mthds
new file mode 100644
index 000000000..327f39989
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/header_and_definition/header.mthds
@@ -0,0 +1,9 @@
+domain = "research"
+description = "Research method headers"
+
+# Header: bare native `Text` input, bare same-domain `KeyFinding` output.
+[pipe.find_key_findings]
+type = "PipeSignature"
+description = "Find the key findings in a document (contract only)."
+inputs = { doc = "Text" }
+output = "KeyFinding"
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/qualified_sibling_ref/concepts.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/qualified_sibling_ref/concepts.mthds
new file mode 100644
index 000000000..5b5dd9461
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/qualified_sibling_ref/concepts.mthds
@@ -0,0 +1,5 @@
+domain = "research"
+description = "Research method domain"
+
+[concept]
+KeyFinding = "A key finding extracted from a source document"
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/qualified_sibling_ref/controller.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/qualified_sibling_ref/controller.mthds
new file mode 100644
index 000000000..b076d95f4
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/qualified_sibling_ref/controller.mthds
@@ -0,0 +1,12 @@
+domain = "research"
+description = "Research brief controller (qualified sibling ref)"
+
+# The step references its own-domain pipe by its *qualified* name `research.find_key_findings`,
+# while the concrete definition lives only in the sibling `definition.mthds`. Qualified same-domain
+# references are deferred to the merged library just like bare ones, so this resolves across files.
+[pipe.research_brief]
+type = "PipeSequence"
+description = "Produce a research brief from a document."
+inputs = { doc = "Text" }
+output = "KeyFinding"
+steps = [{ pipe = "research.find_key_findings", result = "findings" }]
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/qualified_sibling_ref/definition.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/qualified_sibling_ref/definition.mthds
new file mode 100644
index 000000000..2bdd08820
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/qualified_sibling_ref/definition.mthds
@@ -0,0 +1,10 @@
+domain = "research"
+description = "Research method definitions"
+
+[pipe.find_key_findings]
+type = "PipeLLM"
+description = "Find the key findings in a document."
+inputs = { doc = "Text" }
+output = "KeyFinding"
+model = "$quick-reasoning"
+prompt = "List the key findings in $doc."
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/bundle.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/bundle.mthds
new file mode 100644
index 000000000..69ad4ea01
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/bundle.mthds
@@ -0,0 +1,23 @@
+domain = "market_research"
+description = "Turn a source document into a concise research brief"
+main_pipe = "write_research_brief"
+
+# Boundary (client-facing) concept, specified fully at Layer 0. Intermediate concepts are introduced
+# later, each by the controller that owns it.
+[concept.ResearchBrief]
+description = "A concise brief distilled from a source document"
+
+[concept.ResearchBrief.structure]
+title = { type = "text", description = "Short title of the brief", required = true }
+summary = { type = "text", description = "One-paragraph summary", required = true }
+key_findings = { type = "list", item_type = "text", description = "Bullet list of the key findings", required = true }
+
+# Layer 0: the whole job captured as ONE signature. The concrete main pipe is added in its own
+# `write_research_brief.mthds` file — `main_pipe` is a reference, not the implementation. This root
+# file is written once and never rewritten.
+[pipe.write_research_brief]
+type = "PipeSignature"
+description = "Read a source document and produce a concise research brief capturing its key findings."
+inputs = { document = "Document" }
+output = "ResearchBrief"
+signature_for = "PipeSequence"
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/draft_brief.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/draft_brief.mthds
new file mode 100644
index 000000000..ac4486a2e
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/draft_brief.mthds
@@ -0,0 +1,18 @@
+domain = "market_research"
+
+# Concrete operator (leaf) satisfying the `draft_brief` header. Consumes the document and the upstream
+# findings whole (no field-read), so `KeyFinding` stays a simple concept.
+[pipe.draft_brief]
+type = "PipeLLM"
+description = "Draft a research brief from a document and its key findings."
+inputs = { document = "Document", findings = "KeyFinding[]" }
+output = "ResearchBrief"
+prompt = """
+Using the document and the key findings below, write a concise research brief.
+
+Document:
+@document
+
+Key findings:
+@findings
+"""
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/find_key_findings.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/find_key_findings.mthds
new file mode 100644
index 000000000..cbdaf84aa
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/find_key_findings.mthds
@@ -0,0 +1,13 @@
+domain = "market_research"
+
+# Concrete operator (leaf) satisfying the `find_key_findings` header declared in the controller file.
+[pipe.find_key_findings]
+type = "PipeLLM"
+description = "Extract the notable findings from a source document."
+inputs = { document = "Document" }
+output = "KeyFinding[]"
+prompt = """
+Read the document and list its notable findings, one per item.
+
+@document
+"""
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/write_research_brief.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/write_research_brief.mthds
new file mode 100644
index 000000000..263b35da1
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/write_research_brief.mthds
@@ -0,0 +1,33 @@
+domain = "market_research"
+
+# Intermediate concept introduced (and declared once) by the controller that owns it.
+[concept]
+KeyFinding = "A single notable finding extracted from the source document"
+
+# Concrete definition of the main pipe — a controller. Same code as the root's PipeSignature header,
+# so it satisfies it at merge (the concrete wins); the contract matches by concept identity.
+[pipe.write_research_brief]
+type = "PipeSequence"
+description = "Find the key findings in the document, then draft a brief from them."
+inputs = { document = "Document" }
+output = "ResearchBrief"
+steps = [
+ { pipe = "find_key_findings", result = "findings" },
+ { pipe = "draft_brief", result = "brief" },
+]
+
+# Forward declarations of the not-yet-built sub-pipes, in this same controller file. Each is a header
+# that joins the backlog and is satisfied later by a concrete definition in its own sibling file.
+[pipe.find_key_findings]
+type = "PipeSignature"
+description = "Extract the notable findings from a source document."
+inputs = { document = "Document" }
+output = "KeyFinding[]"
+signature_for = "PipeLLM"
+
+[pipe.draft_brief]
+type = "PipeSignature"
+description = "Draft a research brief from a document and its key findings."
+inputs = { document = "Document", findings = "KeyFinding[]" }
+output = "ResearchBrief"
+signature_for = "PipeLLM"
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/signature_only/concepts.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/signature_only/concepts.mthds
new file mode 100644
index 000000000..5b5dd9461
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/signature_only/concepts.mthds
@@ -0,0 +1,5 @@
+domain = "research"
+description = "Research method domain"
+
+[concept]
+KeyFinding = "A key finding extracted from a source document"
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/signature_only/header.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/signature_only/header.mthds
new file mode 100644
index 000000000..dd92122b7
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/signature_only/header.mthds
@@ -0,0 +1,18 @@
+domain = "research"
+description = "Research method headers"
+
+# Forward declaration ("header"): a PipeSignature is a contract only, no way of running.
+[pipe.find_key_findings]
+type = "PipeSignature"
+description = "Find the key findings in a document (contract only)."
+inputs = { doc = "Text" }
+output = "KeyFinding"
+
+# A sibling controller may already reference the header by bare same-domain code, even though no
+# concrete definition exists yet — this is the top-down build in progress.
+[pipe.research_brief]
+type = "PipeSequence"
+description = "Produce a research brief from a document."
+inputs = { doc = "Text" }
+output = "KeyFinding"
+steps = [{ pipe = "find_key_findings", result = "findings" }]
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/test_additive_multi_file_library.py b/tests/e2e/pipelex/pipes/additive_multi_file_library/test_additive_multi_file_library.py
new file mode 100644
index 000000000..4a48a84f3
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/test_additive_multi_file_library.py
@@ -0,0 +1,81 @@
+"""End-to-end proof of the additive multi-file library model, backed by real on-disk `.mthds` files.
+
+A same-domain method is authored as separate, additive `.mthds` files (a forward-declared header +
+a separate definition) sharing a non-native concept. The bundles live next to this module — one
+sub-directory per scenario — so the header/definition split is visible as actual files rather than
+inline strings:
+
+ signature_only/ concepts + header (PipeSignature), no definition -> not yet runnable
+ header_and_definition/ concepts + header + concrete definition -> concrete wins, runnable
+ qualified_sibling_ref/ concepts + controller (qualified ref) + definition -> cross-file ref resolves
+ cross_batch_library/ root bundle + a separate `-L` library dir -> bare concept resolves across batches
+
+The shared concept (`KeyFinding`) is deliberately non-native: a native-only contract would pass even
+with the cross-file resolution bug present, so it would not prove anything.
+"""
+
+from collections.abc import Callable
+from pathlib import Path
+
+import pytest
+
+from pipelex.pipeline.validate_bundle import validate_bundle, validate_bundles_from_directory
+
+_BUNDLES_DIR = Path(__file__).parent
+
+
[email protected](loop_scope="class")
+class TestAdditiveMultiFileLibraryE2E:
+ async def test_signature_only_is_not_yet_runnable(self, load_empty_library: Callable[[], str]):
+ """Header alone (no definition): lenient validation passes, the pipe stays a signature, and the
+ unimplemented header is reported as a pending signature — i.e. the bundle is not yet runnable.
+ """
+ load_empty_library()
+ result = await validate_bundles_from_directory(directory=_BUNDLES_DIR / "signature_only", allow_signatures=True)
+
+ pipe_codes = {pipe.code for pipe in result.pipes}
+ assert {"find_key_findings", "research_brief"} <= pipe_codes
+ find_key_findings = next(pipe for pipe in result.pipes if pipe.code == "find_key_findings")
+ assert find_key_findings.is_signature
+ # `is_runnable` on the validate JSON envelope is exactly `not pending_signatures`.
+ assert result.pending_signatures == ["research.find_key_findings"]
+
+ async def test_definition_reconciles_with_header_and_is_runnable(self, load_empty_library: Callable[[], str]):
+ """Adding the concrete definition lets strict validation pass: the concrete replaces the
+ signature, and nothing is left pending — the assembled library is runnable. The header's bare
+ `Text`/`KeyFinding` contract reconciles with the definition's qualified `native.Text`/
+ `research.KeyFinding` spelling, proving the comparison is by normalized concept identity.
+ """
+ load_empty_library()
+ result = await validate_bundles_from_directory(directory=_BUNDLES_DIR / "header_and_definition", allow_signatures=False)
+
+ find_key_findings = next((pipe for pipe in result.pipes if pipe.code == "find_key_findings"), None)
+ assert find_key_findings is not None
+ assert not find_key_findings.is_signature
+ assert result.pending_signatures == []
+
+ async def test_qualified_sibling_pipe_ref_resolves_across_files(self, load_empty_library: Callable[[], str]):
+ """A controller's QUALIFIED same-domain step ref (`research.find_key_findings`) resolves to a
+ concrete pipe declared only in a sibling file.
+ """
+ load_empty_library()
+ result = await validate_bundles_from_directory(directory=_BUNDLES_DIR / "qualified_sibling_ref", allow_signatures=False)
+
+ pipe_codes = {pipe.code for pipe in result.pipes}
+ assert {"research_brief", "find_key_findings"} <= pipe_codes
+ assert result.pending_signatures == []
+
+ async def test_bare_concept_ref_resolves_across_load_batches(self, load_empty_library: Callable[[], str]):
+ """A root bundle references `KeyFinding` by bare code while the concept is declared in a
+ separate `-L` library directory loaded as its own batch.
+ """
+ load_empty_library()
+ scenario_dir = _BUNDLES_DIR / "cross_batch_library"
+ result = await validate_bundle(
+ mthds_file_path=scenario_dir / "root.mthds",
+ library_dirs=[scenario_dir / "library"],
+ allow_signatures=False,
+ )
+
+ assert "extract_finding" in {pipe.code for pipe in result.pipes}
+ assert result.pending_signatures == []
diff --git a/tests/e2e/pipelex/pipes/additive_multi_file_library/test_recursive_refinement.py b/tests/e2e/pipelex/pipes/additive_multi_file_library/test_recursive_refinement.py
new file mode 100644
index 000000000..d322e16dd
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/additive_multi_file_library/test_recursive_refinement.py
@@ -0,0 +1,53 @@
+"""End-to-end proof of a top-down recursive-refinement bundle, backed by real on-disk `.mthds` files.
+
+This is the artifact the `mthds-vibe` skill builds: a same-domain library where the `main_pipe` is a
+controller and its sub-pipes are forward-declared as signatures, with every concrete definition added
+as a separate sibling file. Signatures and concretes reconcile at TWO levels:
+
+ bundle.mthds -> main_pipe `write_research_brief` as a PipeSignature (the whole job)
+ write_research_brief.mthds -> concrete PipeSequence (satisfies the root header) that forward-declares
+ `find_key_findings` + `draft_brief` as signatures, owns `KeyFinding`
+ find_key_findings.mthds -> concrete PipeLLM (satisfies the controller's header)
+ draft_brief.mthds -> concrete PipeLLM (satisfies the controller's header)
+
+So `write_research_brief` appears as a signature in one file and a concrete in another; each sub-pipe
+likewise. After the additive merge the concretes win at every level and the bundle is runnable.
+"""
+
+from collections.abc import Callable
+from pathlib import Path
+
+import pytest
+
+from pipelex.pipe_controllers.sequence.pipe_sequence import PipeSequence
+from pipelex.pipe_operators.llm.pipe_llm import PipeLLM
+from pipelex.pipeline.validate_bundle import validate_bundles_from_directory
+
+_BUNDLE_DIR = Path(__file__).parent / "recursive_refinement"
+
+
[email protected](loop_scope="class")
+class TestRecursiveRefinementBundle:
+ async def test_assembled_bundle_is_runnable_with_concretes_at_every_level(self, load_empty_library: Callable[[], str]):
+ """Strict validation passes: nothing is left pending, and the concrete pipe wins at every level
+ — the controller `main_pipe` over its `find_key_findings` / `draft_brief` signatures.
+ """
+ load_empty_library()
+ result = await validate_bundles_from_directory(directory=_BUNDLE_DIR, allow_signatures=False)
+
+ pipes_by_code = {pipe.code: pipe for pipe in result.pipes}
+ assert {"write_research_brief", "find_key_findings", "draft_brief"} <= set(pipes_by_code)
+
+ # Level 1: the main pipe reconciled from the root's PipeSignature header to the concrete controller.
+ main_pipe = pipes_by_code["write_research_brief"]
+ assert not main_pipe.is_signature
+ assert isinstance(main_pipe, PipeSequence)
+
+ # Level 2: each sub-pipe reconciled from the controller's forward-declared header to a concrete operator.
+ for sub_code in ("find_key_findings", "draft_brief"):
+ sub_pipe = pipes_by_code[sub_code]
+ assert not sub_pipe.is_signature, f"{sub_code} should be concrete after merge"
+ assert isinstance(sub_pipe, PipeLLM)
+
+ # No header left unsatisfied anywhere in the library -> runnable.
+ assert result.pending_signatures == []
diff --git a/tests/integration/pipelex/cli/test_agent_validate_defaults_strict.py b/tests/integration/pipelex/cli/test_agent_validate_defaults_strict.py
index ad0a9e2a8..e2c15812c 100644
--- a/tests/integration/pipelex/cli/test_agent_validate_defaults_strict.py
+++ b/tests/integration/pipelex/cli/test_agent_validate_defaults_strict.py
@@ -66,6 +66,10 @@ class TestAgentValidateDefaultsStrict:
)
)
assert result["success"] is True
- pipe_codes = {entry["pipe_code"] for entry in result["validated_pipes"]}
- assert "agent_sigcli.agent_sig" in pipe_codes
- assert "agent_sigcli.agent_seq" in pipe_codes
+ pipe_refs = {entry["pipe_ref"] for entry in result["validated_pipes"]}
+ assert "agent_sigcli.agent_sig" in pipe_refs
+ assert "agent_sigcli.agent_seq" in pipe_refs
+ # A lenient success that still carries an unimplemented signature is NOT runnable, and the
+ # envelope says so explicitly via is_runnable (derived from the pending_signatures set).
+ assert result["pending_signatures"] == ["agent_sigcli.agent_sig"]
+ assert result["is_runnable"] is False
diff --git a/tests/integration/pipelex/cli/test_agent_validate_pipe_in_bundle.py b/tests/integration/pipelex/cli/test_agent_validate_pipe_in_bundle.py
index 633ab220c..622587d46 100644
--- a/tests/integration/pipelex/cli/test_agent_validate_pipe_in_bundle.py
+++ b/tests/integration/pipelex/cli/test_agent_validate_pipe_in_bundle.py
@@ -130,9 +130,13 @@ class TestAgentValidatePipeInBundle:
)
)
assert result["success"] is True
- pipe_codes = {entry["pipe_code"] for entry in result["validated_pipes"]}
+ pipe_refs = {entry["pipe_ref"] for entry in result["validated_pipes"]}
# Identity is the namespaced pipe_ref (domain.code) on every validate surface.
- assert "slice_bundle.implemented_pipe" in pipe_codes
+ assert "slice_bundle.implemented_pipe" in pipe_refs
+ # pending_signatures is library-wide: the unrelated standalone signature still counts, so even
+ # this successful slice reports the bundle as not-yet-runnable.
+ assert "slice_bundle.draft_pipe" in result["pending_signatures"]
+ assert result["is_runnable"] is False
def test_whole_bundle_strict_still_rejects_unrelated_signature(
self,
@@ -194,6 +198,9 @@ class TestAgentValidatePipeInBundle:
)
)
assert result["success"] is True
- statuses = {entry["pipe_code"]: entry["status"] for entry in result["validated_pipes"]}
+ statuses = {entry["pipe_ref"]: entry["status"] for entry in result["validated_pipes"]}
# Identity is the namespaced pipe_ref (domain.code), not the bare code.
assert statuses == {"slice_xpkg.cross_parallel": "SKIPPED"}
+ # This bundle has no PipeSignature pipes, so it is runnable — the envelope reports it.
+ assert result["pending_signatures"] == []
+ assert result["is_runnable"] is True
diff --git a/tests/integration/pipelex/libraries/test_additive_multi_file_library.py b/tests/integration/pipelex/libraries/test_additive_multi_file_library.py
new file mode 100644
index 000000000..5a80ed8b2
--- /dev/null
+++ b/tests/integration/pipelex/libraries/test_additive_multi_file_library.py
@@ -0,0 +1,78 @@
+"""Error-surfacing cases for the additive multi-file library model.
+
+The positive end-to-end scenarios (signature/definition reconciliation, cross-file bare/qualified
+references, cross-batch concept resolution) live as real on-disk `.mthds` bundles under
+``tests/e2e/pipelex/pipes/additive_multi_file_library/``. This module keeps the negative cases —
+malformed inputs that must surface a structured ``ValidateBundleError`` rather than a raw traceback
+— authored as in-memory strings, since a genuinely-broken bundle has no business sitting on disk.
+
+The shared concept (`KeyFinding`) is deliberately non-native: a native-only contract would pass even
+with the cross-file resolution bug present, so it would not prove anything.
+"""
+
+import tempfile
+from collections.abc import Callable
+from pathlib import Path
+
+import pytest
+
+from pipelex.pipeline.exceptions import ValidateBundleError
+from pipelex.pipeline.validate_bundle import validate_bundle, validate_bundles_from_directory
+
+RESEARCH_CONCEPTS = """
+domain = "research"
+description = "Research method domain"
+
+[concept]
+KeyFinding = "A key finding extracted from a source document"
+"""
+
+# A controller referencing a qualified same-domain pipe declared in no file, to prove the missing
+# reference still surfaces cleanly once per-file pipe validation no longer fires.
+RESEARCH_CONTROLLER_QUALIFIED_MISSING = """
+domain = "research"
+description = "Research brief controller referencing an undeclared qualified pipe"
+
+[pipe.research_brief]
+type = "PipeSequence"
+description = "Produce a research brief from a document."
+inputs = { doc = "Text" }
+output = "KeyFinding"
+steps = [
+ { pipe = "research.totally_missing", result = "findings" },
+]
+"""
+
+# A root pipe referencing a concept declared in no file, to prove the error surfaces cleanly.
+RESEARCH_ROOT_UNDECLARED = """
+domain = "research"
+description = "Research root referencing an undeclared concept"
+
+[pipe.extract_ghost]
+type = "PipeLLM"
+description = "Extract a ghost from a document."
+inputs = { doc = "Text" }
+output = "Ghost"
+model = "$quick-reasoning"
+prompt = "Extract a ghost from $doc."
+"""
+
+
[email protected](loop_scope="class")
+class TestAdditiveMultiFileLibraryErrors:
+ async def test_undeclared_concept_surfaces_clean_validate_bundle_error(self, load_empty_library: Callable[[], str]):
+ """An undeclared concept reference surfaces as a structured ValidateBundleError, not a raw ConceptLibraryError."""
+ load_empty_library()
+ with pytest.raises(ValidateBundleError) as exc_info:
+ await validate_bundle(mthds_contents=[RESEARCH_ROOT_UNDECLARED], library_dirs=[])
+ assert "Ghost" in exc_info.value.message
+
+ async def test_undeclared_qualified_pipe_ref_surfaces_clean_error(self, load_empty_library: Callable[[], str]):
+ """A qualified same-domain step ref to a pipe declared in no file surfaces a clean ValidateBundleError."""
+ load_empty_library()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ directory = Path(tmp_dir)
+ (directory / "concepts.mthds").write_text(RESEARCH_CONCEPTS, encoding="utf-8")
+ (directory / "controller.mthds").write_text(RESEARCH_CONTROLLER_QUALIFIED_MISSING, encoding="utf-8")
+ with pytest.raises(ValidateBundleError, match="totally_missing"):
+ await validate_bundles_from_directory(directory=directory, allow_signatures=False)
diff --git a/tests/integration/pipelex/libraries/test_cross_file_concept_references.py b/tests/integration/pipelex/libraries/test_cross_file_concept_references.py
new file mode 100644
index 000000000..616d30a14
--- /dev/null
+++ b/tests/integration/pipelex/libraries/test_cross_file_concept_references.py
@@ -0,0 +1,89 @@
+"""Integration tests: same-domain concept references resolve across separate load batches.
+
+These exercise the loader-level concept-reference check
+(`validate_concept_references_in_blueprints`, called from `LibraryManager.load_from_blueprints`)
+together with the pipe factory's library-aware same-domain concept guard. A concept declared in a
+prior batch (e.g. a separate `load_from_blueprints` call, as a `-L` library directory produces)
+must resolve when referenced by bare code from a later batch in the same domain.
+"""
+
+from collections.abc import Callable
+
+import pytest
+
+from pipelex.core.interpreter.interpreter import PipelexInterpreter
+from pipelex.hub import get_library_manager
+from pipelex.libraries.concept.exceptions import ConceptLibraryError
+
+CONCEPT_MTHDS = """
+domain = "crossref"
+description = "Cross-reference domain"
+
+[concept]
+Summary = "A summary of a document"
+"""
+
+PIPE_BARE_REF_MTHDS = """
+domain = "crossref"
+description = "Cross-reference domain"
+
+[pipe.make_summary]
+type = "PipeLLM"
+description = "Summarize a document"
+inputs = { doc = "Text" }
+output = "Summary"
+model = "$quick-reasoning"
+prompt = "Summarize $doc."
+"""
+
+PIPE_UNDECLARED_REF_MTHDS = """
+domain = "crossref"
+description = "Cross-reference domain"
+
+[pipe.make_ghost]
+type = "PipeLLM"
+description = "Produce a ghost"
+inputs = { doc = "Text" }
+output = "Ghost"
+model = "$quick-reasoning"
+prompt = "Ghost $doc."
+"""
+
+
+class TestCrossFileConceptReferences:
+ def test_cross_batch_bare_concept_reference_resolves(self, load_empty_library: Callable[[], str]):
+ """A concept declared in batch 1 resolves when referenced by bare code from a separate batch 2."""
+ library_id = load_empty_library()
+ manager = get_library_manager()
+ concept_blueprint = PipelexInterpreter.make_pipelex_bundle_blueprint(mthds_content=CONCEPT_MTHDS)
+ pipe_blueprint = PipelexInterpreter.make_pipelex_bundle_blueprint(mthds_content=PIPE_BARE_REF_MTHDS)
+
+ # Batch 1: declare the concept only.
+ manager.load_from_blueprints(library_id=library_id, blueprints=[concept_blueprint])
+ # Batch 2: a pipe referencing that concept by bare code, loaded in a separate call.
+ loaded_pipes = manager.load_from_blueprints(library_id=library_id, blueprints=[pipe_blueprint])
+
+ assert "make_summary" in {pipe.code for pipe in loaded_pipes}
+ library = manager.get_library(library_id=library_id)
+ assert "crossref.Summary" in library.concept_library.root
+
+ def test_single_batch_bare_concept_reference_resolves(self, load_empty_library: Callable[[], str]):
+ """The same concept + bare reference also resolve when loaded together in one batch."""
+ library_id = load_empty_library()
+ manager = get_library_manager()
+ concept_blueprint = PipelexInterpreter.make_pipelex_bundle_blueprint(mthds_content=CONCEPT_MTHDS)
+ pipe_blueprint = PipelexInterpreter.make_pipelex_bundle_blueprint(mthds_content=PIPE_BARE_REF_MTHDS)
+
+ loaded_pipes = manager.load_from_blueprints(library_id=library_id, blueprints=[concept_blueprint, pipe_blueprint])
+
+ assert "make_summary" in {pipe.code for pipe in loaded_pipes}
+
+ def test_undeclared_concept_reference_raises_concept_library_error(self, load_empty_library: Callable[[], str]):
+ """A bare reference to a concept declared in no batch raises ConceptLibraryError through the loader."""
+ library_id = load_empty_library()
+ manager = get_library_manager()
+ pipe_blueprint = PipelexInterpreter.make_pipelex_bundle_blueprint(mthds_content=PIPE_UNDECLARED_REF_MTHDS)
+
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ manager.load_from_blueprints(library_id=library_id, blueprints=[pipe_blueprint])
+ assert "Ghost" in str(exc_info.value)
diff --git a/tests/integration/pipelex/pipe_signature/test_pipe_signature.py b/tests/integration/pipelex/pipe_signature/test_pipe_signature.py
index 3cdba6ee4..f5d6e640c 100644
--- a/tests/integration/pipelex/pipe_signature/test_pipe_signature.py
+++ b/tests/integration/pipelex/pipe_signature/test_pipe_signature.py
@@ -3,7 +3,6 @@ from typing import TYPE_CHECKING, Callable
import pytest
from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory
-from pipelex.core.pipes.pipe_blueprint import PipeCategory, PipeType
from pipelex.core.pipes.pipe_factory import PipeFactory
from pipelex.core.stuffs.list_content import ListContent
from pipelex.hub import get_current_library
@@ -41,8 +40,10 @@ class TestPipeSignature:
blueprint = make_signature_blueprint(inputs={"doc": "SigTestDoc"}, output="SigTestSummary")
runtime = _make_runtime(blueprint)
assert isinstance(runtime, PipeSignature)
- assert runtime.type == PipeType.PIPE_SIGNATURE
- assert runtime.pipe_category == PipeCategory.PIPE_SIGNATURE
+ # A signature is outside the executable taxonomy: `type` keeps the "PipeSignature" tag while
+ # `pipe_category` is None (no `PipeType`/`PipeCategory` membership).
+ assert runtime.type == "PipeSignature"
+ assert runtime.pipe_category is None
def test_is_signature_true(
self,
diff --git a/tests/integration/pipelex/pipeline/test_dry_run_pipeline_graph.py b/tests/integration/pipelex/pipeline/test_dry_run_pipeline_graph.py
index 54f49b89a..08ec61e8e 100644
--- a/tests/integration/pipelex/pipeline/test_dry_run_pipeline_graph.py
+++ b/tests/integration/pipelex/pipeline/test_dry_run_pipeline_graph.py
@@ -15,7 +15,7 @@ import pytest
from pytest_mock import MockerFixture
from pipelex.config import get_config
-from pipelex.pipe_run.dry_run_pipeline import dry_run_pipeline
+from pipelex.pipeline.dry_run_pipeline import dry_run_pipeline
from pipelex.system.configuration.configs import NdjsonTracingConfig, TracingBackend
_DRY_RUN_GRAPH_DOMAIN = "dry_run_pipeline_graph"
diff --git a/tests/integration/pipelex/pipeline/test_load_concepts_only.py b/tests/integration/pipelex/pipeline/test_load_concepts_only.py
index bcda4b196..6e9dd8fe9 100644
--- a/tests/integration/pipelex/pipeline/test_load_concepts_only.py
+++ b/tests/integration/pipelex/pipeline/test_load_concepts_only.py
@@ -7,6 +7,7 @@ from pathlib import Path
import pytest
from pipelex.hub import get_library_manager
+from pipelex.pipeline.exceptions import ValidateBundleError
from pipelex.pipeline.validate_bundle import (
LoadConceptsOnlyResult,
load_concepts_only,
@@ -238,6 +239,63 @@ address = { type = "concept", concept_ref = "shared.Address", description = "The
assert address is not None
assert customer is not None
+ def test_load_concepts_only_library_dir_sibling_cross_reference(self, load_empty_library: Callable[[], str]):
+ """Sibling files in a library dir resolve same-domain concept refs regardless of load order.
+
+ The referencing file (``a_refers.mthds``) sorts before the declaring file (``b_declares.mthds``),
+ so loading each file as its own one-file batch would validate the reference before its
+ declaration is present and fail. Batching the directory's files together resolves it.
+ """
+ load_empty_library()
+ refers_mthds = """
+domain = "libdom"
+description = "Library domain"
+
+[concept.Order]
+description = "An order"
+
+[concept.Order.structure]
+line_item = { type = "concept", concept_ref = "libdom.LineItem", description = "A line item" }
+"""
+ declares_mthds = """
+domain = "libdom"
+description = "Library domain"
+
+[concept.LineItem]
+description = "A line item"
+
+[concept.LineItem.structure]
+sku = { type = "text", description = "SKU" }
+"""
+ main_mthds = """
+domain = "main"
+description = "Main domain"
+
+[concept.Customer]
+description = "A customer"
+
+[concept.Customer.structure]
+name = { type = "text", description = "Name" }
+"""
+
+ with tempfile.TemporaryDirectory() as lib_dir, tempfile.TemporaryDirectory() as main_dir:
+ # a_refers sorts before b_declares, so a one-file-batch loader would load the
+ # reference before its declaration and raise.
+ (Path(lib_dir) / "a_refers.mthds").write_text(refers_mthds, encoding="utf-8")
+ (Path(lib_dir) / "b_declares.mthds").write_text(declares_mthds, encoding="utf-8")
+ main_mthds_path = Path(main_dir) / "main.mthds"
+ main_mthds_path.write_text(main_mthds, encoding="utf-8")
+
+ result = load_concepts_only(mthds_file_path=main_mthds_path, library_dirs=[Path(lib_dir)])
+
+ assert result.concepts[0].code == "Customer"
+
+ library_manager = get_library_manager()
+ library = library_manager.get_current_library()
+
+ assert library.concept_library.get_required_concept("libdom.Order") is not None
+ assert library.concept_library.get_required_concept("libdom.LineItem") is not None
+
def test_load_concepts_only_with_mthds_content(self, load_empty_library: Callable[[], str]):
"""Test loading concepts from MTHDS content string."""
load_empty_library()
@@ -288,6 +346,40 @@ refines = "Customer"
assert "Customer" in concept_codes
assert "VIPCustomer" in concept_codes
+ def test_load_concepts_only_rejects_dangling_concept_ref(self, load_empty_library: Callable[[], str]):
+ """A dangling concept_ref in a structure field is rejected, matching the full-load path."""
+ load_empty_library()
+ mthds_content = """
+domain = "testapp"
+description = "Test domain with a dangling concept_ref"
+
+[concept.Invoice]
+description = "An invoice"
+
+[concept.Invoice.structure]
+customer = { type = "concept", concept_ref = "testapp.MissingCustomer", description = "The customer" }
+"""
+
+ with pytest.raises(ValidateBundleError, match="MissingCustomer"):
+ load_concepts_only(mthds_contents=[mthds_content])
+
+ def test_load_concepts_only_rejects_dangling_item_concept_ref(self, load_empty_library: Callable[[], str]):
+ """A dangling item_concept_ref in a list structure field is rejected, matching the full-load path."""
+ load_empty_library()
+ mthds_content = """
+domain = "testapp"
+description = "Test domain with a dangling item_concept_ref"
+
+[concept.Order]
+description = "An order"
+
+[concept.Order.structure]
+items = { type = "list", item_type = "concept", item_concept_ref = "testapp.MissingLineItem", description = "Line items" }
+"""
+
+ with pytest.raises(ValidateBundleError, match="MissingLineItem"):
+ load_concepts_only(mthds_contents=[mthds_content])
+
def test_load_concepts_only_directory_skips_pipes(self, load_empty_library: Callable[[], str]):
"""Test that pipes are skipped when loading from directory."""
load_empty_library()
diff --git a/tests/integration/pipelex/pipeline/test_pipe_io_contracts.py b/tests/integration/pipelex/pipeline/test_pipe_io_contracts.py
new file mode 100644
index 000000000..e6f6e8b1f
--- /dev/null
+++ b/tests/integration/pipelex/pipeline/test_pipe_io_contracts.py
@@ -0,0 +1,135 @@
+"""Pin the D6 `build_pipe_io_contracts` builder: typed `PipeIOContract` entries keyed by `pipe_ref`.
+
+Covers the two combinations the hosted builder it was ported from never saw:
+
+- **`PipeSignature` pipes in a lenient batch** — a forward-declared header validated with
+ ``allow_signatures=True`` gets an IO-contract entry like any concrete pipe (its declared
+ contract is exactly what a top-down build needs), keyed by its namespaced ``pipe_ref``.
+- **Multiplicity entry shapes** — a single output reports ``multiplicity="single"``, a
+ list output (``Concept[]``) reports ``multiplicity="variable"`` with an array JSON Schema
+ on list-typed inputs.
+
+The builder runs against the open validation library (`validate_bundle` leaves it loaded on
+success), mirroring how the protocol wrapper consumes it.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+import pytest
+from pydantic import PydanticUserError
+
+from pipelex.hub import clear_current_library, get_current_library_id_or_none, get_library_manager, set_current_library
+from pipelex.pipeline.exceptions import PipeIOContractError
+from pipelex.pipeline.pipe_io_contracts import IOMultiplicity, build_pipe_io_contracts
+from pipelex.pipeline.validate_bundle import validate_bundle
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ from pytest_mock import MockerFixture
+
+
+def _teardown_validation_library(outer_library_id: str) -> None:
+ """Tear down the library `validate_bundle` left open on success, restoring the outer one."""
+ validation_library_id = get_current_library_id_or_none()
+ if validation_library_id is not None and validation_library_id != outer_library_id:
+ set_current_library(library_id=outer_library_id)
+ get_library_manager().teardown(library_id=validation_library_id)
+ clear_current_library()
+
+
+_SIGNATURE_ONLY_DIR = Path(__file__).parents[3] / "e2e" / "pipelex" / "pipes" / "additive_multi_file_library" / "signature_only"
+
+_MULTIPLICITY_MTHDS = """
+domain = "structures_test"
+description = "Bundle exercising single and variable output multiplicities"
+
+[concept.Item]
+description = "An item"
+
+[pipe.make_one]
+type = "PipeLLM"
+description = "Make one item"
+inputs = { doc = "Text" }
+output = "Item"
+prompt = "Make one item from $doc"
+
+[pipe.make_many]
+type = "PipeLLM"
+description = "Make many items"
+inputs = { docs = "Text[]" }
+output = "Item[]"
+prompt = "Make items from:\\n@docs"
+"""
+
+
[email protected](loop_scope="class")
+class TestBuildPipeIOContracts:
+ async def test_multiplicity_entry_shapes(self, load_empty_library: Callable[[], str]) -> None:
+ """Entries are keyed by namespaced pipe_ref; output multiplicity is single vs variable."""
+ outer_library_id = load_empty_library()
+ try:
+ result = await validate_bundle(mthds_contents=[_MULTIPLICITY_MTHDS])
+ io_contracts = build_pipe_io_contracts(result.pipes)
+ finally:
+ _teardown_validation_library(outer_library_id)
+
+ assert set(io_contracts) == {"structures_test.make_one", "structures_test.make_many"}
+
+ make_one = io_contracts["structures_test.make_one"]
+ assert make_one.output.concept_code == "structures_test.Item"
+ assert make_one.output.multiplicity == IOMultiplicity.SINGLE
+ assert make_one.inputs["doc"].concept_code == "native.Text"
+ assert make_one.inputs["doc"].json_schema
+
+ make_many = io_contracts["structures_test.make_many"]
+ assert make_many.output.concept_code == "structures_test.Item"
+ assert make_many.output.multiplicity == IOMultiplicity.VARIABLE
+ # A list-typed input renders an array JSON Schema.
+ assert make_many.inputs["docs"].json_schema.get("type") == "array"
+
+ async def test_schema_render_failure_converts_to_structured_error(
+ self,
+ load_empty_library: Callable[[], str],
+ mocker: MockerFixture,
+ ) -> None:
+ """A pydantic schema-generation failure converts to PipeIOContractError with pipe/input
+ context — never a raw third-party error (which the Temporal boundary would not convert
+ and Temporal would pointlessly retry).
+ """
+ outer_library_id = load_empty_library()
+ try:
+ result = await validate_bundle(mthds_contents=[_MULTIPLICITY_MTHDS])
+ mocker.patch(
+ "pipelex.core.pipes.stuff_spec.stuff_spec.StuffSpec.render_stuff_spec",
+ side_effect=PydanticUserError("simulated schema-generation failure", code=None),
+ )
+ with pytest.raises(PipeIOContractError, match="Failed to render the JSON Schema"):
+ build_pipe_io_contracts(result.pipes)
+ finally:
+ _teardown_validation_library(outer_library_id)
+
+ async def test_signature_pipes_in_lenient_batch(self, load_empty_library: Callable[[], str]) -> None:
+ """A PipeSignature header in a lenient batch gets a contract entry like any concrete pipe."""
+ outer_library_id = load_empty_library()
+ try:
+ mthds_contents = [
+ (_SIGNATURE_ONLY_DIR / "concepts.mthds").read_text(encoding="utf-8"),
+ (_SIGNATURE_ONLY_DIR / "header.mthds").read_text(encoding="utf-8"),
+ ]
+ result = await validate_bundle(mthds_contents=mthds_contents, allow_signatures=True)
+ io_contracts = build_pipe_io_contracts(result.pipes)
+ finally:
+ _teardown_validation_library(outer_library_id)
+
+ # The signature (forward declaration) and the controller referencing it both report contracts.
+ signature_contract = io_contracts["research.find_key_findings"]
+ assert signature_contract.output.concept_code == "research.KeyFinding"
+ assert signature_contract.output.multiplicity == IOMultiplicity.SINGLE
+ assert signature_contract.inputs["doc"].concept_code == "native.Text"
+
+ controller_contract = io_contracts["research.research_brief"]
+ assert controller_contract.output.concept_code == "research.KeyFinding"
diff --git a/tests/integration/pipelex/pipeline/test_protocol_validate.py b/tests/integration/pipelex/pipeline/test_protocol_validate.py
new file mode 100644
index 000000000..bc936c320
--- /dev/null
+++ b/tests/integration/pipelex/pipeline/test_protocol_validate.py
@@ -0,0 +1,302 @@
+"""Protocol-level `validate` on :class:`PipelexMTHDSProtocol`.
+
+Pins the runnability verdict on the protocol surface: `pending_signatures` (qualified refs of
+pipes still declared as ``PipeSignature`` in the assembled library) and
+``is_runnable = not pending_signatures`` — mirroring the agent-CLI / builder validate envelopes —
+so a top-down build driving the runtime through the MTHDS Protocol can see what remains to
+implement. Also pins the wrapper's library-lifecycle contract: ``validate_bundle`` deliberately
+leaves its validation library open and current on success, and the protocol wrapper (a long-lived
+entry point) must restore the caller's current-library and tear the validation library down.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+import pytest
+
+from pipelex.hub import clear_current_library, get_current_library_id_or_none, get_library_manager, set_current_library
+from pipelex.libraries.exceptions import LibraryError
+from pipelex.pipe_run.exceptions import DryRunError
+from pipelex.pipeline.bundle_validator import DryRunStatus
+from pipelex.pipeline.exceptions import PipeIOContractError, ValidateBundleError
+from pipelex.pipeline.runner import PipelexMTHDSProtocol
+from pipelex.pipeline.validation_report import PipelexValidationReport
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ from pytest_mock import MockerFixture
+
+_SIGNATURE_ONLY_DIR = Path(__file__).parents[3] / "e2e" / "pipelex" / "pipes" / "additive_multi_file_library" / "signature_only"
+
+_COMPLETE_MTHDS = """
+domain = "protocol_validate"
+description = "Minimal complete bundle for protocol-validate tests"
+
+[concept.Summary]
+description = "A summary"
+
+[pipe.summarize]
+type = "PipeLLM"
+description = "Summarize a text"
+inputs = { doc = "Text" }
+output = "Summary"
+prompt = "Summarize $doc"
+"""
+
+_MAIN_PIPE_MTHDS = """
+domain = "protocol_validate_graph"
+description = "Bundle declaring a main_pipe, for the graph arm"
+main_pipe = "outline_then_summarize"
+
+[concept.Summary]
+description = "A summary"
+
+[pipe.outline_then_summarize]
+type = "PipeSequence"
+description = "Outline then summarize"
+inputs = { doc = "Text" }
+output = "Summary"
+steps = [
+ { pipe = "outline", result = "outline_text" },
+ { pipe = "summarize", result = "summary" },
+]
+
+[pipe.outline]
+type = "PipeLLM"
+description = "Outline a text"
+inputs = { doc = "Text" }
+output = "Text"
+prompt = "Outline $doc"
+
+[pipe.summarize]
+type = "PipeLLM"
+description = "Summarize an outline"
+inputs = { outline_text = "Text" }
+output = "Summary"
+prompt = "Summarize $outline_text"
+"""
+
+
+def _signature_only_contents() -> list[str]:
+ return [
+ (_SIGNATURE_ONLY_DIR / "concepts.mthds").read_text(encoding="utf-8"),
+ (_SIGNATURE_ONLY_DIR / "header.mthds").read_text(encoding="utf-8"),
+ ]
+
+
[email protected](loop_scope="class")
+class TestProtocolValidate:
+ async def test_complete_bundle_is_runnable(self, load_empty_library: Callable[[], str]) -> None:
+ """A complete bundle reports nothing pending and is runnable; the structural artifacts are populated."""
+ load_empty_library()
+ try:
+ runner = PipelexMTHDSProtocol()
+ report = await runner.validate(mthds_contents=[_COMPLETE_MTHDS])
+
+ assert isinstance(report, PipelexValidationReport)
+ assert report.pending_signatures == []
+ assert report.is_runnable is True
+ assert report.bundle_blueprint.domain == "protocol_validate"
+ # `pipe_io_contracts` and `validated_pipes` are keyed/identified by namespaced pipe_ref.
+ assert report.pipe_io_contracts["protocol_validate.summarize"].output.concept_code == "protocol_validate.Summary"
+ assert {(entry["pipe_ref"], entry["status"]) for entry in report.validated_pipes} == {
+ ("protocol_validate.summarize", DryRunStatus.SUCCESS)
+ }
+ # No main_pipe declared → no graph.
+ assert report.graph_spec is None
+ finally:
+ clear_current_library()
+
+ async def test_pending_signatures_reported_on_lenient_path(self, load_empty_library: Callable[[], str]) -> None:
+ """An unsatisfied header validated with ``allow_signatures=True`` is reported as pending — not yet runnable."""
+ load_empty_library()
+ try:
+ runner = PipelexMTHDSProtocol()
+ report = await runner.validate(mthds_contents=_signature_only_contents(), allow_signatures=True)
+
+ assert isinstance(report, PipelexValidationReport)
+ assert report.pending_signatures == ["research.find_key_findings"]
+ assert report.is_runnable is False
+ finally:
+ clear_current_library()
+
+ async def test_graph_populated_on_main_pipe_bundle(
+ self,
+ load_empty_library: Callable[[], str],
+ mocker: MockerFixture,
+ ) -> None:
+ """A bundle declaring a main_pipe gets a best-effort graph_spec covering the controller
+ topology (D4) — and the REAL graph run leaves the library lifecycle intact (no mock here:
+ pins that the in-process dry-run does not move the current-library under the wrapper).
+ """
+ outer_library_id = load_empty_library()
+ set_current_library(library_id=outer_library_id)
+ try:
+ library_manager = get_library_manager()
+ open_library_spy = mocker.spy(library_manager, "open_library")
+ teardown_spy = mocker.spy(library_manager, "teardown")
+
+ runner = PipelexMTHDSProtocol()
+ report = await runner.validate(mthds_contents=[_MAIN_PIPE_MTHDS])
+
+ assert isinstance(report, PipelexValidationReport)
+ assert report.graph_spec is not None
+ traced_pipe_codes = {node.pipe_code for node in report.graph_spec.nodes if node.pipe_code}
+ assert {"outline_then_summarize", "outline", "summarize"} <= traced_pipe_codes
+ # The graph arm does not disturb the rest of the report.
+ assert report.is_runnable is True
+ assert "protocol_validate_graph.outline_then_summarize" in report.pipe_io_contracts
+
+ # Lifecycle with the real graph run: outer current-library restored, validation
+ # library torn down.
+ assert get_current_library_id_or_none() == outer_library_id
+ validation_library_id, _ = open_library_spy.spy_return
+ latest_teardown = teardown_spy.call_args_list[-1]
+ assert latest_teardown.kwargs["library_id"] == validation_library_id
+ finally:
+ clear_current_library()
+
+ async def test_graph_failure_mid_window_degrades_and_lifecycle_holds(
+ self,
+ load_empty_library: Callable[[], str],
+ mocker: MockerFixture,
+ ) -> None:
+ """A graph-arm domain failure INSIDE the library window degrades to graph_spec=None with
+ validation still successful, and the wrapper's restore/teardown guarantee still holds (D4).
+ """
+ outer_library_id = load_empty_library()
+ set_current_library(library_id=outer_library_id)
+ try:
+ library_manager = get_library_manager()
+ open_library_spy = mocker.spy(library_manager, "open_library")
+ teardown_spy = mocker.spy(library_manager, "teardown")
+ mocker.patch(
+ "pipelex.pipe_run.dry_run_in_process.dry_run_pipe_in_process",
+ side_effect=DryRunError("simulated graph dry-run failure"),
+ )
+
+ runner = PipelexMTHDSProtocol()
+ report = await runner.validate(mthds_contents=[_MAIN_PIPE_MTHDS])
+
+ assert isinstance(report, PipelexValidationReport)
+ assert report.graph_spec is None
+ assert report.is_runnable is True
+ assert "protocol_validate_graph.outline_then_summarize" in report.pipe_io_contracts
+
+ # Lifecycle: the caller's current-library is restored and the validation library torn down.
+ assert get_current_library_id_or_none() == outer_library_id
+ validation_library_id, _ = open_library_spy.spy_return
+ latest_teardown = teardown_spy.call_args_list[-1]
+ assert latest_teardown.kwargs["library_id"] == validation_library_id
+ finally:
+ clear_current_library()
+
+ async def test_empty_contents_raises_structured_error(self) -> None:
+ """An EMPTY mthds_contents list (not None) raises a structured ValidateBundleError, never a raw IndexError.
+
+ Regression pin: the empty list passes ``validate_bundle``'s ``is not None`` param check, and
+ pre-guard it flowed into ``select_primary_blueprint([])`` → ``IndexError`` on the protocol surface.
+ """
+ runner = PipelexMTHDSProtocol()
+ with pytest.raises(ValidateBundleError, match="must not be empty"):
+ await runner.validate(mthds_contents=[])
+
+ async def test_strict_mode_raises_on_unsatisfied_signature(self, load_empty_library: Callable[[], str]) -> None:
+ """With the strict default (``allow_signatures=False``), an unsatisfied signature raises instead of reporting."""
+ load_empty_library()
+ try:
+ runner = PipelexMTHDSProtocol()
+ with pytest.raises(ValidateBundleError):
+ await runner.validate(mthds_contents=_signature_only_contents())
+ finally:
+ clear_current_library()
+
+ async def test_success_restores_outer_library_and_tears_down_validation_library(
+ self,
+ load_empty_library: Callable[[], str],
+ mocker: MockerFixture,
+ ) -> None:
+ """On success, the wrapper restores the caller's current-library and tears the validation library down.
+
+ ``validate_bundle`` deliberately leaves its validation library OPEN and current on success
+ (the CLI surfaces consume it before process exit) — the protocol wrapper must not.
+ """
+ outer_library_id = load_empty_library()
+ set_current_library(library_id=outer_library_id)
+ try:
+ library_manager = get_library_manager()
+ open_library_spy = mocker.spy(library_manager, "open_library")
+ teardown_spy = mocker.spy(library_manager, "teardown")
+
+ runner = PipelexMTHDSProtocol()
+ await runner.validate(mthds_contents=[_COMPLETE_MTHDS])
+
+ assert get_current_library_id_or_none() == outer_library_id
+ validation_library_id, _ = open_library_spy.spy_return
+ latest_teardown = teardown_spy.call_args_list[-1]
+ assert latest_teardown.kwargs["library_id"] == validation_library_id
+ finally:
+ clear_current_library()
+
+ async def test_success_clears_when_no_outer_library(self) -> None:
+ """With no outer current-library, a successful validate leaves no current library behind."""
+ clear_current_library()
+ runner = PipelexMTHDSProtocol()
+ await runner.validate(mthds_contents=[_COMPLETE_MTHDS])
+ assert get_current_library_id_or_none() is None
+
+ async def test_teardown_failure_after_success_propagates(
+ self,
+ load_empty_library: Callable[[], str],
+ mocker: MockerFixture,
+ ) -> None:
+ """A teardown raise after a SUCCESSFUL body propagates to the caller (never silently
+ suppressed), with the caller's current-library already restored first.
+
+ Also a regression pin for the body-success detection: the wrapper must key suppression
+ on its OWN body outcome, not on ``sys.exc_info()`` — which also sees an exception the
+ caller happens to be handling and would wrongly swallow the teardown failure here.
+ """
+ outer_library_id = load_empty_library()
+ set_current_library(library_id=outer_library_id)
+ try:
+ library_manager = get_library_manager()
+ mocker.patch.object(library_manager, "teardown", side_effect=LibraryError("simulated teardown failure"))
+
+ runner = PipelexMTHDSProtocol()
+ with pytest.raises(LibraryError, match="simulated teardown failure"):
+ await runner.validate(mthds_contents=[_COMPLETE_MTHDS])
+
+ assert get_current_library_id_or_none() == outer_library_id
+ finally:
+ clear_current_library()
+
+ async def test_body_failure_mid_window_propagates_over_teardown_failure(
+ self,
+ load_empty_library: Callable[[], str],
+ mocker: MockerFixture,
+ ) -> None:
+ """When the body fails INSIDE the library window and teardown ALSO fails, the BODY's
+ error reaches the caller (the teardown error is suppressed and logged) and the caller's
+ current-library is restored — the failure path of the wrapper's lifecycle contract.
+ """
+ outer_library_id = load_empty_library()
+ set_current_library(library_id=outer_library_id)
+ try:
+ library_manager = get_library_manager()
+ mocker.patch(
+ "pipelex.pipeline.runner.build_pipe_io_contracts",
+ side_effect=PipeIOContractError(message="simulated render failure"),
+ )
+ mocker.patch.object(library_manager, "teardown", side_effect=LibraryError("simulated teardown failure"))
+
+ runner = PipelexMTHDSProtocol()
+ with pytest.raises(PipeIOContractError, match="simulated render failure"):
+ await runner.validate(mthds_contents=[_COMPLETE_MTHDS])
+
+ assert get_current_library_id_or_none() == outer_library_id
+ finally:
+ clear_current_library()
diff --git a/tests/integration/pipelex/temporal/test_dry_run_graph_in_process.py b/tests/integration/pipelex/temporal/test_dry_run_graph_in_process.py
index a884705ad..0026ba652 100644
--- a/tests/integration/pipelex/temporal/test_dry_run_graph_in_process.py
+++ b/tests/integration/pipelex/temporal/test_dry_run_graph_in_process.py
@@ -28,7 +28,7 @@ from pytest_mock import MockerFixture
from pipelex.cogt.content_generation.content_generator import ContentGenerator
from pipelex.graph.graphspec import GraphSpec
from pipelex.hub import get_library_manager, get_pipelex_hub, get_required_pipe, scoped_current_library
-from pipelex.pipe_run.dry_run_pipeline import dry_run_pipe_in_process
+from pipelex.pipe_run.dry_run_in_process import dry_run_pipe_in_process
from pipelex.pipeline.execution_seams import acquire_library
from pipelex.temporal.tprl.workflow_caller import WorkflowExecutor
from pipelex.temporal.tprl_content_generation.content_generator_in_workflow import ContentGeneratorInWorkflow
diff --git a/tests/integration/pipelex/temporal/test_dry_validate_activity_in_memory.py b/tests/integration/pipelex/temporal/test_dry_validate_activity_in_memory.py
index 32699bb3e..13b4d06f4 100644
--- a/tests/integration/pipelex/temporal/test_dry_validate_activity_in_memory.py
+++ b/tests/integration/pipelex/temporal/test_dry_validate_activity_in_memory.py
@@ -33,6 +33,7 @@ from pipelex.config import get_config
from pipelex.hub import clear_current_library, get_current_library_id_or_none, get_library_manager
from pipelex.pipe_run.exceptions import DryRunError
from pipelex.pipeline.bundle_validator import DryRunStatus
+from pipelex.pipeline.exceptions import PipeIOContractError
from pipelex.pipeline.execution_seams import acquire_library
from pipelex.pipeline.validate_bundle import validate_bundle
from pipelex.system.configuration.configs import NdjsonTracingConfig, TracingBackend
@@ -213,10 +214,23 @@ class TestDryValidateActivityInMemory:
traced_pipe_codes = {node.pipe_code for node in result.graph_spec.nodes if node.pipe_code}
assert {"alpha_sequence", "alpha_first", "alpha_second"} <= traced_pipe_codes
+ # D10: the worker-computed wire fields cross the boundary — pipe_io_contracts keyed by
+ # namespaced pipe_ref with typed entries surviving (de)serialization, and a complete
+ # bundle reporting nothing pending.
+ assert result.pending_signatures == []
+ assert set(result.pipe_io_contracts) == {
+ "dry_validate_alpha.alpha_sequence",
+ "dry_validate_alpha.alpha_first",
+ "dry_validate_alpha.alpha_second",
+ }
+ sequence_contract = result.pipe_io_contracts["dry_validate_alpha.alpha_sequence"]
+ assert sequence_contract.inputs["subject"].concept_code == "native.Text"
+ assert sequence_contract.output.concept_code == "native.Text"
+
async def test_graph_failure_is_best_effort(self, temporal_client: TemporalClient, mocker: MockerFixture) -> None:
"""D5: an expected dry-run failure in the graph arm yields graph_spec=None, validation still OK."""
mocker.patch(
- "pipelex.temporal.tprl_pipe.act_dry_validate.dry_run_pipe_in_process",
+ "pipelex.pipe_run.dry_run_in_process.dry_run_pipe_in_process",
side_effect=DryRunError("simulated graph dry-run failure"),
)
@@ -228,7 +242,7 @@ class TestDryValidateActivityInMemory:
async def test_graph_bug_propagates(self, temporal_client: TemporalClient, mocker: MockerFixture) -> None:
"""D5 (bug-propagates arm): a non-Pipelex programming bug in the graph arm fails the run."""
mocker.patch(
- "pipelex.temporal.tprl_pipe.act_dry_validate.dry_run_pipe_in_process",
+ "pipelex.pipe_run.dry_run_in_process.dry_run_pipe_in_process",
side_effect=KeyError("simulated programming bug"),
)
@@ -255,11 +269,17 @@ class TestDryValidateActivityInMemory:
assert "dry_validate_sig.unimplemented_sig" in error_report.message
async def test_signatures_allowed_in_lenient_mode(self, temporal_client: TemporalClient) -> None:
- """The same signature bundle validates in lenient mode (allow_signatures=True)."""
+ """The same signature bundle validates in lenient mode (allow_signatures=True), and the
+ runnability verdict's input crosses the boundary (D10/F5): the unsatisfied header is
+ reported in pending_signatures, with a structures entry like any concrete pipe.
+ """
result = await self._execute(temporal_client, DryValidateArg(mthds_contents=[_SIGNATURE_MTHDS], allow_signatures=True))
assert result.dry_run_outputs["dry_validate_sig.sig_caller"].status == DryRunStatus.SUCCESS
assert result.graph_spec is not None
+ assert result.pending_signatures == ["dry_validate_sig.unimplemented_sig"]
+ assert "dry_validate_sig.unimplemented_sig" in result.pipe_io_contracts
+ assert result.pipe_io_contracts["dry_validate_sig.unimplemented_sig"].output.concept_code == "native.Text"
async def test_validation_failure_does_not_retry_activity(self, temporal_client: TemporalClient, mocker: MockerFixture) -> None:
"""D-C5 regression: a deterministic validation failure must run the activity exactly once.
@@ -275,6 +295,21 @@ class TestDryValidateActivityInMemory:
await self._execute(temporal_client, DryValidateArg(mthds_contents=[_SIGNATURE_MTHDS], allow_signatures=False))
assert sweep_spy.call_count == 1
+ async def test_pipe_io_contracts_failure_does_not_retry_activity(self, temporal_client: TemporalClient, mocker: MockerFixture) -> None:
+ """PipeIOContractError is non-retryable at the workflow tier, like ValidateBundleError —
+ a deterministic schema-render failure must run the activity exactly once. Pins the
+ string match on the ApplicationError type name in wf_dry_validate's retry policy: if
+ the class is renamed without updating the policy, the sweep silently re-runs and only
+ this assertion catches it.
+ """
+ io_contracts_mock = mocker.patch(
+ "pipelex.temporal.tprl_pipe.act_dry_validate.build_pipe_io_contracts",
+ side_effect=PipeIOContractError(message="simulated schema render failure"),
+ )
+ with pytest.raises(WorkflowFailureError):
+ await self._execute(temporal_client, DryValidateArg(mthds_contents=[_ALPHA_MTHDS]))
+ assert io_contracts_mock.call_count == 1
+
async def test_no_main_pipe_and_no_pipe_code_yields_no_graph(self, temporal_client: TemporalClient) -> None:
"""Without a declared main_pipe and without an explicit pipe_code, the graph arm is
skipped: validation succeeds with graph_spec=None.
diff --git a/tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py b/tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py
index 2bcc4ffc4..b8dd1a593 100644
--- a/tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py
+++ b/tests/unit/pipelex/builder/pipe/test_pipe_signature_spec.py
@@ -36,8 +36,9 @@ class TestPipeSignatureSpec:
assert with_hint.signature_for is PipeType.PIPE_LLM
def test_signature_for_rejects_pipe_signature(self) -> None:
+ # Structural: `PipeSignature` is not a `PipeType`, so the string cannot coerce into the field.
with pytest.raises(ValidationError):
- _make_minimal_signature(signature_for=PipeType.PIPE_SIGNATURE)
+ _make_minimal_signature(signature_for="PipeSignature")
def test_inputs_accept_multiplicity(self) -> None:
var_list = _make_minimal_signature(inputs={"docs": "Document[]"})
diff --git a/tests/unit/pipelex/cli/agent_cli/test_validate_format.py b/tests/unit/pipelex/cli/agent_cli/test_validate_format.py
index 6e3cfd545..b62a92f3c 100644
--- a/tests/unit/pipelex/cli/agent_cli/test_validate_format.py
+++ b/tests/unit/pipelex/cli/agent_cli/test_validate_format.py
@@ -23,7 +23,7 @@ class TestValidateFormat:
"""Patch the validate pipe command's dependencies."""
result: dict[str, Any] = {
"success": True,
- "validated_pipes": [{"pipe_code": "p1", "status": "SUCCESS"}],
+ "validated_pipes": [{"pipe_ref": "p1", "status": "SUCCESS"}],
"total_pipes": 1,
}
mocker.patch(f"{VALIDATE_PIPE_MODULE}.make_pipelex_for_agent_cli")
diff --git a/tests/unit/pipelex/cli/agent_cli/test_validate_output_helpers.py b/tests/unit/pipelex/cli/agent_cli/test_validate_output_helpers.py
new file mode 100644
index 000000000..8cdd943b1
--- /dev/null
+++ b/tests/unit/pipelex/cli/agent_cli/test_validate_output_helpers.py
@@ -0,0 +1,73 @@
+"""Unit tests for the agent CLI validate markdown renderer (`format_validate_markdown`)."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from pipelex.cli.agent_cli.commands.validate._output_helpers import format_validate_markdown # noqa: PLC2701
+
+
+class TestFormatValidateMarkdown:
+ def test_renders_pending_signatures_section_with_not_runnable_verdict(self):
+ """A populated pending_signatures list renders the verbatim section heading, an explicit
+ "NOT yet runnable" verdict, and each ref as a bullet.
+ """
+ result: dict[str, Any] = {
+ "success": True,
+ "bundle_path": "/fake/method.mthds",
+ "validated_pipes": [{"pipe_ref": "research.research_brief", "status": "SUCCESS"}],
+ "total_pipes": 1,
+ "pending_signatures": ["research.find_key_findings", "research.rank_findings"],
+ "is_runnable": False,
+ }
+
+ markdown = format_validate_markdown(result)
+
+ assert markdown.startswith("# Validation passed")
+ # Heading kept verbatim — a downstream plugin reads this exact string.
+ assert "## Pending signatures (2)" in markdown
+ # Explicit negative verdict, with the count, immediately above the list.
+ assert "⚠️ This method is NOT yet runnable" in markdown
+ assert "2 pipe(s) are still `PipeSignature` placeholders" in markdown
+ assert "- `research.find_key_findings`" in markdown
+ assert "- `research.rank_findings`" in markdown
+ # The verdict must precede the verbatim heading — consumers expect the note directly above it.
+ assert markdown.index("⚠️ This method is NOT yet runnable") < markdown.index("## Pending signatures")
+
+ def test_renders_runnable_verdict_for_complete_bundle(self):
+ """A present-but-empty pending_signatures (complete bundle) renders an explicit runnable
+ verdict and no "Pending signatures" section.
+ """
+ result: dict[str, Any] = {
+ "success": True,
+ "bundle_path": "/fake/method.mthds",
+ "validated_pipes": [{"pipe_ref": "research.research_brief", "status": "SUCCESS"}],
+ "total_pipes": 1,
+ "pending_signatures": [],
+ "is_runnable": True,
+ }
+
+ markdown = format_validate_markdown(result)
+
+ assert markdown.startswith("# Validation passed")
+ assert "✅ All pipes are concretely implemented" in markdown
+ assert "this method is runnable." in markdown
+ assert "Pending signatures" not in markdown
+
+ def test_omits_runnability_verdict_when_key_absent(self):
+ """The `validate all` / `validate pipe` shape omits the `pending_signatures` key entirely —
+ so no runnability verdict (positive or negative) leaks onto those non-bundle surfaces.
+ """
+ without_key: dict[str, Any] = {
+ "success": True,
+ "validated_pipes": [{"pipe_ref": "research.research_brief", "status": "SUCCESS"}],
+ "total_pipes": 1,
+ }
+
+ markdown = format_validate_markdown(without_key)
+
+ assert markdown.startswith("# Validation passed")
+ assert "Pending signatures" not in markdown
+ assert "runnable" not in markdown
+ assert "✅" not in markdown
+ assert "⚠️" not in markdown
diff --git a/tests/unit/pipelex/cli/test_agent_validate_cmd.py b/tests/unit/pipelex/cli/test_agent_validate_cmd.py
index 54f773127..306434f45 100644
--- a/tests/unit/pipelex/cli/test_agent_validate_cmd.py
+++ b/tests/unit/pipelex/cli/test_agent_validate_cmd.py
@@ -47,7 +47,7 @@ class TestValidateBundleCmd:
validation_result: dict[str, Any] = {
"success": True,
"bundle_path": str(mthds_file),
- "validated_pipes": [{"pipe_code": "my_pipe", "status": "SUCCESS"}],
+ "validated_pipes": [{"pipe_ref": "my_pipe", "status": "SUCCESS"}],
"total_pipes": 1,
}
mocker.patch(
diff --git a/tests/unit/pipelex/cli/test_pipe_cmd.py b/tests/unit/pipelex/cli/test_pipe_cmd.py
index 1fc762809..e14723fe0 100644
--- a/tests/unit/pipelex/cli/test_pipe_cmd.py
+++ b/tests/unit/pipelex/cli/test_pipe_cmd.py
@@ -116,6 +116,56 @@ class TestCliPipeCmd:
assert "step_one" in toml
assert "step_two" in toml
+ def test_search_fields_appear_in_toml(self) -> None:
+ """PipeSearch type-specific fields (prompt, model, filters) must round-trip to TOML."""
+ spec = parse_pipe_spec(
+ "PipeSearch",
+ {
+ "pipe_code": "my_search",
+ "description": "Search pipe",
+ "inputs": {"topic": "Text"},
+ "output": "Text",
+ "model": "$search-default",
+ "prompt": "Latest news about $topic",
+ "from_date": "2025-01-01",
+ "to_date": "2025-06-01",
+ "include_domains": ["reuters.com", "bbc.com"],
+ "exclude_domains": ["example.com"],
+ "max_results": 5,
+ },
+ )
+ toml = _pipe_spec_to_toml(spec)
+ assert 'type = "PipeSearch"' in toml
+ assert 'model = "$search-default"' in toml
+ assert 'prompt = "Latest news about $topic"' in toml
+ assert 'from_date = "2025-01-01"' in toml
+ assert 'to_date = "2025-06-01"' in toml
+ assert "reuters.com" in toml
+ assert "bbc.com" in toml
+ assert "example.com" in toml
+ assert "max_results = 5" in toml
+
+ def test_search_optional_filters_omitted_in_toml(self) -> None:
+ """Unset PipeSearch filters must not appear in the TOML (only prompt is required)."""
+ spec = parse_pipe_spec(
+ "PipeSearch",
+ {
+ "pipe_code": "bare_search",
+ "description": "Minimal search pipe",
+ "inputs": {"topic": "Text"},
+ "output": "Text",
+ "prompt": "About $topic",
+ },
+ )
+ toml = _pipe_spec_to_toml(spec)
+ assert 'prompt = "About $topic"' in toml
+ assert "model =" not in toml
+ assert "from_date" not in toml
+ assert "to_date" not in toml
+ assert "include_domains" not in toml
+ assert "exclude_domains" not in toml
+ assert "max_results" not in toml
+
def test_llm_no_model_omits_model_in_toml(self) -> None:
"""When model is None, no model line should appear in the TOML."""
spec = parse_pipe_spec(
diff --git a/tests/unit/pipelex/core/bundles/test_pipelex_bundle_blueprint_concept_construction.py b/tests/unit/pipelex/core/bundles/test_pipelex_bundle_blueprint_concept_construction.py
new file mode 100644
index 000000000..6f5d2b5b1
--- /dev/null
+++ b/tests/unit/pipelex/core/bundles/test_pipelex_bundle_blueprint_concept_construction.py
@@ -0,0 +1,262 @@
+from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
+from pipelex.core.concepts.concept_blueprint import ConceptBlueprint
+from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprint, ConceptStructureBlueprintFieldType
+from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint
+
+
+class TestPipelexBundleBlueprintConceptConstruction:
+ """Construction smoke tests for concept references in PipelexBundleBlueprint.
+
+ A bundle no longer validates same-domain concept references per file: a concept declared in a
+ sibling file may be referenced here, so construction always succeeds regardless of declaration.
+ Reference resolution against the merged library now lives in
+ tests/unit/pipelex/libraries/test_library_crate_concept_references.py. These tests pin that the
+ various concept-reference shapes still parse and construct.
+ """
+
+ def test_valid_native_concept_in_pipe_output(self):
+ """Native concepts like Text construct without declaration."""
+ bundle = PipelexBundleBlueprint(
+ domain="test_domain",
+ description="Test bundle",
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ type="PipeLLM",
+ description="Test pipe",
+ output="Text",
+ prompt="Hello",
+ ),
+ },
+ )
+ assert bundle.pipe is not None
+ assert "my_pipe" in bundle.pipe
+
+ def test_valid_native_concept_in_pipe_input(self):
+ """Native concepts in inputs construct without declaration."""
+ bundle = PipelexBundleBlueprint(
+ domain="test_domain",
+ description="Test bundle",
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ type="PipeLLM",
+ description="Test pipe",
+ inputs={"data": "Text", "image": "Image"},
+ output="Text",
+ prompt="Process $data and $image",
+ ),
+ },
+ )
+ assert bundle.pipe is not None
+
+ def test_valid_declared_local_concept_in_pipe_output(self):
+ """A local concept declared in the bundle and used in a pipe output constructs."""
+ bundle = PipelexBundleBlueprint(
+ domain="test_domain",
+ description="Test bundle",
+ concept={"MyCustomConcept": "A custom concept"},
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ type="PipeLLM",
+ description="Test pipe",
+ output="MyCustomConcept",
+ prompt="Generate something",
+ ),
+ },
+ )
+ assert bundle.concept is not None
+ assert "MyCustomConcept" in bundle.concept
+
+ def test_valid_declared_local_concept_in_pipe_input(self):
+ """A local concept declared in the bundle and used in a pipe input constructs."""
+ bundle = PipelexBundleBlueprint(
+ domain="test_domain",
+ description="Test bundle",
+ concept={"InputData": "Input data concept"},
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ type="PipeLLM",
+ description="Test pipe",
+ inputs={"data": "InputData"},
+ output="Text",
+ prompt="Process $data",
+ ),
+ },
+ )
+ assert bundle.concept is not None
+
+ def test_valid_same_domain_concept_ref_declared(self):
+ """A same-domain concept ref (domain.Concept) constructs."""
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="Test bundle",
+ concept={"MyCustomConcept": "A custom concept"},
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ type="PipeLLM",
+ description="Test pipe",
+ output="my_domain.MyCustomConcept",
+ prompt="Generate something",
+ ),
+ },
+ )
+ assert bundle.concept is not None
+
+ def test_valid_external_domain_concept_ref(self):
+ """An external-domain concept ref constructs (resolved later via dependencies)."""
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="Test bundle",
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ type="PipeLLM",
+ description="Test pipe",
+ inputs={"external_data": "other_domain.ExternalConcept"},
+ output="Text",
+ prompt="Process $external_data",
+ ),
+ },
+ )
+ assert bundle.pipe is not None
+
+ def test_valid_native_concept_with_domain_prefix(self):
+ """Native concepts with the native. prefix construct."""
+ bundle = PipelexBundleBlueprint(
+ domain="test_domain",
+ description="Test bundle",
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ type="PipeLLM",
+ description="Test pipe",
+ output="native.Text",
+ prompt="Hello",
+ ),
+ },
+ )
+ assert bundle.pipe is not None
+
+ def test_valid_concept_with_multiplicity(self):
+ """Concepts with multiplicity brackets construct."""
+ bundle = PipelexBundleBlueprint(
+ domain="test_domain",
+ description="Test bundle",
+ concept={"Item": "An item concept"},
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ type="PipeLLM",
+ description="Test pipe",
+ inputs={"items": "Item[]"},
+ output="Text[3]",
+ prompt="Process $items",
+ ),
+ },
+ )
+ assert bundle.pipe is not None
+
+ def test_valid_declared_concept_in_refines(self):
+ """A concept refining another concept declared in the bundle constructs."""
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="Test bundle",
+ concept={
+ "BaseConcept": "Base concept",
+ "DerivedConcept": ConceptBlueprint(
+ description="Derived concept",
+ refines="BaseConcept",
+ ),
+ },
+ )
+ assert bundle.concept is not None
+ assert "DerivedConcept" in bundle.concept
+
+ def test_valid_native_concept_in_refines(self):
+ """A concept refining a native concept constructs."""
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="Test bundle",
+ concept={
+ "MyTextConcept": ConceptBlueprint(
+ description="A text-based concept",
+ refines="Text",
+ ),
+ },
+ )
+ assert bundle.concept is not None
+
+ def test_valid_concept_ref_in_structure(self):
+ """A concept ref in a structure field constructs."""
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="Test bundle",
+ concept={
+ "Address": "An address concept",
+ "Person": ConceptBlueprint(
+ description="A person concept",
+ structure={
+ "name": "The person's name",
+ "address": ConceptStructureBlueprint(
+ description="The person's address",
+ type=ConceptStructureBlueprintFieldType.CONCEPT,
+ concept_ref="Address",
+ ),
+ },
+ ),
+ },
+ )
+ assert bundle.concept is not None
+
+ def test_valid_item_concept_ref_in_structure(self):
+ """An item concept ref in a list structure field constructs."""
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="Test bundle",
+ concept={
+ "LineItem": "A line item concept",
+ "Order": ConceptBlueprint(
+ description="An order concept",
+ structure={
+ "order_id": "The order ID",
+ "items": ConceptStructureBlueprint(
+ description="The order items",
+ type=ConceptStructureBlueprintFieldType.LIST,
+ item_type="concept",
+ item_concept_ref="LineItem",
+ ),
+ },
+ ),
+ },
+ )
+ assert bundle.concept is not None
+
+ def test_valid_hierarchical_domain_concept_ref_output(self):
+ """A hierarchical same-domain concept ref in a pipe output constructs."""
+ bundle = PipelexBundleBlueprint(
+ domain="legal.contracts",
+ description="Test bundle",
+ concept={"NonCompeteClause": "A non-compete clause concept"},
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ type="PipeLLM",
+ description="Test pipe",
+ output="legal.contracts.NonCompeteClause",
+ prompt="Generate something",
+ ),
+ },
+ )
+ assert bundle.concept is not None
+
+ def test_valid_hierarchical_domain_external_concept_ref(self):
+ """An external concept ref from a different hierarchical domain constructs."""
+ bundle = PipelexBundleBlueprint(
+ domain="legal.contracts",
+ description="Test bundle",
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ type="PipeLLM",
+ description="Test pipe",
+ inputs={"score": "scoring.WeightedScore"},
+ output="Text",
+ prompt="Process $score",
+ ),
+ },
+ )
+ assert bundle.pipe is not None
diff --git a/tests/unit/pipelex/core/bundles/test_pipelex_bundle_blueprint_concept_validation.py b/tests/unit/pipelex/core/bundles/test_pipelex_bundle_blueprint_concept_validation.py
deleted file mode 100644
index 6c35ce7ad..000000000
--- a/tests/unit/pipelex/core/bundles/test_pipelex_bundle_blueprint_concept_validation.py
+++ /dev/null
@@ -1,502 +0,0 @@
-import pytest
-from pydantic import ValidationError
-
-from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
-from pipelex.core.concepts.concept_blueprint import ConceptBlueprint
-from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprint, ConceptStructureBlueprintFieldType
-from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint
-
-
-class TestPipelexBundleBlueprintConceptValidation:
- """Test validation of local concept references in PipelexBundleBlueprint."""
-
- # ========== VALID CASES ==========
-
- def test_valid_native_concept_in_pipe_output(self):
- """Native concepts like Text should be valid without declaration."""
- bundle = PipelexBundleBlueprint(
- domain="test_domain",
- description="Test bundle",
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- output="Text",
- prompt="Hello",
- ),
- },
- )
- assert bundle.pipe is not None
- assert "my_pipe" in bundle.pipe
-
- def test_valid_native_concept_in_pipe_input(self):
- """Native concepts in inputs should be valid without declaration."""
- bundle = PipelexBundleBlueprint(
- domain="test_domain",
- description="Test bundle",
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- inputs={"data": "Text", "image": "Image"},
- output="Text",
- prompt="Process $data and $image",
- ),
- },
- )
- assert bundle.pipe is not None
-
- def test_valid_declared_local_concept_in_pipe_output(self):
- """Local concept that is declared in the bundle should be valid."""
- bundle = PipelexBundleBlueprint(
- domain="test_domain",
- description="Test bundle",
- concept={"MyCustomConcept": "A custom concept"},
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- output="MyCustomConcept",
- prompt="Generate something",
- ),
- },
- )
- assert bundle.concept is not None
- assert "MyCustomConcept" in bundle.concept
-
- def test_valid_declared_local_concept_in_pipe_input(self):
- """Local concept in inputs that is declared should be valid."""
- bundle = PipelexBundleBlueprint(
- domain="test_domain",
- description="Test bundle",
- concept={"InputData": "Input data concept"},
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- inputs={"data": "InputData"},
- output="Text",
- prompt="Process $data",
- ),
- },
- )
- assert bundle.concept is not None
-
- def test_valid_same_domain_concept_ref_declared(self):
- """Same-domain concept ref (domain.Concept) that is declared should be valid."""
- bundle = PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- concept={"MyCustomConcept": "A custom concept"},
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- output="my_domain.MyCustomConcept",
- prompt="Generate something",
- ),
- },
- )
- assert bundle.concept is not None
-
- def test_valid_external_domain_concept_ref_not_validated(self):
- """External domain concept ref should not be validated (assumed to be from dependency)."""
- bundle = PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- inputs={"external_data": "other_domain.ExternalConcept"},
- output="Text",
- prompt="Process $external_data",
- ),
- },
- )
- assert bundle.pipe is not None
-
- def test_valid_native_concept_with_domain_prefix(self):
- """Native concepts with native. prefix should be valid."""
- bundle = PipelexBundleBlueprint(
- domain="test_domain",
- description="Test bundle",
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- output="native.Text",
- prompt="Hello",
- ),
- },
- )
- assert bundle.pipe is not None
-
- def test_valid_concept_with_multiplicity(self):
- """Concepts with multiplicity brackets should be validated correctly."""
- bundle = PipelexBundleBlueprint(
- domain="test_domain",
- description="Test bundle",
- concept={"Item": "An item concept"},
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- inputs={"items": "Item[]"},
- output="Text[3]",
- prompt="Process $items",
- ),
- },
- )
- assert bundle.pipe is not None
-
- def test_valid_declared_concept_in_refines(self):
- """Concept declared in the bundle can be referenced in refines field."""
- bundle = PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- concept={
- "BaseConcept": "Base concept",
- "DerivedConcept": ConceptBlueprint(
- description="Derived concept",
- refines="BaseConcept",
- ),
- },
- )
- assert bundle.concept is not None
- assert "DerivedConcept" in bundle.concept
-
- def test_valid_native_concept_in_refines(self):
- """Native concepts can be referenced in refines without declaration."""
- bundle = PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- concept={
- "MyTextConcept": ConceptBlueprint(
- description="A text-based concept",
- refines="Text",
- ),
- },
- )
- assert bundle.concept is not None
-
- def test_valid_concept_ref_in_structure(self):
- """Concept refs in structure fields should be validated."""
- bundle = PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- concept={
- "Address": "An address concept",
- "Person": ConceptBlueprint(
- description="A person concept",
- structure={
- "name": "The person's name",
- "address": ConceptStructureBlueprint(
- description="The person's address",
- type=ConceptStructureBlueprintFieldType.CONCEPT,
- concept_ref="Address",
- ),
- },
- ),
- },
- )
- assert bundle.concept is not None
-
- def test_valid_item_concept_ref_in_structure(self):
- """Item concept refs in list fields should be validated."""
- bundle = PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- concept={
- "LineItem": "A line item concept",
- "Order": ConceptBlueprint(
- description="An order concept",
- structure={
- "order_id": "The order ID",
- "items": ConceptStructureBlueprint(
- description="The order items",
- type=ConceptStructureBlueprintFieldType.LIST,
- item_type="concept",
- item_concept_ref="LineItem",
- ),
- },
- ),
- },
- )
- assert bundle.concept is not None
-
- # ========== HIERARCHICAL DOMAIN CASES ==========
-
- def test_valid_hierarchical_domain_concept_ref_output(self):
- """Hierarchical domain concept ref for same domain should be valid."""
- bundle = PipelexBundleBlueprint(
- domain="legal.contracts",
- description="Test bundle",
- concept={"NonCompeteClause": "A non-compete clause concept"},
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- output="legal.contracts.NonCompeteClause",
- prompt="Generate something",
- ),
- },
- )
- assert bundle.concept is not None
-
- def test_valid_hierarchical_domain_external_concept_ref(self):
- """External concept ref from a different hierarchical domain should be skipped."""
- bundle = PipelexBundleBlueprint(
- domain="legal.contracts",
- description="Test bundle",
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- inputs={"score": "scoring.WeightedScore"},
- output="Text",
- prompt="Process $score",
- ),
- },
- )
- assert bundle.pipe is not None
-
- def test_invalid_hierarchical_domain_undeclared_same_domain(self):
- """Hierarchical same-domain concept ref that is not declared should raise error."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="legal.contracts",
- description="Test bundle",
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- output="legal.contracts.Missing",
- prompt="Generate something",
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "Missing" in error_message
- assert "not declared in domain" in error_message
-
- # ========== INVALID CASES ==========
-
- def test_invalid_undeclared_local_concept_in_pipe_output(self):
- """Undeclared local concept in pipe output should raise error."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="test_domain",
- description="Test bundle",
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- output="UndeclaredConcept",
- prompt="Generate something",
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "UndeclaredConcept" in error_message
- assert "pipe.my_pipe.output" in error_message
- assert "not declared in domain" in error_message
-
- def test_invalid_undeclared_local_concept_in_pipe_input(self):
- """Undeclared local concept in pipe input should raise error."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="test_domain",
- description="Test bundle",
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- inputs={"data": "UndeclaredInput"},
- output="Text",
- prompt="Process $data",
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "UndeclaredInput" in error_message
- assert "pipe.my_pipe.inputs.data" in error_message
-
- def test_invalid_undeclared_same_domain_concept_ref(self):
- """Same-domain concept ref that is not declared should raise error."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- output="my_domain.NotDeclaredConcept",
- prompt="Generate something",
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "NotDeclaredConcept" in error_message
- assert "pipe.my_pipe.output" in error_message
-
- def test_invalid_undeclared_concept_in_refines(self):
- """Undeclared concept in refines field should raise error."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- concept={
- "DerivedConcept": ConceptBlueprint(
- description="Derived concept",
- refines="NonExistentBaseConcept",
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "NonExistentBaseConcept" in error_message
- assert "concept.DerivedConcept.refines" in error_message
-
- def test_invalid_undeclared_concept_ref_in_structure(self):
- """Undeclared concept ref in structure field should raise error."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- concept={
- "Person": ConceptBlueprint(
- description="A person concept",
- structure={
- "name": "The person's name",
- "address": ConceptStructureBlueprint(
- description="The person's address",
- type=ConceptStructureBlueprintFieldType.CONCEPT,
- concept_ref="UndeclaredAddress",
- ),
- },
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "UndeclaredAddress" in error_message
- assert "concept.Person.structure.address.concept_ref" in error_message
-
- def test_invalid_undeclared_item_concept_ref_in_structure(self):
- """Undeclared item concept ref in list field should raise error."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- concept={
- "Order": ConceptBlueprint(
- description="An order concept",
- structure={
- "order_id": "The order ID",
- "items": ConceptStructureBlueprint(
- description="The order items",
- type=ConceptStructureBlueprintFieldType.LIST,
- item_type="concept",
- item_concept_ref="UndeclaredLineItem",
- ),
- },
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "UndeclaredLineItem" in error_message
- assert "concept.Order.structure.items.item_concept_ref" in error_message
-
- def test_invalid_undeclared_concept_with_multiplicity(self):
- """Undeclared concept with multiplicity brackets should raise error."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="test_domain",
- description="Test bundle",
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- inputs={"items": "UndeclaredItem[]"},
- output="Text",
- prompt="Process $items",
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "UndeclaredItem" in error_message
- assert "pipe.my_pipe.inputs.items" in error_message
-
- def test_invalid_multiple_undeclared_concepts(self):
- """Multiple undeclared concepts should all be reported in error."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="test_domain",
- description="Test bundle",
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- inputs={"input1": "Undeclared1", "input2": "Undeclared2"},
- output="Undeclared3",
- prompt="Process $input1 and $input2",
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "Undeclared1" in error_message
- assert "Undeclared2" in error_message
- assert "Undeclared3" in error_message
-
- def test_error_message_includes_declared_concepts(self):
- """Error message should include list of declared concepts for debugging."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="test_domain",
- description="Test bundle",
- concept={
- "DeclaredConcept1": "First declared concept",
- "DeclaredConcept2": "Second declared concept",
- },
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- output="UndeclaredConcept",
- prompt="Generate",
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "DeclaredConcept1" in error_message
- assert "DeclaredConcept2" in error_message
-
- def test_error_message_includes_native_concepts(self):
- """Error message should mention native concepts."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="test_domain",
- description="Test bundle",
- pipe={
- "my_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Test pipe",
- output="UndeclaredConcept",
- prompt="Generate",
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "Native concepts" in error_message
- assert "Text" in error_message
diff --git a/tests/unit/pipelex/core/bundles/test_pipelex_bundle_blueprint_pipe_validation.py b/tests/unit/pipelex/core/bundles/test_pipelex_bundle_blueprint_pipe_validation.py
deleted file mode 100644
index 65a7264b7..000000000
--- a/tests/unit/pipelex/core/bundles/test_pipelex_bundle_blueprint_pipe_validation.py
+++ /dev/null
@@ -1,194 +0,0 @@
-import pytest
-from pydantic import ValidationError
-
-from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
-from pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprint
-from pipelex.pipe_controllers.condition.pipe_condition_blueprint import PipeConditionBlueprint
-from pipelex.pipe_controllers.sequence.pipe_sequence_blueprint import PipeSequenceBlueprint
-from pipelex.pipe_controllers.sub_pipe_blueprint import SubPipeBlueprint
-from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint
-
-
-class TestPipelexBundleBlueprintPipeValidation:
- """Test validation of pipe references in PipelexBundleBlueprint."""
-
- # ========== VALID CASES ==========
-
- def test_valid_bare_step_refs_to_local_pipes(self):
- """Bare step refs (no domain prefix) should pass without validation at bundle level."""
- bundle = PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- concept={"Result": "A result concept"},
- pipe={
- "step1": PipeLLMBlueprint(
- type="PipeLLM",
- description="Step 1",
- output="Text",
- prompt="Hello",
- ),
- "step2": PipeLLMBlueprint(
- type="PipeLLM",
- description="Step 2",
- output="Result",
- prompt="Process",
- ),
- "my_sequence": PipeSequenceBlueprint(
- type="PipeSequence",
- description="Main sequence",
- output="Result",
- steps=[
- SubPipeBlueprint(pipe="step1", result="intermediate"),
- SubPipeBlueprint(pipe="step2", result="final"),
- ],
- ),
- },
- )
- assert bundle.pipe is not None
-
- def test_valid_external_pipe_ref_in_sequence(self):
- """External domain-qualified pipe ref should be skipped (not validated locally)."""
- bundle = PipelexBundleBlueprint(
- domain="orchestration",
- description="Test bundle",
- pipe={
- "my_sequence": PipeSequenceBlueprint(
- type="PipeSequence",
- description="Orchestration sequence",
- output="Text",
- steps=[
- SubPipeBlueprint(pipe="scoring.compute_score", result="score"),
- ],
- ),
- },
- )
- assert bundle.pipe is not None
-
- def test_valid_special_outcomes_not_treated_as_pipe_refs(self):
- """Special outcomes like 'fail' and 'continue' should not be validated as pipe refs."""
- bundle = PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- concept={"Result": "A result concept"},
- pipe={
- "good_pipe": PipeLLMBlueprint(
- type="PipeLLM",
- description="Good pipe",
- output="Result",
- prompt="Do something",
- ),
- "my_condition": PipeConditionBlueprint(
- type="PipeCondition",
- description="Condition check",
- output="Result",
- expression="True",
- outcomes={"True": "good_pipe"},
- default_outcome="fail",
- ),
- },
- )
- assert bundle.pipe is not None
-
- def test_valid_external_batch_pipe_ref(self):
- """External domain-qualified branch_pipe_code should be skipped."""
- bundle = PipelexBundleBlueprint(
- domain="orchestration",
- description="Test bundle",
- pipe={
- "my_batch": PipeBatchBlueprint(
- type="PipeBatch",
- description="Batch process",
- output="Text[]",
- inputs={"items": "Text[]"},
- branch_pipe_code="scoring.process_item",
- input_list_name="items",
- input_item_name="item",
- ),
- },
- )
- assert bundle.pipe is not None
-
- def test_valid_bare_ref_to_nonexistent_pipe(self):
- """Bare refs to pipes not declared locally should pass (deferred to package-level)."""
- bundle = PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- pipe={
- "my_sequence": PipeSequenceBlueprint(
- type="PipeSequence",
- description="Main sequence",
- output="Text",
- steps=[
- SubPipeBlueprint(pipe="nonexistent_step", result="something"),
- ],
- ),
- },
- )
- assert bundle.pipe is not None
-
- # ========== INVALID CASES ==========
-
- def test_invalid_same_domain_pipe_ref_to_nonexistent_pipe(self):
- """Same-domain qualified pipe ref to a non-existent pipe should raise error."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- pipe={
- "my_sequence": PipeSequenceBlueprint(
- type="PipeSequence",
- description="Main sequence",
- output="Text",
- steps=[
- SubPipeBlueprint(pipe="my_domain.nonexistent_pipe", result="something"),
- ],
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "my_domain.nonexistent_pipe" in error_message
- assert "not declared in domain" in error_message
-
- def test_invalid_same_domain_batch_pipe_ref(self):
- """Same-domain qualified branch_pipe_code to non-existent pipe should raise error."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- pipe={
- "my_batch": PipeBatchBlueprint(
- type="PipeBatch",
- description="Batch process",
- output="Text[]",
- inputs={"items": "Text[]"},
- branch_pipe_code="my_domain.nonexistent_branch",
- input_list_name="items",
- input_item_name="item",
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "my_domain.nonexistent_branch" in error_message
-
- def test_invalid_same_domain_condition_outcome_ref(self):
- """Same-domain qualified outcome pipe ref to non-existent pipe should raise error."""
- with pytest.raises(ValidationError) as exc_info:
- PipelexBundleBlueprint(
- domain="my_domain",
- description="Test bundle",
- pipe={
- "my_condition": PipeConditionBlueprint(
- type="PipeCondition",
- description="Condition check",
- output="Text",
- expression="True",
- outcomes={"True": "my_domain.nonexistent_handler"},
- default_outcome="fail",
- ),
- },
- )
-
- error_message = str(exc_info.value)
- assert "my_domain.nonexistent_handler" in error_message
diff --git a/tests/unit/pipelex/core/pipes/output/test_output_renderer_anything_formats.py b/tests/unit/pipelex/core/pipes/output/test_output_renderer_anything_formats.py
index e146a3e26..d74f643ce 100644
--- a/tests/unit/pipelex/core/pipes/output/test_output_renderer_anything_formats.py
+++ b/tests/unit/pipelex/core/pipes/output/test_output_renderer_anything_formats.py
@@ -13,6 +13,7 @@ GET_REQUIRED_PIPE_TARGET = "pipelex.core.pipes.output.output_renderer.get_requir
def _make_anything_condition_pipe(mocker: MockerFixture, mapped_pipe_code: str) -> Any:
condition_pipe = mocker.MagicMock()
condition_pipe.type = "PipeCondition"
+ condition_pipe.is_signature = False
condition_pipe.output.concept.code = "Anything"
condition_pipe.pipe_dependencies.return_value = {mapped_pipe_code}
return condition_pipe
@@ -20,6 +21,7 @@ def _make_anything_condition_pipe(mocker: MockerFixture, mapped_pipe_code: str)
def _make_mapped_pipe(mocker: MockerFixture, concept_ref: str, rendered: dict[str, Any]) -> Any:
mapped_pipe = mocker.MagicMock()
+ mapped_pipe.is_signature = False
mapped_pipe.output.concept.concept_ref = concept_ref
mapped_pipe.output.render_stuff_spec.return_value = rendered
return mapped_pipe
@@ -38,6 +40,7 @@ class TestRenderOutputAnythingFormats:
"""An Anything output with no determinable possible outputs raises a ValueError naming native.Anything."""
anything_pipe = mocker.MagicMock()
anything_pipe.type = "PipeLLM"
+ anything_pipe.is_signature = False
anything_pipe.output.concept.code = "Anything"
with pytest.raises(ValueError, match=r"native\.Anything"):
diff --git a/tests/unit/pipelex/core/pipes/output/test_output_renderer_collect_condition.py b/tests/unit/pipelex/core/pipes/output/test_output_renderer_collect_condition.py
index 5298ec27a..35ab25ce3 100644
--- a/tests/unit/pipelex/core/pipes/output/test_output_renderer_collect_condition.py
+++ b/tests/unit/pipelex/core/pipes/output/test_output_renderer_collect_condition.py
@@ -13,12 +13,14 @@ GET_REQUIRED_PIPE_TARGET = "pipelex.core.pipes.output.output_renderer.get_requir
def _make_condition_pipe(mocker: MockerFixture, dependencies: set[str]) -> Any:
condition_pipe = mocker.MagicMock()
condition_pipe.type = "PipeCondition"
+ condition_pipe.is_signature = False
condition_pipe.pipe_dependencies.return_value = dependencies
return condition_pipe
def _make_mapped_pipe(mocker: MockerFixture, concept_ref: str) -> Any:
mapped_pipe = mocker.MagicMock()
+ mapped_pipe.is_signature = False
mapped_pipe.output.concept.concept_ref = concept_ref
return mapped_pipe
@@ -104,6 +106,7 @@ class TestCollectPossibleOutputsCondition:
"""Operator pipe types have no mapped outputs to collect."""
operator_pipe = mocker.MagicMock()
operator_pipe.type = pipe_type
+ operator_pipe.is_signature = False
get_pipe_mock = mocker.patch(GET_REQUIRED_PIPE_TARGET)
result = _collect_possible_outputs(operator_pipe)
diff --git a/tests/unit/pipelex/core/pipes/output/test_output_renderer_collect_sequence.py b/tests/unit/pipelex/core/pipes/output/test_output_renderer_collect_sequence.py
index 6140239ad..5ecfc1317 100644
--- a/tests/unit/pipelex/core/pipes/output/test_output_renderer_collect_sequence.py
+++ b/tests/unit/pipelex/core/pipes/output/test_output_renderer_collect_sequence.py
@@ -13,6 +13,7 @@ GET_REQUIRED_PIPE_TARGET = "pipelex.core.pipes.output.output_renderer.get_requir
def _make_sequence_pipe(mocker: MockerFixture, sub_pipe_codes: list[str]) -> Any:
sequence_pipe = mocker.MagicMock()
sequence_pipe.type = "PipeSequence"
+ sequence_pipe.is_signature = False
sub_pipes: list[Any] = []
for sub_pipe_code in sub_pipe_codes:
sub_pipe = mocker.MagicMock()
@@ -25,6 +26,7 @@ def _make_sequence_pipe(mocker: MockerFixture, sub_pipe_codes: list[str]) -> Any
def _make_concrete_pipe(mocker: MockerFixture, concept_ref: str) -> Any:
concrete_pipe = mocker.MagicMock()
concrete_pipe.type = "PipeLLM"
+ concrete_pipe.is_signature = False
concrete_pipe.output.concept.code = "Text"
concrete_pipe.output.concept.concept_ref = concept_ref
return concrete_pipe
diff --git a/tests/unit/pipelex/core/pipes/test_pipe_abstract_signature_surface.py b/tests/unit/pipelex/core/pipes/test_pipe_abstract_signature_surface.py
index cfe1ddca3..661b2a483 100644
--- a/tests/unit/pipelex/core/pipes/test_pipe_abstract_signature_surface.py
+++ b/tests/unit/pipelex/core/pipes/test_pipe_abstract_signature_surface.py
@@ -35,9 +35,12 @@ class TestPipeAbstractSignatureSurface:
stub = _StubPipe(pipe_category="PipeController")
assert _is_signature_of(stub) is False
- def test_is_signature_true_for_signature_category(self) -> None:
+ def test_is_signature_false_ignores_pipe_category(self) -> None:
+ # Identity is class-based now: the base descriptor returns False regardless of `pipe_category` —
+ # even the legacy "PipeSignature" string no longer flips it. `PipeSignature` overrides to True
+ # (covered by the signature integration tests, which need a real `StuffSpec`/`Concept`).
stub = _StubPipe(pipe_category="PipeSignature")
- assert _is_signature_of(stub) is True
+ assert _is_signature_of(stub) is False
def test_pipe_dependencies_default_returns_empty_set(self) -> None:
stub = _StubPipe(pipe_category="PipeOperator")
diff --git a/tests/unit/pipelex/core/pipes/test_pipe_blueprint.py b/tests/unit/pipelex/core/pipes/test_pipe_blueprint.py
index 63e0ea232..f996aa56e 100644
--- a/tests/unit/pipelex/core/pipes/test_pipe_blueprint.py
+++ b/tests/unit/pipelex/core/pipes/test_pipe_blueprint.py
@@ -38,8 +38,6 @@ class TestPipeBlueprintValidation:
pipe_type = PipeType.PIPE_LLM
case PipeCategory.PIPE_CONTROLLER:
pipe_type = PipeType.PIPE_SEQUENCE
- case PipeCategory.PIPE_SIGNATURE:
- pipe_type = PipeType.PIPE_SIGNATURE
blueprint = ConcretePipeBlueprint(
type=pipe_type,
pipe_category=category_enum,
diff --git a/tests/unit/pipelex/core/pipes/test_pipe_blueprint_signature_enums.py b/tests/unit/pipelex/core/pipes/test_pipe_blueprint_signature_enums.py
index 474f103cc..a257b6010 100644
--- a/tests/unit/pipelex/core/pipes/test_pipe_blueprint_signature_enums.py
+++ b/tests/unit/pipelex/core/pipes/test_pipe_blueprint_signature_enums.py
@@ -1,18 +1,35 @@
-from pipelex.core.pipes.pipe_blueprint import PipeCategory, PipeType
+import pytest
+from pipelex.core.pipes.pipe_blueprint import PIPE_SIGNATURE_TYPE_TAG, PipeCategory, PipeType
-class TestPipeSignatureEnums:
- def test_pipe_type_pipe_signature_value(self) -> None:
- assert PipeType.PIPE_SIGNATURE == "PipeSignature"
- def test_pipe_type_pipe_signature_in_value_list(self) -> None:
- assert "PipeSignature" in PipeType.value_list()
+class TestPipeSignatureTaxonomyEviction:
+ def test_signature_tag_value(self) -> None:
+ assert PIPE_SIGNATURE_TYPE_TAG == "PipeSignature"
- def test_pipe_type_pipe_signature_category(self) -> None:
- assert PipeType("PipeSignature").category is PipeCategory.PIPE_SIGNATURE
+ def test_signature_tag_not_in_pipe_type(self) -> None:
+ assert PIPE_SIGNATURE_TYPE_TAG not in PipeType.value_list()
- def test_pipe_category_pipe_signature_value(self) -> None:
- assert PipeCategory.PIPE_SIGNATURE == "PipeSignature"
+ def test_signature_tag_not_in_pipe_category(self) -> None:
+ assert PIPE_SIGNATURE_TYPE_TAG not in PipeCategory.value_list()
- def test_pipe_category_signature_is_not_controller(self) -> None:
- assert PipeCategory.is_controller_by_str("PipeSignature") is False
+ def test_pipe_type_signature_member_removed(self) -> None:
+ assert not hasattr(PipeType, "PIPE_SIGNATURE")
+
+ def test_pipe_category_signature_member_removed(self) -> None:
+ assert not hasattr(PipeCategory, "PIPE_SIGNATURE")
+
+ def test_coercing_signature_tag_to_pipe_type_raises(self) -> None:
+ with pytest.raises(ValueError, match="PipeSignature"):
+ PipeType(PIPE_SIGNATURE_TYPE_TAG)
+
+ def test_signature_tag_is_not_controller(self) -> None:
+ assert PipeCategory.is_controller_by_str(PIPE_SIGNATURE_TYPE_TAG) is False
+
+ def test_signature_tag_is_not_operator(self) -> None:
+ # `is_controller_by_str` returning False must NOT be read as "therefore an operator": the
+ # signature tag is outside the controller/operator dichotomy entirely. There is no
+ # `is_operator_by_str`, so "not an operator" is shown by the tag coercing to no
+ # `PipeCategory` member at all — it is neither operator nor controller.
+ with pytest.raises(ValueError, match="PipeSignature"):
+ PipeCategory(PIPE_SIGNATURE_TYPE_TAG)
diff --git a/tests/unit/pipelex/libraries/test_concept_reference_validation.py b/tests/unit/pipelex/libraries/test_concept_reference_validation.py
new file mode 100644
index 000000000..85d65296b
--- /dev/null
+++ b/tests/unit/pipelex/libraries/test_concept_reference_validation.py
@@ -0,0 +1,337 @@
+import pytest
+
+from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
+from pipelex.core.concepts.concept_blueprint import ConceptBlueprint
+from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprint, ConceptStructureBlueprintFieldType
+from pipelex.libraries.concept.exceptions import ConceptLibraryError
+from pipelex.libraries.concept_reference_validation import validate_concept_references_in_blueprints
+from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint
+from tests.unit.pipelex.libraries.test_library_crate_data import BlueprintSamples
+
+
+class TestConceptReferenceValidation:
+ """Concept references resolve against the merged library, not per file.
+
+ `validate_concept_references_in_blueprints` runs in the loader after the structural merge: a
+ bundle that references a concept declared in a sibling file (in the same batch or already in
+ the library) validates, while a reference declared nowhere raises ConceptLibraryError.
+ """
+
+ # ========== CROSS-FILE RESOLUTION (the unblock) ==========
+
+ @pytest.mark.parametrize(
+ "blueprints",
+ [
+ [BlueprintSamples.CROSSREF_CONCEPT_BUNDLE, BlueprintSamples.CROSSREF_PIPE_BUNDLE],
+ [BlueprintSamples.CROSSREF_PIPE_BUNDLE, BlueprintSamples.CROSSREF_CONCEPT_BUNDLE],
+ ],
+ )
+ def test_cross_file_concept_reference_resolves(self, blueprints: list[PipelexBundleBlueprint]):
+ """A concept declared in one file, referenced by bare code from a sibling file in the same batch, resolves (order-independent)."""
+ validate_concept_references_in_blueprints(blueprints=blueprints)
+
+ def test_cross_batch_concept_reference_resolves_via_already_loaded(self):
+ """A bare ref resolves against a concept loaded by a prior batch (passed as already_loaded_concept_refs)."""
+ validate_concept_references_in_blueprints(
+ blueprints=[BlueprintSamples.CROSSREF_PIPE_BUNDLE],
+ already_loaded_concept_refs={"crossref.Summary"},
+ )
+
+ def test_cross_file_undeclared_concept_raises_naming_ref_and_source(self):
+ """A bare concept reference declared in no file raises ConceptLibraryError naming the ref and its source."""
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ validate_concept_references_in_blueprints(blueprints=[BlueprintSamples.CROSSREF_PIPE_BUNDLE])
+ message = str(exc_info.value)
+ assert "Summary" in message
+ assert "pipe.make_summary.output" in message
+ assert "/fake/crossref_pipe.mthds" in message
+
+ # ========== REFERENCES DEFERRED TO OTHER LAYERS (no error) ==========
+
+ def test_native_concept_reference_allowed(self):
+ """Native concepts (Text) need no declaration and never trigger the undeclared check."""
+ bundle = PipelexBundleBlueprint(
+ domain="native_ok",
+ description="Native concepts only",
+ pipe={
+ "echo": PipeLLMBlueprint(
+ description="Echo a document",
+ inputs={"doc": "Text"},
+ output="Text",
+ prompt="Echo $doc.",
+ ),
+ },
+ )
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+
+ def test_same_domain_qualified_ref_sharing_native_local_code_is_flagged(self):
+ """A same-domain qualified ref that merely shares a native local code (e.g. `my_domain.Text`)
+ is NOT native and must still be validated — matching how it actually resolves. A bare-local-code
+ native check would wrongly suppress the undeclared-reference error.
+ """
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="Qualified ref sharing a native local code",
+ pipe={
+ "make_text": PipeLLMBlueprint(
+ description="Produce a domain-qualified text",
+ inputs={"doc": "Text"},
+ output="my_domain.Text",
+ prompt="Echo $doc.",
+ ),
+ },
+ )
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+ assert "my_domain.Text" in str(exc_info.value)
+
+ def test_external_domain_reference_not_validated(self):
+ """An external-domain concept ref is deferred to dependency loading, not flagged here."""
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="External ref",
+ pipe={
+ "use_external": PipeLLMBlueprint(
+ description="Use an external concept",
+ inputs={"score": "scoring.WeightedScore"},
+ output="Text",
+ prompt="Process $score.",
+ ),
+ },
+ )
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+
+ def test_cross_package_reference_not_validated(self):
+ """A cross-package concept ref ('alias->...') is deferred to package resolution, not flagged here."""
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="Cross-package ref",
+ concept={
+ "Wrapper": ConceptBlueprint(
+ description="Wraps a dependency concept",
+ structure={
+ "doc": ConceptStructureBlueprint(
+ description="A document from a dependency package",
+ type=ConceptStructureBlueprintFieldType.CONCEPT,
+ concept_ref="docs->documents.Document",
+ ),
+ },
+ ),
+ },
+ )
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+
+ # ========== UNDECLARED-REFERENCE CASES (caught by the loader-level check) ==========
+
+ def test_undeclared_concept_in_pipe_output_raises(self):
+ """An undeclared concept in a pipe output is caught with its context path."""
+ bundle = PipelexBundleBlueprint(
+ domain="test_domain",
+ description="Test bundle",
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ description="Test pipe",
+ output="UndeclaredConcept",
+ prompt="Generate something",
+ ),
+ },
+ )
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+ message = str(exc_info.value)
+ assert "UndeclaredConcept" in message
+ assert "pipe.my_pipe.output" in message
+ assert "not declared in domain" in message
+
+ def test_undeclared_concept_in_pipe_input_raises(self):
+ """An undeclared concept in a pipe input is caught with its context path."""
+ bundle = PipelexBundleBlueprint(
+ domain="test_domain",
+ description="Test bundle",
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ description="Test pipe",
+ inputs={"data": "UndeclaredInput"},
+ output="Text",
+ prompt="Process $data",
+ ),
+ },
+ )
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+ message = str(exc_info.value)
+ assert "UndeclaredInput" in message
+ assert "pipe.my_pipe.inputs.data" in message
+
+ def test_undeclared_same_domain_qualified_reference_raises(self):
+ """A same-domain qualified ref (domain.Concept) not declared anywhere is caught."""
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="Test bundle",
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ description="Test pipe",
+ output="my_domain.NotDeclaredConcept",
+ prompt="Generate something",
+ ),
+ },
+ )
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+ message = str(exc_info.value)
+ assert "NotDeclaredConcept" in message
+ assert "pipe.my_pipe.output" in message
+
+ def test_undeclared_hierarchical_same_domain_reference_raises(self):
+ """A hierarchical same-domain qualified ref not declared anywhere is caught."""
+ bundle = PipelexBundleBlueprint(
+ domain="legal.contracts",
+ description="Test bundle",
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ description="Test pipe",
+ output="legal.contracts.Missing",
+ prompt="Generate something",
+ ),
+ },
+ )
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+ message = str(exc_info.value)
+ assert "Missing" in message
+ assert "not declared in domain" in message
+
+ def test_undeclared_concept_in_refines_raises(self):
+ """An undeclared concept in a refines field is caught with its context path."""
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="Test bundle",
+ concept={
+ "DerivedConcept": ConceptBlueprint(
+ description="Derived concept",
+ refines="NonExistentBaseConcept",
+ ),
+ },
+ )
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+ message = str(exc_info.value)
+ assert "NonExistentBaseConcept" in message
+ assert "concept.DerivedConcept.refines" in message
+
+ def test_undeclared_concept_ref_in_structure_raises(self):
+ """An undeclared concept_ref in a structure field is caught with its context path."""
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="Test bundle",
+ concept={
+ "Person": ConceptBlueprint(
+ description="A person concept",
+ structure={
+ "name": "The person's name",
+ "address": ConceptStructureBlueprint(
+ description="The person's address",
+ type=ConceptStructureBlueprintFieldType.CONCEPT,
+ concept_ref="UndeclaredAddress",
+ ),
+ },
+ ),
+ },
+ )
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+ message = str(exc_info.value)
+ assert "UndeclaredAddress" in message
+ assert "concept.Person.structure.address.concept_ref" in message
+
+ def test_undeclared_item_concept_ref_in_structure_raises(self):
+ """An undeclared item_concept_ref in a list structure field is caught."""
+ bundle = PipelexBundleBlueprint(
+ domain="my_domain",
+ description="Test bundle",
+ concept={
+ "Order": ConceptBlueprint(
+ description="An order concept",
+ structure={
+ "order_id": "The order ID",
+ "items": ConceptStructureBlueprint(
+ description="The order items",
+ type=ConceptStructureBlueprintFieldType.LIST,
+ item_type="concept",
+ item_concept_ref="UndeclaredLineItem",
+ ),
+ },
+ ),
+ },
+ )
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+ message = str(exc_info.value)
+ assert "UndeclaredLineItem" in message
+ assert "concept.Order.structure.items.item_concept_ref" in message
+
+ def test_undeclared_concept_with_multiplicity_raises(self):
+ """A multiplicity-bracketed undeclared concept resolves to its base code and is caught."""
+ bundle = PipelexBundleBlueprint(
+ domain="test_domain",
+ description="Test bundle",
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ description="Test pipe",
+ inputs={"items": "UndeclaredItem[]"},
+ output="Text",
+ prompt="Process $items",
+ ),
+ },
+ )
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+ message = str(exc_info.value)
+ assert "UndeclaredItem" in message
+ assert "pipe.my_pipe.inputs.items" in message
+
+ def test_multiple_undeclared_concepts_all_reported(self):
+ """Every undeclared reference is reported together, not just the first."""
+ bundle = PipelexBundleBlueprint(
+ domain="test_domain",
+ description="Test bundle",
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ description="Test pipe",
+ inputs={"input1": "Undeclared1", "input2": "Undeclared2"},
+ output="Undeclared3",
+ prompt="Process $input1 and $input2",
+ ),
+ },
+ )
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+ message = str(exc_info.value)
+ assert "Undeclared1" in message
+ assert "Undeclared2" in message
+ assert "Undeclared3" in message
+
+ def test_error_message_lists_declared_and_native_concepts(self):
+ """The error message lists the declared concepts and native concepts for debugging."""
+ bundle = PipelexBundleBlueprint(
+ domain="test_domain",
+ description="Test bundle",
+ concept={
+ "DeclaredConcept1": "First declared concept",
+ "DeclaredConcept2": "Second declared concept",
+ },
+ pipe={
+ "my_pipe": PipeLLMBlueprint(
+ description="Test pipe",
+ output="UndeclaredConcept",
+ prompt="Generate",
+ ),
+ },
+ )
+ with pytest.raises(ConceptLibraryError) as exc_info:
+ validate_concept_references_in_blueprints(blueprints=[bundle])
+ message = str(exc_info.value)
+ assert "DeclaredConcept1" in message
+ assert "DeclaredConcept2" in message
+ assert "Native concepts" in message
+ assert "Text" in message
diff --git a/tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py b/tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py
new file mode 100644
index 000000000..4881e671d
--- /dev/null
+++ b/tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py
@@ -0,0 +1,131 @@
+"""Tests that a multi-file dependency package reconciles like the main additive load path.
+
+A dependency can be authored across files: a header file declaring a `PipeSignature` forward
+declaration plus a concrete sibling that implements it. The dependency loader must merge those
+files into a crate (so the signature and concrete collapse to a single concrete pipe) instead of
+adding each blueprint's pipes directly — which would collide in `add_new_pipe` and silently drop a
+declaration. A genuine duplicate (two concrete definitions of the same pipe) must still raise.
+"""
+
+from pathlib import Path
+
+import pytest
+from mthds.package.dependency_resolver import ResolvedDependency
+from mthds.package.manifest.schema import MethodsManifest
+from pytest_mock import MockerFixture
+
+from pipelex.hub import get_library_manager
+from pipelex.libraries.library_factory import LibraryFactory
+from pipelex.libraries.library_manager import LibraryManager
+from pipelex.libraries.pipe.exceptions import PipeLibraryError
+
+# Header file: a PipeSignature forward-declaration of `summarize`.
+DEP_HEADER_MTHDS = """\
+domain = "summary_dep"
+description = "Dependency header declaring a summarize signature"
+
+[pipe.summarize]
+type = "PipeSignature"
+description = "Summarize a document (contract only)."
+inputs = { doc = "Text" }
+output = "Text"
+"""
+
+# Concrete sibling: the real `summarize` implementation, contract matching the header.
+DEP_CONCRETE_MTHDS = """\
+domain = "summary_dep"
+description = "Dependency definition implementing summarize"
+
+[pipe.summarize]
+type = "PipeLLM"
+description = "Summarize a document."
+inputs = { doc = "Text" }
+output = "Text"
+prompt = "Summarize $doc."
+"""
+
+# A second concrete `summarize` (genuine duplicate) for the negative case.
+DEP_CONCRETE_DUP_MTHDS = """\
+domain = "summary_dep"
+description = "Dependency definition with a duplicate concrete summarize"
+
+[pipe.summarize]
+type = "PipeLLM"
+description = "Another summarize implementation."
+inputs = { doc = "Text" }
+output = "Text"
+prompt = "Briefly summarize $doc."
+"""
+
+
+class TestDependencyMultiFileReconciliation:
+ def _build_resolved_dep(self, tmp_path: Path, file_contents: list[tuple[str, str]]) -> ResolvedDependency:
+ mthds_files: list[Path] = []
+ for file_name, content in file_contents:
+ mthds_file = tmp_path / file_name
+ mthds_file.write_text(content, encoding="utf-8")
+ mthds_files.append(mthds_file)
+
+ manifest = MethodsManifest(
+ address="github.com/org/summary-dep",
+ version="1.0.0",
+ description="A multi-file dep package",
+ )
+ return ResolvedDependency(
+ alias="summary_dep",
+ address="github.com/org/summary-dep",
+ manifest=manifest,
+ package_root=tmp_path,
+ mthds_files=mthds_files,
+ # None => no export filter, every pipe is public.
+ exported_pipe_codes=None,
+ )
+
+ def test_signature_and_concrete_sibling_reconcile_to_concrete(
+ self,
+ mocker: MockerFixture,
+ tmp_path: Path,
+ ) -> None:
+ """A header signature + concrete sibling collapse to a single concrete pipe (concrete wins).
+
+ The header file is listed first, so the broken per-blueprint loader would add the signature
+ and then drop the concrete as a duplicate, leaving `summarize` as a non-executable signature.
+ Routing through the crate merge reconciles them: the concrete must win.
+ """
+ library_manager = get_library_manager()
+ library = LibraryFactory.make_empty()
+ mocker.patch.object(library_manager, "get_current_library", return_value=library)
+
+ manager = LibraryManager()
+ manager._load_single_dependency( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]
+ library=library,
+ resolved_dep=self._build_resolved_dep(
+ tmp_path=tmp_path,
+ file_contents=[("header.mthds", DEP_HEADER_MTHDS), ("definition.mthds", DEP_CONCRETE_MTHDS)],
+ ),
+ )
+
+ child_library = library.dependency_libraries["summary_dep"]
+ summarize_pipes = [pipe for pipe in child_library.pipe_library.get_pipes() if pipe.code == "summarize"]
+ assert len(summarize_pipes) == 1, "Signature and concrete must reconcile to exactly one pipe"
+ assert not summarize_pipes[0].is_signature, "The concrete definition must win over the forward signature"
+
+ def test_two_concrete_definitions_raise(
+ self,
+ mocker: MockerFixture,
+ tmp_path: Path,
+ ) -> None:
+ """Two concrete definitions of the same pipe in a dependency are a genuine duplicate and must raise."""
+ library_manager = get_library_manager()
+ library = LibraryFactory.make_empty()
+ mocker.patch.object(library_manager, "get_current_library", return_value=library)
+
+ manager = LibraryManager()
+ with pytest.raises(PipeLibraryError):
+ manager._load_single_dependency( # noqa: SLF001 # pyright: ignore[reportPrivateUsage]
+ library=library,
+ resolved_dep=self._build_resolved_dep(
+ tmp_path=tmp_path,
+ file_contents=[("def_a.mthds", DEP_CONCRETE_MTHDS), ("def_b.mthds", DEP_CONCRETE_DUP_MTHDS)],
+ ),
+ )
diff --git a/tests/unit/pipelex/libraries/test_domain_library.py b/tests/unit/pipelex/libraries/test_domain_library.py
index 09ba510ac..6b4f8f43b 100644
--- a/tests/unit/pipelex/libraries/test_domain_library.py
+++ b/tests/unit/pipelex/libraries/test_domain_library.py
@@ -1,3 +1,7 @@
+import logging
+
+import pytest
+
from pipelex.core.domains.domain import Domain
from pipelex.libraries.domain.domain_library import DomainLibrary
@@ -24,3 +28,57 @@ class TestDomainLibrary:
assert len(library.root) == 2
assert library.get_domain("scoring") is domain_scoring
assert library.get_domain("analytics") is domain_analytics
+
+ @pytest.mark.parametrize(
+ "domains",
+ [
+ # Root header first, then the membership-only sibling.
+ [Domain(code="meta", description="Meta domain", system_prompt="You are a meta assistant."), Domain(code="meta")],
+ # Sibling first (no metadata): the root must still win — order-independent.
+ [Domain(code="meta"), Domain(code="meta", description="Meta domain", system_prompt="You are a meta assistant.")],
+ ],
+ )
+ def test_membership_sibling_defers_to_root(self, domains: list[Domain], caplog: pytest.LogCaptureFixture):
+ """A membership-only sibling Domain (no description/system_prompt) defers to the root's header, silently, in either order."""
+ library = DomainLibrary.make_empty()
+ with caplog.at_level(logging.WARNING):
+ library.add_domains(domains=domains)
+ merged = library.get_required_domain("meta")
+ assert merged.description == "Meta domain"
+ assert merged.system_prompt == "You are a meta assistant."
+ assert not [record for record in caplog.records if "declared with different" in record.message]
+
+ def test_same_values_no_warning(self, caplog: pytest.LogCaptureFixture):
+ """Two Domains declaring the same non-empty description/system_prompt merge without warning."""
+ library = DomainLibrary.make_empty()
+ with caplog.at_level(logging.WARNING):
+ library.add_domains(
+ domains=[
+ Domain(code="meta", description="Meta domain", system_prompt="You are a meta assistant."),
+ Domain(code="meta", description="Meta domain", system_prompt="You are a meta assistant."),
+ ]
+ )
+ merged = library.get_required_domain("meta")
+ assert merged.description == "Meta domain"
+ assert merged.system_prompt == "You are a meta assistant."
+ assert not [record for record in caplog.records if "declared with different" in record.message]
+
+ def test_conflict_keeps_first_and_warns(self, caplog: pytest.LogCaptureFixture):
+ """Two Domains declaring different non-empty values keep the first and warn for each field."""
+ library = DomainLibrary.make_empty()
+ with caplog.at_level(logging.WARNING):
+ library.add_domains(
+ domains=[
+ Domain(code="meta", description="Meta domain", system_prompt="You are a meta assistant."),
+ Domain(code="meta", description="A different meta domain", system_prompt="You are a different meta assistant."),
+ ]
+ )
+ merged = library.get_required_domain("meta")
+ assert merged.description == "Meta domain"
+ assert merged.system_prompt == "You are a meta assistant."
+ messages = [record.message for record in caplog.records]
+ assert any(
+ "Domain 'meta' declared with different descriptions: 'Meta domain' vs 'A different meta domain'. Keeping the first." in message
+ for message in messages
+ )
+ assert any("Domain 'meta' declared with different system_prompts. Keeping the first." in message for message in messages)
diff --git a/tests/unit/pipelex/libraries/test_library_crate.py b/tests/unit/pipelex/libraries/test_library_crate.py
index 9bbf7a439..a4a1d2e40 100644
--- a/tests/unit/pipelex/libraries/test_library_crate.py
+++ b/tests/unit/pipelex/libraries/test_library_crate.py
@@ -1,5 +1,8 @@
+import logging
+
import pytest
+from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
from pipelex.libraries.concept.exceptions import ConceptLibraryError
from pipelex.libraries.library_crate import LibraryCrate
from pipelex.libraries.library_crate_factory import LibraryCrateFactory
@@ -135,3 +138,153 @@ class TestLibraryCrate:
LibraryCrateFactory.make_from_blueprints(
blueprints=[BlueprintSamples.NONE_SOURCE_BUNDLE, BlueprintSamples.NONE_SOURCE_DUPLICATE_CONCEPT_BUNDLE],
)
+
+ def test_signature_then_concrete_concrete_wins(self):
+ """A signature followed by a concrete pipe reconciles: the concrete wins."""
+ crate = LibraryCrateFactory.make_from_blueprints(
+ blueprints=[BlueprintSamples.SIG_SIGNATURE_BUNDLE, BlueprintSamples.SIG_CONCRETE_BUNDLE],
+ )
+ winner = crate.pipes["reconcile.summarize"]
+ assert winner.is_signature is False
+ assert crate.source_map["reconcile.summarize"] == "/fake/reconcile_concrete.mthds"
+
+ def test_concrete_then_signature_concrete_wins(self):
+ """A concrete pipe followed by a signature reconciles the same way (order-independent)."""
+ crate = LibraryCrateFactory.make_from_blueprints(
+ blueprints=[BlueprintSamples.SIG_CONCRETE_BUNDLE, BlueprintSamples.SIG_SIGNATURE_BUNDLE],
+ )
+ winner = crate.pipes["reconcile.summarize"]
+ assert winner.is_signature is False
+ assert crate.source_map["reconcile.summarize"] == "/fake/reconcile_concrete.mthds"
+
+ def test_signature_plus_signature_matching_is_order_independent(self):
+ """Two matching signatures collapse to one, and the winner does not depend on load order."""
+ crate_ab = LibraryCrateFactory.make_from_blueprints(
+ blueprints=[BlueprintSamples.SIG_SIGNATURE_BUNDLE, BlueprintSamples.SIG_SIGNATURE_DUP_BUNDLE],
+ )
+ crate_ba = LibraryCrateFactory.make_from_blueprints(
+ blueprints=[BlueprintSamples.SIG_SIGNATURE_DUP_BUNDLE, BlueprintSamples.SIG_SIGNATURE_BUNDLE],
+ )
+ assert crate_ab.pipes["reconcile.summarize"].is_signature is True
+ assert crate_ba.pipes["reconcile.summarize"].is_signature is True
+ # Deterministic tie-break: same surviving source and same fingerprint regardless of order.
+ assert crate_ab.source_map["reconcile.summarize"] == crate_ba.source_map["reconcile.summarize"]
+ assert crate_ab.fingerprint == crate_ba.fingerprint
+
+ def test_signature_plus_signature_mismatched_raises(self):
+ """Two signatures with differing contracts raise a PipeLibraryError."""
+ with pytest.raises(PipeLibraryError, match=r"mismatched contracts"):
+ LibraryCrateFactory.make_from_blueprints(
+ blueprints=[BlueprintSamples.SIG_SIGNATURE_BUNDLE, BlueprintSamples.SIG_SIGNATURE_MISMATCH_BUNDLE],
+ )
+
+ def test_signature_plus_concrete_mismatched_inputs_raises(self):
+ """A signature and a concrete with differing inputs raise a PipeLibraryError."""
+ with pytest.raises(PipeLibraryError, match=r"mismatched contracts"):
+ LibraryCrateFactory.make_from_blueprints(
+ blueprints=[BlueprintSamples.SIG_SIGNATURE_BUNDLE, BlueprintSamples.SIG_CONCRETE_MISMATCH_BUNDLE],
+ )
+
+ def test_signature_with_inputs_plus_concrete_without_inputs_raises(self):
+ """Exact-match: a header with explicit inputs and a concrete that omits them mismatch."""
+ with pytest.raises(PipeLibraryError, match=r"mismatched contracts"):
+ LibraryCrateFactory.make_from_blueprints(
+ blueprints=[BlueprintSamples.SIG_SIGNATURE_BUNDLE, BlueprintSamples.SIG_CONCRETE_NO_INPUTS_BUNDLE],
+ )
+
+ @pytest.mark.parametrize(
+ "blueprints",
+ [
+ [BlueprintSamples.SIG_SIGNATURE_BUNDLE, BlueprintSamples.SIG_CONCRETE_NO_SOURCE_BUNDLE],
+ [BlueprintSamples.SIG_CONCRETE_NO_SOURCE_BUNDLE, BlueprintSamples.SIG_SIGNATURE_BUNDLE],
+ ],
+ )
+ def test_sourceless_concrete_winner_clears_stale_source(self, blueprints: list[PipelexBundleBlueprint]):
+ """A concrete with no source wins over a signature without leaving the signature's file in source_map."""
+ crate = LibraryCrateFactory.make_from_blueprints(blueprints=blueprints)
+ assert crate.pipes["reconcile.summarize"].is_signature is False
+ # The losing signature's file must not be misattributed to the winning concrete.
+ assert "reconcile.summarize" not in crate.source_map
+
+ @pytest.mark.parametrize(
+ "blueprints",
+ [
+ # Header outputs bare `Summary`; concrete outputs same-domain-qualified `reconcile.Summary`.
+ [BlueprintSamples.SIG_SIGNATURE_BARE_SUMMARY_BUNDLE, BlueprintSamples.SIG_CONCRETE_QUALIFIED_SUMMARY_BUNDLE],
+ # Header contract uses `native.Text`; concrete uses bare native `Text`.
+ [BlueprintSamples.SIG_SIGNATURE_NATIVE_QUALIFIED_BUNDLE, BlueprintSamples.SIG_CONCRETE_BUNDLE],
+ # Same variable-length output, bare `Summary[]` vs qualified `reconcile.Summary[]`.
+ [BlueprintSamples.SIG_SIGNATURE_LIST_BARE_BUNDLE, BlueprintSamples.SIG_CONCRETE_LIST_QUALIFIED_BUNDLE],
+ # Same fixed-count output, bare `Summary[2]` vs qualified `reconcile.Summary[2]`.
+ [BlueprintSamples.SIG_SIGNATURE_LIST_FIXED_BUNDLE, BlueprintSamples.SIG_CONCRETE_LIST_FIXED_QUALIFIED_BUNDLE],
+ # Same external-domain output `other_domain.Insight` on both sides (kept verbatim).
+ [BlueprintSamples.SIG_SIGNATURE_EXTERNAL_OUTPUT_BUNDLE, BlueprintSamples.SIG_CONCRETE_EXTERNAL_OUTPUT_BUNDLE],
+ ],
+ )
+ def test_contracts_reconcile_across_equivalent_concept_spellings(self, blueprints: list[PipelexBundleBlueprint]):
+ """Bare<->qualified, native, fixed-count, and external-domain spellings of the same contract reconcile (concrete wins)."""
+ crate = LibraryCrateFactory.make_from_blueprints(blueprints=blueprints)
+ assert crate.pipes["reconcile.summarize"].is_signature is False
+
+ @pytest.mark.parametrize(
+ "blueprints",
+ [
+ # Differing multiplicity: `Summary[]` (header, variable) vs `reconcile.Summary` (concrete, single).
+ [BlueprintSamples.SIG_SIGNATURE_LIST_BARE_BUNDLE, BlueprintSamples.SIG_CONCRETE_QUALIFIED_SUMMARY_BUNDLE],
+ # Variable `Summary[]` vs fixed `reconcile.Summary[2]` — `[]` must NOT conflate with `[N]`.
+ [BlueprintSamples.SIG_SIGNATURE_LIST_BARE_BUNDLE, BlueprintSamples.SIG_CONCRETE_LIST_FIXED_QUALIFIED_BUNDLE],
+ # Regression guard: variable `Summary[]` vs fixed `reconcile.Summary[1]` — the exact pair the
+ # `True == 1` bool/int conflation would have wrongly accepted.
+ [BlueprintSamples.SIG_SIGNATURE_LIST_BARE_BUNDLE, BlueprintSamples.SIG_CONCRETE_LIST_ONE_QUALIFIED_BUNDLE],
+ # Genuinely different output concept: `Brief` (header) vs `reconcile.Summary` (concrete).
+ [BlueprintSamples.SIG_SIGNATURE_BRIEF_BUNDLE, BlueprintSamples.SIG_CONCRETE_QUALIFIED_SUMMARY_BUNDLE],
+ # External-domain `other_domain.Insight` (header) vs same-domain bare `Summary` (concrete) — must not match.
+ [BlueprintSamples.SIG_SIGNATURE_EXTERNAL_OUTPUT_BUNDLE, BlueprintSamples.SIG_CONCRETE_QUALIFIED_SUMMARY_BUNDLE],
+ ],
+ )
+ def test_contracts_still_mismatch_when_genuinely_different(self, blueprints: list[PipelexBundleBlueprint]):
+ """Differing multiplicity (incl. `[]` vs `[N]`), a different concept, or an external-domain ref still raises."""
+ with pytest.raises(PipeLibraryError, match=r"mismatched contracts"):
+ LibraryCrateFactory.make_from_blueprints(blueprints=blueprints)
+
+ @pytest.mark.parametrize(
+ "blueprints",
+ [
+ # Root first, then the membership-only sibling.
+ [BlueprintSamples.META_ROOT_BUNDLE, BlueprintSamples.META_MEMBER_BUNDLE],
+ # Sibling first (empty metadata): the root must still win — order-independent.
+ [BlueprintSamples.META_MEMBER_BUNDLE, BlueprintSamples.META_ROOT_BUNDLE],
+ ],
+ )
+ def test_domain_metadata_membership_sibling_defers_to_root(self, blueprints: list[PipelexBundleBlueprint], caplog: pytest.LogCaptureFixture):
+ """A membership-only sibling (no description/system_prompt) defers to the root's header in either order, silently."""
+ with caplog.at_level(logging.WARNING):
+ crate = LibraryCrateFactory.make_from_blueprints(blueprints=blueprints)
+ assert crate.domains["meta"].description == "Meta domain"
+ assert crate.domains["meta"].system_prompt == "You are a meta assistant."
+ assert not [record for record in caplog.records if "declared with different" in record.message]
+
+ def test_domain_metadata_same_values_no_warning(self, caplog: pytest.LogCaptureFixture):
+ """Two files declaring the same non-empty description/system_prompt merge without warning."""
+ with caplog.at_level(logging.WARNING):
+ crate = LibraryCrateFactory.make_from_blueprints(
+ blueprints=[BlueprintSamples.META_ROOT_BUNDLE, BlueprintSamples.META_SAME_BUNDLE],
+ )
+ assert crate.domains["meta"].description == "Meta domain"
+ assert crate.domains["meta"].system_prompt == "You are a meta assistant."
+ assert not [record for record in caplog.records if "declared with different" in record.message]
+
+ def test_domain_metadata_conflict_keeps_first_and_warns(self, caplog: pytest.LogCaptureFixture):
+ """Two files declaring different non-empty values keep the first and warn for each field."""
+ with caplog.at_level(logging.WARNING):
+ crate = LibraryCrateFactory.make_from_blueprints(
+ blueprints=[BlueprintSamples.META_ROOT_BUNDLE, BlueprintSamples.META_CONFLICT_BUNDLE],
+ )
+ assert crate.domains["meta"].description == "Meta domain"
+ assert crate.domains["meta"].system_prompt == "You are a meta assistant."
+ messages = [record.message for record in caplog.records]
+ assert any(
+ "Domain 'meta' declared with different descriptions: 'Meta domain' vs 'A different meta domain'. Keeping the first." in message
+ for message in messages
+ )
+ assert any("Domain 'meta' declared with different system_prompts. Keeping the first." in message for message in messages)
diff --git a/tests/unit/pipelex/libraries/test_library_crate_data.py b/tests/unit/pipelex/libraries/test_library_crate_data.py
index 36b2cdae9..bcb129296 100644
--- a/tests/unit/pipelex/libraries/test_library_crate_data.py
+++ b/tests/unit/pipelex/libraries/test_library_crate_data.py
@@ -3,6 +3,7 @@ from typing import ClassVar
from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
from pipelex.core.concepts.concept_blueprint import ConceptBlueprint
from pipelex.pipe_operators.llm.pipe_llm_blueprint import PipeLLMBlueprint
+from pipelex.pipe_signature.pipe_signature_blueprint import PipeSignatureBlueprint
class BlueprintSamples:
@@ -146,3 +147,347 @@ class BlueprintSamples:
"Item": ConceptBlueprint(description="Duplicate item"),
},
)
+
+ # --- Phase 1 (Part A): pipe signature/concrete reconciliation ---
+ # All bundles below use the native concept Text in their contracts, so per-file
+ # concept-reference validation passes without declaring any concept. The shared pipe
+ # code is `summarize` with contract (inputs={"doc": "Text"}, output="Text").
+
+ # Concrete definition of `summarize`.
+ SIG_CONCRETE_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_concrete.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeLLMBlueprint(
+ description="Summarize a document",
+ inputs={"doc": "Text"},
+ output="Text",
+ prompt="Summarize $doc.",
+ ),
+ },
+ )
+
+ # Forward declaration (header) of `summarize` with a matching contract.
+ SIG_SIGNATURE_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_header.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeSignatureBlueprint(
+ description="Header for summarize",
+ inputs={"doc": "Text"},
+ output="Text",
+ ),
+ },
+ )
+
+ # A second forward declaration of `summarize` with the same matching contract
+ # (a sub-pipe forward-declared by several callers).
+ SIG_SIGNATURE_DUP_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_header_2.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeSignatureBlueprint(
+ description="Second header for summarize",
+ inputs={"doc": "Text"},
+ output="Text",
+ ),
+ },
+ )
+
+ # A forward declaration of `summarize` with a mismatched contract (extra input).
+ SIG_SIGNATURE_MISMATCH_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_header_bad.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeSignatureBlueprint(
+ description="Mismatched header for summarize",
+ inputs={"doc": "Text", "lang": "Text"},
+ output="Text",
+ ),
+ },
+ )
+
+ # A concrete definition of `summarize` whose contract mismatches the header (extra input).
+ SIG_CONCRETE_MISMATCH_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_concrete_bad.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeLLMBlueprint(
+ description="Summarize a document in a language",
+ inputs={"doc": "Text", "lang": "Text"},
+ output="Text",
+ prompt="Summarize $doc in $lang.",
+ ),
+ },
+ )
+
+ # A concrete definition of `summarize` with a matching contract but NO bundle source
+ # (in-memory bundle). Exercises that a sourceless winner clears any stale source_map entry.
+ SIG_CONCRETE_NO_SOURCE_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source=None,
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeLLMBlueprint(
+ description="Summarize a document",
+ inputs={"doc": "Text"},
+ output="Text",
+ prompt="Summarize $doc.",
+ ),
+ },
+ )
+
+ # A concrete definition of `summarize` that omits inputs entirely (mismatches the
+ # explicit-inputs header under exact-match semantics).
+ SIG_CONCRETE_NO_INPUTS_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_concrete_no_inputs.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeLLMBlueprint(
+ description="Summarize without declared inputs",
+ output="Text",
+ prompt="Summarize the document.",
+ ),
+ },
+ )
+
+ # --- Phase 2 (Part B): cross-file concept references resolve at library level ---
+ # `crossref` declares a non-native concept `Summary` in one file and references it by bare
+ # code from a sibling file of the same domain. With per-file validation gone, both files
+ # construct, and the reference resolves against the merged crate.
+
+ # File A: declares the non-native concept `Summary`.
+ CROSSREF_CONCEPT_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/crossref_concept.mthds",
+ domain="crossref",
+ description="Cross-reference domain",
+ concept={
+ "Summary": ConceptBlueprint(description="A summary of a document"),
+ },
+ )
+
+ # File B: a pipe that references `Summary` (declared in file A) by bare code.
+ CROSSREF_PIPE_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/crossref_pipe.mthds",
+ domain="crossref",
+ description="Cross-reference domain",
+ pipe={
+ "make_summary": PipeLLMBlueprint(
+ description="Summarize a document",
+ inputs={"doc": "Text"},
+ output="Summary",
+ prompt="Summarize $doc.",
+ ),
+ },
+ )
+
+ # --- Normalized contract conformance: bare <-> qualified <-> native equivalence ---
+ # The merge is a pure structural step (no concept-ref validation), so these contracts may name
+ # an undeclared concept `Summary`; only the contract identity matters here. All share the pipe
+ # code `summarize` in domain `reconcile` so they collide with each other / SIG_CONCRETE_BUNDLE.
+
+ # Header whose output is the same-domain concept written bare: `Summary`.
+ SIG_SIGNATURE_BARE_SUMMARY_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_header_bare_summary.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeSignatureBlueprint(
+ description="Header for summarize (bare Summary output)",
+ inputs={"doc": "Text"},
+ output="Summary",
+ ),
+ },
+ )
+
+ # Concrete whose output is the SAME concept written domain-qualified: `reconcile.Summary`.
+ # Normalized identity makes this reconcile with SIG_SIGNATURE_BARE_SUMMARY_BUNDLE.
+ SIG_CONCRETE_QUALIFIED_SUMMARY_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_concrete_qualified_summary.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeLLMBlueprint(
+ description="Summarize a document",
+ inputs={"doc": "Text"},
+ output="reconcile.Summary",
+ prompt="Summarize $doc.",
+ ),
+ },
+ )
+
+ # Header whose contract uses the native concept in its fully-qualified form (`native.Text`).
+ # Normalized identity makes this reconcile with SIG_CONCRETE_BUNDLE (bare `Text`).
+ SIG_SIGNATURE_NATIVE_QUALIFIED_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_header_native_qualified.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeSignatureBlueprint(
+ description="Header for summarize (native.Text contract)",
+ inputs={"doc": "native.Text"},
+ output="native.Text",
+ ),
+ },
+ )
+
+ # Header with a list-valued output written bare: `Summary[]`.
+ SIG_SIGNATURE_LIST_BARE_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_header_list_bare.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeSignatureBlueprint(
+ description="Header for summarize (Summary[] output)",
+ inputs={"doc": "Text"},
+ output="Summary[]",
+ ),
+ },
+ )
+
+ # Concrete with the SAME list-valued output written domain-qualified: `reconcile.Summary[]`.
+ SIG_CONCRETE_LIST_QUALIFIED_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_concrete_list_qualified.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeLLMBlueprint(
+ description="Summarize a document into key points",
+ inputs={"doc": "Text"},
+ output="reconcile.Summary[]",
+ prompt="Summarize $doc.",
+ ),
+ },
+ )
+
+ # Header whose output is a genuinely DIFFERENT same-domain concept: `Brief` (not `Summary`).
+ SIG_SIGNATURE_BRIEF_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_header_brief.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeSignatureBlueprint(
+ description="Header for summarize (Brief output)",
+ inputs={"doc": "Text"},
+ output="Brief",
+ ),
+ },
+ )
+
+ # Header with a FIXED-count list output `Summary[2]` — distinct from the variable-length
+ # `Summary[]` (pins that `[]` and `[N]` must not be conflated via Python's `True == 1`).
+ SIG_SIGNATURE_LIST_FIXED_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_header_list_fixed.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeSignatureBlueprint(
+ description="Header for summarize (Summary[2] output)",
+ inputs={"doc": "Text"},
+ output="Summary[2]",
+ ),
+ },
+ )
+
+ # Concrete with the SAME fixed-count output, domain-qualified: `reconcile.Summary[2]`.
+ SIG_CONCRETE_LIST_FIXED_QUALIFIED_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_concrete_list_fixed_qualified.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeLLMBlueprint(
+ description="Summarize a document into exactly two points",
+ inputs={"doc": "Text"},
+ output="reconcile.Summary[2]",
+ prompt="Summarize $doc.",
+ ),
+ },
+ )
+
+ # Concrete with a list output of EXACTLY ONE, domain-qualified: `reconcile.Summary[1]`. Paired
+ # against `Summary[]` this is the precise regression guard: parsing `[]`->True and `[1]`->int 1
+ # and comparing them conflates the two because Python evaluates `True == 1` as true.
+ SIG_CONCRETE_LIST_ONE_QUALIFIED_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_concrete_list_one_qualified.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeLLMBlueprint(
+ description="Summarize a document into exactly one point",
+ inputs={"doc": "Text"},
+ output="reconcile.Summary[1]",
+ prompt="Summarize $doc.",
+ ),
+ },
+ )
+
+ # Header whose output is an EXTERNAL-domain concept `other_domain.Insight` — must NOT canonicalize
+ # to `reconcile.Insight`, so it stays distinct from a same-domain `Insight`.
+ SIG_SIGNATURE_EXTERNAL_OUTPUT_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_header_external.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeSignatureBlueprint(
+ description="Header for summarize (external-domain output)",
+ inputs={"doc": "Text"},
+ output="other_domain.Insight",
+ ),
+ },
+ )
+
+ # Concrete with the SAME external-domain output `other_domain.Insight` — kept verbatim, matches.
+ SIG_CONCRETE_EXTERNAL_OUTPUT_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/reconcile_concrete_external.mthds",
+ domain="reconcile",
+ description="Reconciliation domain",
+ pipe={
+ "summarize": PipeLLMBlueprint(
+ description="Summarize a document into an insight",
+ inputs={"doc": "Text"},
+ output="other_domain.Insight",
+ prompt="Summarize $doc.",
+ ),
+ },
+ )
+
+ # --- Domain metadata merge: order-independent, omission-quiet ---
+ # Under the additive model a same-domain library is authored as one root file (full domain header)
+ # plus membership-only sibling files that declare just `domain = "meta"`. These fixtures exercise the
+ # merge in isolation (no concepts/pipes needed — the metadata merge is independent of content).
+
+ # Root: carries the full domain header (description + system_prompt).
+ META_ROOT_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/meta_root.mthds",
+ domain="meta",
+ description="Meta domain",
+ system_prompt="You are a meta assistant.",
+ )
+
+ # Membership-only sibling: declares the domain, omits description and system_prompt.
+ META_MEMBER_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/meta_member.mthds",
+ domain="meta",
+ )
+
+ # Sibling re-declaring the SAME non-empty description and system_prompt as the root (no conflict).
+ META_SAME_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/meta_same.mthds",
+ domain="meta",
+ description="Meta domain",
+ system_prompt="You are a meta assistant.",
+ )
+
+ # Sibling declaring DIFFERENT non-empty description and system_prompt — a genuine double-declaration.
+ META_CONFLICT_BUNDLE: ClassVar[PipelexBundleBlueprint] = PipelexBundleBlueprint(
+ source="/fake/meta_conflict.mthds",
+ domain="meta",
+ description="A different meta domain",
+ system_prompt="You are a different meta assistant.",
+ )
diff --git a/tests/unit/pipelex/pipe_signature/test_pipe_signature_blueprint_validator.py b/tests/unit/pipelex/pipe_signature/test_pipe_signature_blueprint_validator.py
index 2f25f1bb2..35c80d95e 100644
--- a/tests/unit/pipelex/pipe_signature/test_pipe_signature_blueprint_validator.py
+++ b/tests/unit/pipelex/pipe_signature/test_pipe_signature_blueprint_validator.py
@@ -7,12 +7,14 @@ from pipelex.pipe_signature.pipe_signature_blueprint import PipeSignatureBluepri
class TestPipeSignatureBlueprintValidator:
def test_blueprint_rejects_signature_for_pipe_signature(self) -> None:
+ # `PipeSignature` is no longer a `PipeType` member, so Pydantic cannot coerce the string into
+ # `signature_for` — the rejection is now structural, not a custom validator.
with pytest.raises(ValidationError):
PipeSignatureBlueprint(
description="A signature cannot stand in for itself.",
inputs={"doc": "Text"},
output="Text",
- signature_for=PipeType.PIPE_SIGNATURE,
+ signature_for="PipeSignature", # type: ignore[arg-type]
)
def test_blueprint_accepts_signature_for_pipe_llm(self) -> None:
@@ -31,3 +33,26 @@ class TestPipeSignatureBlueprintValidator:
output="Text",
)
assert blueprint.signature_for is None
+
+ def test_blueprint_is_signature_true(self) -> None:
+ # Closes the base-False / subclass-True pair at the blueprint layer (otherwise only
+ # exercised indirectly through the factory's `blueprint.is_signature` branch).
+ blueprint = PipeSignatureBlueprint(
+ description="A signature reports is_signature directly.",
+ inputs={"doc": "Text"},
+ output="Text",
+ )
+ assert blueprint.is_signature is True
+
+ def test_blueprint_excludes_pipe_category_from_model_dump(self) -> None:
+ # `pipe_category` is None and `Field(exclude=True)`, so it must never serialize into emitted
+ # .mthds. This guards the `exclude=True` override independently of the JSON-schema exclusion
+ # test (a separate Pydantic mechanism): dropping `exclude=True` would leak it here while the
+ # schema test stayed green.
+ blueprint = PipeSignatureBlueprint(
+ description="A signature does not serialize a pipe_category.",
+ inputs={"doc": "Text"},
+ output="Text",
+ )
+ assert blueprint.pipe_category is None
+ assert "pipe_category" not in blueprint.model_dump()
diff --git a/tests/unit/pipelex/pipeline/test_build_validated_pipes.py b/tests/unit/pipelex/pipeline/test_build_validated_pipes.py
index 04ee5c758..4213eae8b 100644
--- a/tests/unit/pipelex/pipeline/test_build_validated_pipes.py
+++ b/tests/unit/pipelex/pipeline/test_build_validated_pipes.py
@@ -7,7 +7,7 @@ corrupt the published contract while the rest of the suite stays green:
1. **Truthful status.** A FAILURE (e.g. an ``allowed_to_fail`` pipe) and a SKIPPED (cross-package)
must surface as ``"FAILURE"`` / ``"SKIPPED"`` — NOT flattened to ``"SUCCESS"`` (the exact bug the
C-8 fix removed). The old callers hardcoded an all-``"SUCCESS"`` list.
-2. **Namespaced identity.** Each entry's ``pipe_code`` field carries the namespaced ``pipe_ref``
+2. **Namespaced identity.** Each entry's ``pipe_ref`` field carries the namespaced ``pipe_ref``
(``domain.code``), never the bare ``code`` — one unambiguous identity across every validate surface.
Pure unit test (no Pipelex boot, no inference): drives the projection over a hand-built result map.
@@ -34,7 +34,7 @@ class TestBuildValidatedPipes:
entries = build_validated_pipes(dry_run_result)
- by_ref = {entry["pipe_code"]: entry["status"] for entry in entries}
+ by_ref = {entry["pipe_ref"]: entry["status"] for entry in entries}
# Every entry is keyed by its namespaced pipe_ref, never the bare code.
assert set(by_ref) == {"domain_a.impl", "domain_a.flaky", "domain_b.xpkg"}
assert not ({"impl", "flaky", "xpkg"} & set(by_ref))
diff --git a/tests/unit/pipelex/pipeline/test_runner_models.py b/tests/unit/pipelex/pipeline/test_runner_models.py
new file mode 100644
index 000000000..e4d1c74ac
--- /dev/null
+++ b/tests/unit/pipelex/pipeline/test_runner_models.py
@@ -0,0 +1,55 @@
+"""Pin the protocol `models()` deck shape on :class:`PipelexMTHDSProtocol`.
+
+The aliases/waterfalls routing extensions are keyed BY CATEGORY: the same alias name exists
+in several categories pointing at different models, and the old flat maps (built by
+``update()``-ing the per-category maps together) silently dropped entries on those
+collisions. This is the regression pin for that fix — plus the presets→flat-``models``
+projection, each entry carrying its category as ``type``.
+
+Pure unit test (no Pipelex boot): ``list_models`` is patched at the runner's import site.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import pytest
+
+from pipelex.pipeline.runner import PipelexMTHDSProtocol
+
+if TYPE_CHECKING:
+ from pytest_mock import MockerFixture
+
+_DECK_RAW = {
+ "presets": {
+ "llm": [{"name": "gpt-mini"}, {"name": "claude-x"}],
+ "extract": [{"name": "extracto"}],
+ },
+ "aliases": {
+ "llm": {"default-small": "gpt-mini"},
+ "extract": {"default-small": "extracto"},
+ },
+ "waterfalls": {
+ "llm": {"default-small": ["gpt-mini", "claude-x"]},
+ "extract": {"default-small": ["extracto"]},
+ },
+}
+
+
[email protected](loop_scope="class")
+class TestRunnerModels:
+ async def test_deck_keeps_category_keyed_aliases_on_cross_category_collision(self, mocker: MockerFixture) -> None:
+ """The SAME alias name in two categories points at different models — both entries must survive."""
+ mocker.patch("pipelex.pipeline.runner.list_models", return_value=_DECK_RAW)
+
+ deck = await PipelexMTHDSProtocol().models()
+
+ assert {(model.name, model.type) for model in deck.models} == {
+ ("gpt-mini", "llm"),
+ ("claude-x", "llm"),
+ ("extracto", "extract"),
+ }
+ assert deck.aliases["llm"]["default-small"] == "gpt-mini"
+ assert deck.aliases["extract"]["default-small"] == "extracto"
+ assert deck.waterfalls["llm"]["default-small"] == ["gpt-mini", "claude-x"]
+ assert deck.waterfalls["extract"]["default-small"] == ["extracto"]
diff --git a/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py b/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py
index ff6d9c731..2edf1f547 100644
--- a/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py
+++ b/tests/unit/pipelex/pipeline/test_runner_protocol_surfaces.py
@@ -1,8 +1,8 @@
"""Coverage for the small protocol surfaces of :class:`PipelexMTHDSProtocol`.
Pins the ``extra`` rejection guard on ``execute``, the ``start`` not-implemented
-contract, the ``models`` deck shaping (presets to ModelInfo, aliases/waterfalls merged
-across categories, category filter passthrough), and the ``version`` handshake
+contract, the ``models`` deck shaping (presets to ModelInfo, aliases/waterfalls kept
+keyed by category, category filter passthrough), and the ``version`` handshake
including the missing-distribution fallback.
"""
@@ -14,10 +14,10 @@ from typing import TYPE_CHECKING, Any
import pytest
from mthds.protocol.exceptions import PipelineRequestError
from mthds.protocol.models import ModelCategory as MthdsModelCategory
+from mthds.protocol.protocol import PROTOCOL_VERSION
from pipelex.builder.operations.models_ops import ModelCategory
from pipelex.pipeline.runner import (
- MTHDS_PROTOCOL_VERSION,
PipelexModelDeck,
PipelexMTHDSProtocol,
PipelexVersionInfo,
@@ -65,9 +65,10 @@ class TestRunnerProtocolSurfaces:
assert "execute" in str(exc_info.value)
assert "not implemented by the local runtime" in str(exc_info.value)
- async def test_models_shapes_deck_and_merges_aliases_and_waterfalls(self, mocker: MockerFixture) -> None:
+ async def test_models_shapes_deck_and_keeps_aliases_and_waterfalls_keyed_by_category(self, mocker: MockerFixture) -> None:
"""Each preset becomes one ModelInfo typed by its category; aliases and
- waterfalls are merged across categories; no filter = categories None.
+ waterfalls stay keyed by category (no flattening, so the same alias name in
+ two categories can't collide); no filter = categories None.
"""
list_models_mock = mocker.patch("pipelex.pipeline.runner.list_models", return_value=_MODELS_PAYLOAD)
runner = PipelexMTHDSProtocol()
@@ -81,8 +82,8 @@ class TestRunnerProtocolSurfaces:
("cheap_llm", MthdsModelCategory.LLM),
("doc_extractor", MthdsModelCategory.EXTRACT),
}
- assert deck.aliases == {"best": "smart_llm", "ocr": "doc_extractor"}
- assert deck.waterfalls == {"main_chain": ["smart_llm", "cheap_llm"]}
+ assert deck.aliases == {"llm": {"best": "smart_llm"}, "extract": {"ocr": "doc_extractor"}}
+ assert deck.waterfalls == {"llm": {"main_chain": ["smart_llm", "cheap_llm"]}, "extract": {}}
list_models_mock.assert_called_once_with(categories=None)
async def test_models_category_filter_translates_to_builder_enum(self, mocker: MockerFixture) -> None:
@@ -100,8 +101,8 @@ class TestRunnerProtocolSurfaces:
list_models_mock.assert_called_once_with(categories=[ModelCategory.LLM])
assert isinstance(deck, PipelexModelDeck)
assert [(model_info.name, model_info.type) for model_info in deck.models] == [("smart_llm", MthdsModelCategory.LLM)]
- assert deck.aliases == {"best": "smart_llm"}
- assert deck.waterfalls == {}
+ assert deck.aliases == {"llm": {"best": "smart_llm"}}
+ assert deck.waterfalls == {"llm": {}}
async def test_version_reports_installed_distribution(self, mocker: MockerFixture) -> None:
"""All three implementation version fields carry the installed pipelex version,
@@ -113,7 +114,7 @@ class TestRunnerProtocolSurfaces:
version_info = await runner.version()
assert isinstance(version_info, PipelexVersionInfo)
- assert version_info.protocol_version == MTHDS_PROTOCOL_VERSION
+ assert version_info.protocol_version == PROTOCOL_VERSION
assert version_info.runner_version == "9.8.7"
assert version_info.implementation == "pipelex"
assert version_info.implementation_version == "9.8.7"
@@ -128,7 +129,7 @@ class TestRunnerProtocolSurfaces:
version_info = await runner.version()
assert isinstance(version_info, PipelexVersionInfo)
- assert version_info.protocol_version == MTHDS_PROTOCOL_VERSION
+ assert version_info.protocol_version == PROTOCOL_VERSION
assert version_info.runner_version == "unknown"
assert version_info.implementation == "pipelex"
assert version_info.implementation_version == "unknown"
diff --git a/tests/unit/pipelex/pipeline/test_runner_validate_method.py b/tests/unit/pipelex/pipeline/test_runner_validate_method.py
deleted file mode 100644
index 0a737d6e2..000000000
--- a/tests/unit/pipelex/pipeline/test_runner_validate_method.py
+++ /dev/null
@@ -1,201 +0,0 @@
-"""Coverage for :meth:`PipelexMTHDSProtocol.validate` — report shaping and library restore.
-
-Pins how the protocol wrapper maps a ``validate_bundle`` result onto
-``PipelexValidationReport`` (single blueprint = dict, multiple = list; pipe structures
-keyed by pipe code), the ``library_dirs``/``allow_signatures`` passthrough, and the
-finally-block matrix that restores the caller's current-library and tears the
-validation library down.
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-from typing import TYPE_CHECKING, NamedTuple
-
-import pytest
-
-from pipelex.pipeline.runner import PipelexMTHDSProtocol, PipelexValidationReport
-
-if TYPE_CHECKING:
- from pytest_mock import MockerFixture, MockType
-
-_BLUEPRINT_DUMP_ONE = {"domain": "demo", "description": "first bundle"}
-_BLUEPRINT_DUMP_TWO = {"domain": "extra", "description": "second bundle"}
-_PIPE_DUMP_ONE = {"code": "first_pipe", "type": "PipeLLM"}
-_PIPE_DUMP_TWO = {"code": "second_pipe", "type": "PipeFunc"}
-
-
-class _ValidateEnv(NamedTuple):
- validate_bundle_mock: MockType
- current_library_mock: MockType
- set_current_library_mock: MockType
- clear_current_library_mock: MockType
- library_manager: MockType
-
-
[email protected](loop_scope="class")
-class TestRunnerValidateMethod:
- def _make_blueprint(self, mocker: MockerFixture, dump: dict[str, str]) -> MockType:
- blueprint: MockType = mocker.MagicMock(name=f"blueprint_{dump['domain']}")
- blueprint.model_dump.return_value = dump
- return blueprint
-
- def _make_pipe(self, mocker: MockerFixture, dump: dict[str, str]) -> MockType:
- pipe: MockType = mocker.MagicMock(name=f"pipe_{dump['code']}")
- pipe.code = dump["code"]
- pipe.model_dump.return_value = dump
- return pipe
-
- def _patch_env(
- self,
- mocker: MockerFixture,
- *,
- blueprint_dumps: list[dict[str, str]],
- pipe_dumps: list[dict[str, str]],
- library_ids: list[str | None],
- ) -> _ValidateEnv:
- """Patch ``validate_bundle`` and the library hub getters at the runner namespace.
-
- ``library_ids`` feeds ``get_current_library_id_or_none`` as a side_effect pair:
- first call = the caller's prev library, second call = the validation library left
- current by ``validate_bundle``.
- """
- result = mocker.MagicMock(name="validate_bundle_result")
- result.blueprints = [self._make_blueprint(mocker, dump) for dump in blueprint_dumps]
- result.pipes = [self._make_pipe(mocker, dump) for dump in pipe_dumps]
- validate_bundle_mock = mocker.patch(
- "pipelex.pipeline.runner.validate_bundle",
- new=mocker.AsyncMock(return_value=result),
- )
- current_library_mock = mocker.patch(
- "pipelex.pipeline.runner.get_current_library_id_or_none",
- side_effect=library_ids,
- )
- set_current_library_mock = mocker.patch("pipelex.pipeline.runner.set_current_library")
- clear_current_library_mock = mocker.patch("pipelex.pipeline.runner.clear_current_library")
- library_manager = mocker.patch("pipelex.pipeline.runner.get_library_manager").return_value
- return _ValidateEnv(
- validate_bundle_mock=validate_bundle_mock,
- current_library_mock=current_library_mock,
- set_current_library_mock=set_current_library_mock,
- clear_current_library_mock=clear_current_library_mock,
- library_manager=library_manager,
- )
-
- async def test_single_blueprint_reported_as_dict(self, mocker: MockerFixture) -> None:
- """One blueprint = a bare dict (not a one-item list), with pipe structures keyed by code."""
- env = self._patch_env(
- mocker,
- blueprint_dumps=[_BLUEPRINT_DUMP_ONE],
- pipe_dumps=[_PIPE_DUMP_ONE, _PIPE_DUMP_TWO],
- library_ids=[None, "val-lib"],
- )
- runner = PipelexMTHDSProtocol()
-
- report = await runner.validate(mthds_contents=["bundle-content"])
-
- assert isinstance(report, PipelexValidationReport)
- assert report.blueprint == _BLUEPRINT_DUMP_ONE
- assert report.graph_spec is None
- assert report.pipe_structures == {"first_pipe": _PIPE_DUMP_ONE, "second_pipe": _PIPE_DUMP_TWO}
- for blueprint in env.validate_bundle_mock.return_value.blueprints:
- blueprint.model_dump.assert_called_once_with(mode="json")
- for pipe in env.validate_bundle_mock.return_value.pipes:
- pipe.model_dump.assert_called_once_with(mode="json")
-
- async def test_multiple_blueprints_reported_as_list(self, mocker: MockerFixture) -> None:
- """Several blueprints = a list of dicts in declaration order."""
- self._patch_env(
- mocker,
- blueprint_dumps=[_BLUEPRINT_DUMP_ONE, _BLUEPRINT_DUMP_TWO],
- pipe_dumps=[_PIPE_DUMP_ONE],
- library_ids=[None, "val-lib"],
- )
- runner = PipelexMTHDSProtocol()
-
- report = await runner.validate(mthds_contents=["content-one", "content-two"])
-
- assert isinstance(report, PipelexValidationReport)
- assert report.blueprint == [_BLUEPRINT_DUMP_ONE, _BLUEPRINT_DUMP_TWO]
- assert report.pipe_structures == {"first_pipe": _PIPE_DUMP_ONE}
-
- async def test_library_dirs_converted_to_paths_and_allow_signatures_passthrough(self, mocker: MockerFixture) -> None:
- """Constructor library_dirs strings reach validate_bundle as Path objects;
- allow_signatures is forwarded verbatim.
- """
- env = self._patch_env(
- mocker,
- blueprint_dumps=[_BLUEPRINT_DUMP_ONE],
- pipe_dumps=[],
- library_ids=[None, "val-lib"],
- )
- runner = PipelexMTHDSProtocol(library_dirs=["dir_alpha", "nested/dir_beta"])
-
- await runner.validate(mthds_contents=["bundle-content"], allow_signatures=True)
-
- env.validate_bundle_mock.assert_awaited_once_with(
- mthds_contents=["bundle-content"],
- library_dirs=[Path("dir_alpha"), Path("nested/dir_beta")],
- allow_signatures=True,
- )
-
- async def test_no_library_dirs_passes_none(self, mocker: MockerFixture) -> None:
- """Without constructor library_dirs, validate_bundle receives None (strict default)."""
- env = self._patch_env(
- mocker,
- blueprint_dumps=[_BLUEPRINT_DUMP_ONE],
- pipe_dumps=[],
- library_ids=[None, "val-lib"],
- )
- runner = PipelexMTHDSProtocol()
-
- await runner.validate(mthds_contents=["bundle-content"])
-
- env.validate_bundle_mock.assert_awaited_once_with(
- mthds_contents=["bundle-content"],
- library_dirs=None,
- allow_signatures=False,
- )
-
- @pytest.mark.parametrize(
- ("prev_library_id", "validation_library_id", "expect_set_prev", "expect_clear", "expect_teardown"),
- [
- pytest.param("outer-lib", "val-lib", True, False, True, id="prev_set_restores_then_teardown"),
- pytest.param(None, "val-lib", False, True, True, id="prev_none_clears_then_teardown"),
- pytest.param("same-lib", "same-lib", False, False, False, id="validation_is_prev_no_restore_no_teardown"),
- ],
- )
- async def test_finally_restores_caller_library_matrix(
- self,
- mocker: MockerFixture,
- prev_library_id: str | None,
- validation_library_id: str,
- expect_set_prev: bool,
- expect_clear: bool,
- expect_teardown: bool,
- ) -> None:
- """The finally restores the caller's current-library and tears the validation
- library down — unless the validation library IS the caller's library.
- """
- env = self._patch_env(
- mocker,
- blueprint_dumps=[_BLUEPRINT_DUMP_ONE],
- pipe_dumps=[],
- library_ids=[prev_library_id, validation_library_id],
- )
- runner = PipelexMTHDSProtocol()
-
- await runner.validate(mthds_contents=["bundle-content"])
-
- if expect_set_prev:
- env.set_current_library_mock.assert_called_once_with(library_id=prev_library_id)
- else:
- env.set_current_library_mock.assert_not_called()
- if expect_clear:
- env.clear_current_library_mock.assert_called_once_with()
- else:
- env.clear_current_library_mock.assert_not_called()
- if expect_teardown:
- env.library_manager.teardown.assert_called_once_with(library_id=validation_library_id)
- else:
- env.library_manager.teardown.assert_not_called()
diff --git a/tests/unit/pipelex/pipeline/test_runner_validate_plumbing.py b/tests/unit/pipelex/pipeline/test_runner_validate_plumbing.py
new file mode 100644
index 000000000..7aca19c1c
--- /dev/null
+++ b/tests/unit/pipelex/pipeline/test_runner_validate_plumbing.py
@@ -0,0 +1,134 @@
+"""Unit coverage for the plumbing of :meth:`PipelexMTHDSProtocol.validate`.
+
+Pins the wrapper's argument passthrough and library-lifecycle ``finally`` matrix with the
+domain collaborators mocked out — complementing the real-library integration coverage in
+``tests/integration/pipelex/pipeline/test_protocol_validate.py``. Specifically:
+
+- constructor ``library_dirs`` strings are converted to ``Path`` objects (and ``None`` when
+ unset) before reaching ``validate_bundle``, and ``allow_signatures`` is forwarded verbatim;
+- the ``finally`` restores the caller's current-library (``set`` when it had one, ``clear`` when
+ it didn't) and tears the validation library down — except when the validation library IS the
+ caller's, where it must do neither. That last branch is unreachable with a real
+ fresh-library ``validate_bundle`` (which always opens a new library id), so only a mocked
+ unit test can pin the guard.
+
+The report shaping itself is covered by ``test_validation_report.py`` and the integration
+``test_protocol_validate.py``; this module deliberately mocks ``build_validation_report`` and
+the artifact builders and asserts nothing about the returned report.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING, NamedTuple
+
+import pytest
+
+from pipelex.pipeline.runner import PipelexMTHDSProtocol
+
+if TYPE_CHECKING:
+ from pytest_mock import MockerFixture, MockType
+
+
+class _ValidateEnv(NamedTuple):
+ validate_bundle_mock: MockType
+ set_current_library_mock: MockType
+ clear_current_library_mock: MockType
+ library_manager: MockType
+
+
[email protected](loop_scope="class")
+class TestRunnerValidatePlumbing:
+ def _patch_env(self, mocker: MockerFixture, *, library_ids: list[str | None]) -> _ValidateEnv:
+ """Patch ``validate_bundle``, the library hub getters, and the report-artifact builders
+ at the runner namespace so ``validate``'s body runs without a real loaded library.
+
+ ``library_ids`` feeds ``get_current_library_id_or_none`` as a side_effect pair: first
+ call = the caller's prev library, second call = the validation library left current by
+ ``validate_bundle``.
+ """
+ validate_bundle_mock = mocker.patch(
+ "pipelex.pipeline.runner.validate_bundle",
+ new=mocker.AsyncMock(return_value=mocker.MagicMock(name="validate_bundle_result")),
+ )
+ mocker.patch("pipelex.pipeline.runner.get_current_library_id_or_none", side_effect=library_ids)
+ set_current_library_mock = mocker.patch("pipelex.pipeline.runner.set_current_library")
+ clear_current_library_mock = mocker.patch("pipelex.pipeline.runner.clear_current_library")
+ library_manager = mocker.patch("pipelex.pipeline.runner.get_library_manager").return_value
+ # These artifact builders run inside the library window; mock them so the body completes
+ # without a real loaded library. Their output shaping is pinned in test_validation_report.py
+ # and the integration test_protocol_validate.py — this module asserts only the plumbing.
+ mocker.patch("pipelex.pipeline.runner.build_pipe_io_contracts", return_value={})
+ mocker.patch("pipelex.pipeline.runner.select_primary_blueprint")
+ mocker.patch("pipelex.pipeline.runner.best_effort_graph_spec", new=mocker.AsyncMock(return_value=None))
+ mocker.patch("pipelex.pipeline.runner.build_validation_report")
+ return _ValidateEnv(
+ validate_bundle_mock=validate_bundle_mock,
+ set_current_library_mock=set_current_library_mock,
+ clear_current_library_mock=clear_current_library_mock,
+ library_manager=library_manager,
+ )
+
+ async def test_library_dirs_converted_to_paths_and_allow_signatures_passthrough(self, mocker: MockerFixture) -> None:
+ """Constructor library_dirs strings reach validate_bundle as Path objects; allow_signatures forwarded verbatim."""
+ env = self._patch_env(mocker, library_ids=[None, "val-lib"])
+ runner = PipelexMTHDSProtocol(library_dirs=["dir_alpha", "nested/dir_beta"])
+
+ await runner.validate(mthds_contents=["bundle-content"], allow_signatures=True)
+
+ env.validate_bundle_mock.assert_awaited_once_with(
+ mthds_contents=["bundle-content"],
+ library_dirs=[Path("dir_alpha"), Path("nested/dir_beta")],
+ allow_signatures=True,
+ )
+
+ async def test_no_library_dirs_passes_none_and_strict_default(self, mocker: MockerFixture) -> None:
+ """Without constructor library_dirs, validate_bundle receives None and the strict default."""
+ env = self._patch_env(mocker, library_ids=[None, "val-lib"])
+ runner = PipelexMTHDSProtocol()
+
+ await runner.validate(mthds_contents=["bundle-content"])
+
+ env.validate_bundle_mock.assert_awaited_once_with(
+ mthds_contents=["bundle-content"],
+ library_dirs=None,
+ allow_signatures=False,
+ )
+
+ @pytest.mark.parametrize(
+ ("prev_library_id", "validation_library_id", "expect_set_prev", "expect_clear", "expect_teardown"),
+ [
+ pytest.param("outer-lib", "val-lib", True, False, True, id="prev_set_restores_then_teardown"),
+ pytest.param(None, "val-lib", False, True, True, id="prev_none_clears_then_teardown"),
+ pytest.param("same-lib", "same-lib", False, False, False, id="validation_is_prev_no_restore_no_teardown"),
+ ],
+ )
+ async def test_finally_restores_caller_library_matrix(
+ self,
+ mocker: MockerFixture,
+ prev_library_id: str | None,
+ validation_library_id: str,
+ expect_set_prev: bool,
+ expect_clear: bool,
+ expect_teardown: bool,
+ ) -> None:
+ """The finally restores the caller's current-library and tears the validation library
+ down — unless the validation library IS the caller's library, where it does neither.
+ """
+ env = self._patch_env(mocker, library_ids=[prev_library_id, validation_library_id])
+ runner = PipelexMTHDSProtocol()
+
+ await runner.validate(mthds_contents=["bundle-content"])
+
+ if expect_set_prev:
+ env.set_current_library_mock.assert_called_once_with(library_id=prev_library_id)
+ else:
+ env.set_current_library_mock.assert_not_called()
+ if expect_clear:
+ env.clear_current_library_mock.assert_called_once_with()
+ else:
+ env.clear_current_library_mock.assert_not_called()
+ if expect_teardown:
+ env.library_manager.teardown.assert_called_once_with(library_id=validation_library_id)
+ else:
+ env.library_manager.teardown.assert_not_called()
diff --git a/tests/unit/pipelex/pipeline/test_select_primary_blueprint.py b/tests/unit/pipelex/pipeline/test_select_primary_blueprint.py
new file mode 100644
index 000000000..26736e494
--- /dev/null
+++ b/tests/unit/pipelex/pipeline/test_select_primary_blueprint.py
@@ -0,0 +1,88 @@
+"""Pin the D13 primary-blueprint selection rule: first blueprint declaring ``main_pipe``, else first.
+
+``select_primary_blueprint`` is the single selection rule shared by every validate surface — the
+canonical report's ``bundle_blueprint``, the graph arm's target derivation, and the Temporal
+activity. The qualified ``main_pipe_ref`` (``domain.main_pipe``) must come from the SAME blueprint
+that was selected, and be ``None`` when nothing in the batch declares a ``main_pipe``.
+
+Pure parsing test (no Pipelex boot, no library): blueprints come straight from the interpreter.
+"""
+
+import pytest
+
+from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
+from pipelex.core.interpreter.interpreter import PipelexInterpreter
+from pipelex.pipeline.blueprint_selection import select_primary_blueprint
+from pipelex.pipeline.exceptions import ValidateBundleError
+
+_NO_MAIN_PIPE_MTHDS = """
+domain = "alpha"
+description = "Concepts only, no main_pipe"
+
+[concept.Thing]
+description = "A thing"
+"""
+
+_MAIN_PIPE_BETA_MTHDS = """
+domain = "beta"
+description = "Declares a main_pipe"
+main_pipe = "do_it"
+
+[pipe.do_it]
+type = "PipeLLM"
+description = "Do it"
+inputs = { doc = "Text" }
+output = "Text"
+prompt = "Do it with $doc"
+"""
+
+_MAIN_PIPE_GAMMA_MTHDS = """
+domain = "gamma"
+description = "Also declares a main_pipe"
+main_pipe = "do_other"
+
+[pipe.do_other]
+type = "PipeLLM"
+description = "Do something else"
+inputs = { doc = "Text" }
+output = "Text"
+prompt = "Do something else with $doc"
+"""
+
+
+def _blueprint(mthds_content: str) -> PipelexBundleBlueprint:
+ return PipelexInterpreter.make_pipelex_bundle_blueprint(mthds_content=mthds_content)
+
+
+class TestSelectPrimaryBlueprint:
+ def test_none_declaring_selects_first_with_no_ref(self) -> None:
+ """No blueprint declares main_pipe: the first is primary and the ref is None."""
+ blueprints = [_blueprint(_NO_MAIN_PIPE_MTHDS), _blueprint(_NO_MAIN_PIPE_MTHDS.replace("alpha", "alpha_two"))]
+
+ selection = select_primary_blueprint(blueprints)
+
+ assert selection.blueprint is blueprints[0]
+ assert selection.main_pipe_ref is None
+
+ def test_first_declaring_wins_over_earlier_non_declaring(self) -> None:
+ """The first blueprint declaring main_pipe is primary, even when it is not first in the batch."""
+ blueprints = [_blueprint(_NO_MAIN_PIPE_MTHDS), _blueprint(_MAIN_PIPE_BETA_MTHDS)]
+
+ selection = select_primary_blueprint(blueprints)
+
+ assert selection.blueprint is blueprints[1]
+ assert selection.main_pipe_ref == "beta.do_it"
+
+ def test_multiple_declaring_first_wins(self) -> None:
+ """When several blueprints declare main_pipe, the first declaring one wins."""
+ blueprints = [_blueprint(_MAIN_PIPE_BETA_MTHDS), _blueprint(_MAIN_PIPE_GAMMA_MTHDS)]
+
+ selection = select_primary_blueprint(blueprints)
+
+ assert selection.blueprint is blueprints[0]
+ assert selection.main_pipe_ref == "beta.do_it"
+
+ def test_empty_batch_raises_structured_error(self) -> None:
+ """An empty batch raises a ValidateBundleError, never a raw IndexError."""
+ with pytest.raises(ValidateBundleError, match="empty batch"):
+ select_primary_blueprint([])
diff --git a/tests/unit/pipelex/pipeline/test_validation_report.py b/tests/unit/pipelex/pipeline/test_validation_report.py
new file mode 100644
index 000000000..fb1ec02ce
--- /dev/null
+++ b/tests/unit/pipelex/pipeline/test_validation_report.py
@@ -0,0 +1,82 @@
+"""Pin the D14 assembly contract of ``build_validation_report``.
+
+The canonical ``PipelexValidationReport`` is constructed in exactly one place — this assembly
+function — by every backend (local protocol ``validate``, hosted direct, hosted Temporal). The
+test pins what the assembly derives from its ingredients: primary-blueprint selection for
+``bundle_blueprint`` (first declaring ``main_pipe``, else first), the ``validated_pipes``
+projection from the dry-run status map, and ``is_runnable = not pending_signatures``.
+
+Pure unit test (no Pipelex boot): blueprints from the interpreter, hand-built status map.
+"""
+
+from pipelex.core.interpreter.interpreter import PipelexInterpreter
+from pipelex.pipeline.bundle_validator import DryRunOutput, DryRunStatus
+from pipelex.pipeline.pipe_io_contracts import IOMultiplicity, PipeIOContract, PipeOutputContract
+from pipelex.pipeline.validation_report import build_validation_report
+
+_NO_MAIN_PIPE_MTHDS = """
+domain = "alpha"
+description = "Concepts only, no main_pipe"
+
+[concept.Thing]
+description = "A thing"
+"""
+
+_MAIN_PIPE_MTHDS = """
+domain = "beta"
+description = "Declares a main_pipe"
+main_pipe = "do_it"
+
+[pipe.do_it]
+type = "PipeLLM"
+description = "Do it"
+inputs = { doc = "Text" }
+output = "Text"
+prompt = "Do it with $doc"
+"""
+
+
+class TestBuildValidationReport:
+ def test_assembles_canonical_report_from_ingredients(self) -> None:
+ blueprints = [
+ PipelexInterpreter.make_pipelex_bundle_blueprint(mthds_content=_NO_MAIN_PIPE_MTHDS),
+ PipelexInterpreter.make_pipelex_bundle_blueprint(mthds_content=_MAIN_PIPE_MTHDS),
+ ]
+ pipe_io_contracts = {
+ "beta.do_it": PipeIOContract(
+ inputs={},
+ output=PipeOutputContract(concept_code="native.Text", multiplicity=IOMultiplicity.SINGLE),
+ ),
+ }
+ dry_run_result: dict[str, DryRunOutput] = {
+ "beta.do_it": DryRunOutput(pipe_code="do_it", pipe_ref="beta.do_it", status=DryRunStatus.SUCCESS),
+ }
+
+ report = build_validation_report(
+ blueprints=blueprints,
+ pipe_io_contracts=pipe_io_contracts,
+ dry_run_result=dry_run_result,
+ pending_signatures=["beta.still_pending"],
+ )
+
+ # Primary selection: the first blueprint declaring main_pipe wins, not the first in the batch.
+ assert report.bundle_blueprint is blueprints[1]
+ assert report.pipe_io_contracts == pipe_io_contracts
+ assert report.validated_pipes == [{"pipe_ref": "beta.do_it", "status": DryRunStatus.SUCCESS}]
+ assert report.pending_signatures == ["beta.still_pending"]
+ assert report.is_runnable is False
+ assert report.graph_spec is None
+
+ def test_runnable_when_nothing_pending(self) -> None:
+ blueprints = [PipelexInterpreter.make_pipelex_bundle_blueprint(mthds_content=_MAIN_PIPE_MTHDS)]
+
+ report = build_validation_report(
+ blueprints=blueprints,
+ pipe_io_contracts={},
+ dry_run_result={},
+ pending_signatures=[],
+ )
+
+ assert report.bundle_blueprint is blueprints[0]
+ assert report.is_runnable is True
+ assert report.validated_pipes == []
diff --git a/tests/unit/pipelex/temporal/test_dry_validate_dispatch.py b/tests/unit/pipelex/temporal/test_dry_validate_dispatch.py
index 72b7131f3..75f94adaf 100644
--- a/tests/unit/pipelex/temporal/test_dry_validate_dispatch.py
+++ b/tests/unit/pipelex/temporal/test_dry_validate_dispatch.py
@@ -23,7 +23,7 @@ from pipelex.temporal.tprl_pipe.wf_dry_validate import WfDryValidate
class TestDryValidateDispatch:
@pytest.mark.asyncio
async def test_dispatch_pins_no_workflow_retry_and_interactive_timeout(self, mocker: MockerFixture) -> None:
- expected_result = DryValidateResult(dry_run_outputs={})
+ expected_result = DryValidateResult(dry_run_outputs={}, pending_signatures=[], pipe_io_contracts={})
fake_executor = mocker.Mock()
fake_executor.make_workflow_id.return_value = "wf_dry_validate_test"
fake_executor.execute_workflow = mocker.AsyncMock(return_value=expected_result)
diff --git a/wip/recursivity/domain-metadata-merge.md b/wip/recursivity/domain-metadata-merge.md
new file mode 100644
index 000000000..7d0cc56ce
--- /dev/null
+++ b/wip/recursivity/domain-metadata-merge.md
@@ -0,0 +1,72 @@
+# Handoff — domain metadata merge under the additive multi-file model (pipelex)
+
+> **Status: DONE.** Implemented on `feature/Support-recursive-design`. Surfaced during the final `mthds-plugins/wip/recursive/design.md` review. Small, self-contained pipelex change. Builds on the additive multi-file model already shipped on this branch (see `../../TODOS.md` Parts A+B and [`recursive-followups.md`](recursive-followups.md) Tasks 1–2). Does **not** block the additive model — it removes friction the model introduces.
+>
+> Verified: `make agent-test` (green) + `make agent-check` (clean).
+>
+> **As built.** Added the order-independent, omission-quiet merge as a shared helper `pipelex/libraries/domain/domain_metadata_merge.py::merge_domain_metadata_field(...)`, wired from both `LibraryCrateFactory.make_from_blueprints` (crate-blueprint layer) and `DomainLibrary.add_domain` (runtime-`Domain` layer). The resolved conflict-resolution TODO at `domain_library.py` is gone (the separate system_prompt-inlining TODO is kept). `main_pipe` left untouched (inert, per below). Tests in `tests/unit/pipelex/libraries/test_library_crate.py` + `test_domain_library.py` (both-orders membership, same-value no-warn, conflict-warns, across description + system_prompt) with warnings asserted via `caplog`. CHANGELOG `[Unreleased]` sub-bullet folded into the "Additive multi-file library construction" entry.
+
+## Why
+
+The additive model authors a same-domain library as many `.mthds` files: one **root** (`bundle.mthds`) that carries the full domain header (`domain`, `description`, `main_pipe`, optional `system_prompt`) and N **non-root definition files** that carry only `domain = "<same_domain>"` to declare membership (see `design.md` §2.7 and the §3 worked example — `build_research_brief.mthds` sets only `domain = "research_brief"`).
+
+The domain-metadata merge was written for the single-file world (first-write-wins + warn on any difference). Under the additive model it misbehaves in two ways, both rooted in "an omitted field is treated as a conflicting empty value":
+
+1. **Spurious warnings on every validation.** A non-root file omits `description`, so the merge compares the root's real description against `""` and logs `Domain '<d>' declared with different descriptions: '<real>' vs ''. Keeping the first.` This fires once per non-root file, at **two** layers (see Where), and the PostToolUse hook validates the whole library (`-L <dir>`) on **every per-file save** — so a build of K files emits O(K) warnings on every save. Pure noise that will train authors/agents to ignore warnings.
+
+2. **Load-order-dependent metadata loss (the real bug).** First-write-wins means the *first* domain blueprint seen wins. If a non-root file (empty description) is merged before the root, the assembled domain keeps `description = ""` and the root's real description is **discarded** (with the warning above). The assembled domain's `description` / `system_prompt` therefore depend on file load order — which for a `-L` directory is filesystem/sort order, not authoring intent. (Example: `build_research_brief.mthds` sorts before `bundle.mthds`, so the empty-description sibling can win.)
+
+`description` / `system_prompt` are display/doc/PipeLLM-fallback metadata, not execution-critical, so this is not a correctness-of-results bug — but it is wrong, order-dependent, and noisy.
+
+**Not affected — `main_pipe` (verified, do not "fix").** The runtime `Domain` model (`pipelex/core/domains/domain.py`) carries only `code`, `description`, `system_prompt` — **no `main_pipe`** — and `DomainFactory.make_from_blueprint` copies only description + system_prompt. The `DomainBlueprint.main_pipe` set during the crate merge is dropped when the runtime `Domain` is built, so the first-write-wins on `main_pipe` is inert. Main-pipe existence is validated **per file** on the bundle blueprint that declares it (`PipelexBundleBlueprint`, the `main_pipe in self.pipe` check), and the root always carries both `main_pipe` and the matching header (Layer 0), so that check passes. No order-fragility there. Leave it alone.
+
+## Where (verified file:line)
+
+Two sites apply the same first-write-wins + warn-on-difference logic. Both need the same relaxation:
+
+- `pipelex/libraries/library_crate_factory.py` — `make_from_blueprints`, the domain block (currently ~l.63–83). Builds the per-domain `DomainBlueprint`; `description=blueprint.description or ""`; the `else` arm warns when `existing.description != (blueprint.description or "")` and when `existing.system_prompt != blueprint.system_prompt`.
+- `pipelex/libraries/domain/domain_library.py` — `add_domain` (~l.33–50). Same warn-on-difference at runtime-`Domain` registration. **Already carries a TODO** at l.34: `# TODO: resolve domain metadata conflicts properly — currently first-write-wins with a warning.` This handoff is that TODO.
+
+Supporting facts (verified):
+- `PipelexBundleBlueprint.description: str | None = None` — omitting it is legal (`pipelex/core/bundles/pipelex_bundle_blueprint.py`).
+- `DomainBlueprint.description: str` (required) — the factory coerces an omitted bundle description to `""` (`pipelex/core/domains/domain_blueprint.py`).
+- `Domain.description: str | None = None`, `Domain.system_prompt: str | None = None` (`pipelex/core/domains/domain.py`).
+
+## The fix
+
+Make domain-metadata merge **order-independent** and **quiet for omissions**: an omitted (empty/`None`) `description` or `system_prompt` contributes *no opinion* — it neither overrides an established non-empty value nor triggers a warning. Warn **only** when two *non-empty* values genuinely differ (a real conflict the author should resolve).
+
+Concretely, per domain field (`description`, `system_prompt`):
+- established empty/None + incoming non-empty → take incoming, no warning (root can arrive after a sibling).
+- established non-empty + incoming empty/None → keep established, no warning (sibling defers to root).
+- both non-empty and equal → keep, no warning.
+- both non-empty and different → keep first, **warn** (genuine conflict — unchanged behavior).
+
+This means the root's `description`/`system_prompt` always wins over membership-only siblings regardless of load order, and the additive flow is warning-free, while genuine double-declarations still warn.
+
+**Apply at both sites**, or — preferred — extract one shared helper (e.g. `pipelex/libraries/domain/domain_metadata_merge.py::merge_domain_metadata(...)` or a `DomainBlueprint`/`Domain` "fold" method) and call it from both `make_from_blueprints` and `add_domain`, so the two layers can't drift. Keep the existing class/`type_uri`/message slugs; this is behavior-narrowing on the no-conflict path only.
+
+### Authoring-side alternative (rejected as primary)
+
+We could instead require every non-root file to repeat the full domain header (`description`, `system_prompt`). Rejected: it forces prose duplication across every definition file, which is its own drift source and defeats the point of membership-only sibling files. The runtime fix is the right lever; if anything, the cheat sheet should explicitly say non-root files carry **only** `domain = "..."`.
+
+## Tasks
+
+- [x] Add the order-independent, omission-quiet merge (shared helper) and wire both `make_from_blueprints` and `DomainLibrary.add_domain` to it. Removed the now-resolved conflict-resolution TODO at `domain_library.py` (kept the separate system_prompt-inlining TODO).
+- [x] `make agent-check` clean (ruff, plxt, pyright, mypy).
+- [x] Tests below green; then full `make agent-test`.
+- [x] CHANGELOG `[Unreleased]` entry (folded into the existing "Additive multi-file library construction" entry).
+
+## Tests
+
+- Root (real description) + sibling (`domain` only) merged **both orders** → assembled domain keeps the root's description/system_prompt; **no warning** emitted. Assert at both layers (crate factory result and `DomainLibrary` after `add_domains`).
+- Two files each declaring a **different non-empty** description → first kept, **warning** still emitted (unchanged).
+- Two files with the **same non-empty** description → kept, no warning.
+- Cover `system_prompt` with the same matrix.
+- Regression: existing single-file domain-metadata tests still pass.
+
+(Capture warnings with `caplog`/the project's log-capture fixture; assert presence/absence explicitly — the whole point is the no-warning path.)
+
+## Tracked from
+
+`mthds-plugins/wip/recursive/design.md` §2.7 (the additive multi-file layout: root carries the domain header, siblings carry only `domain =`) and §3 (the worked example whose sibling files omit `description`). Also indexed in `mthds-plugins/wip/deferred-issues.md`.
diff --git a/wip/recursivity/protocol-validate-pending-signatures.md b/wip/recursivity/protocol-validate-pending-signatures.md
new file mode 100644
index 000000000..e61adcd92
--- /dev/null
+++ b/wip/recursivity/protocol-validate-pending-signatures.md
@@ -0,0 +1,32 @@
+# Follow-up — surface `pending_signatures` / `is_runnable` on the protocol-level `validate`
+
+> **Status: ✅ DONE — implemented 2026-06-12.** `pending_signatures` + `is_runnable` added to `PipelexValidationReport` and populated in `PipelexMTHDSProtocol.validate`; first test coverage for the protocol `validate` landed in `tests/integration/pipelex/pipeline/test_protocol_validate.py` (verdict on both paths, strict-mode raise, library-lifecycle contract); changelog updated under `[Unreleased]`.
+
+## Context (cold start)
+
+v0.33.0 (PR #985) turned the runner into a local MTHDS Protocol implementation: `PipelexMTHDSProtocol` in `pipelex/pipeline/runner.py`. Its `validate(mthds_contents, allow_signatures=False)` method wraps our `validate_bundle` and maps the result onto `PipelexValidationReport`, currently returning only `blueprint`, `graph_spec=None`, and `pipe_structures`.
+
+Meanwhile this branch's recursive-design work made `validate_bundle` compute the runnability verdict: `ValidateBundleResult.pending_signatures` (`pipelex/pipeline/validate_bundle.py` — `build_pending_signatures`, library-wide, cross-package refs excluded). It is surfaced as `pending_signatures: string[]` + `is_runnable: bool` on the agent-CLI / builder validate envelopes (`pipelex/cli/agent_cli/commands/validate/_validate_core.py`, `pipelex/builder/operations/validate_ops.py` — `is_runnable = not pending_signatures` everywhere), but **not** on the protocol `validate` — so a top-down build driving the runtime through the MTHDS Protocol (instead of the agent CLI) can't see what remains to implement.
+
+This is protocol-legal without any spec change: the protocol base `mthds.protocol.models.ValidationReport` deliberately declares **no body fields** and sets `extra="allow"` — "implementations may include their own artifacts". `PipelexValidationReport` already follows that pattern with `blueprint` / `graph_spec` / `pipe_structures` as Pipelex extension fields.
+
+## Plan
+
+1. **Add the two extension fields to `PipelexValidationReport`** (`pipelex/pipeline/runner.py`): `pending_signatures: list[str] = Field(default_factory=list)` and `is_runnable: bool = True`.
+2. **Populate them in `PipelexMTHDSProtocol.validate`** from the `validate_bundle` result, mirroring the CLI convention: `pending_signatures=result.pending_signatures, is_runnable=not result.pending_signatures`. The wrapper already holds `result` in hand where it builds the report — a two-line change.
+3. **Tests — note there is currently NO test coverage for `PipelexMTHDSProtocol.validate` at all** (grep `\.validate(` under `tests/` finds nothing against the protocol wrapper). So this needs a first integration test, e.g. `tests/integration/pipelex/pipeline/test_protocol_validate.py`:
+ - a complete bundle → `pending_signatures == []`, `is_runnable is True`;
+ - a bundle with an unsatisfied `PipeSignature`, `allow_signatures=True` → the signature's qualified ref in `pending_signatures`, `is_runnable is False`;
+ - reuse the `.mthds` fixtures under `tests/e2e/pipelex/pipes/additive_multi_file_library/signature_only/` (header + concepts, no definition) rather than authoring new ones.
+ - While there, the test can also pin the wrapper's library-lifecycle contract (restores the caller's current library, tears the validation library down) — it's documented in a comment in `validate` but untested.
+4. **Changelog** — entry under `[Unreleased]` (Changed, alongside the existing additive-multi-file entry that already documents `pending_signatures` on the CLI surfaces).
+
+## Verify
+
+`make agent-check` clean + `make agent-test` green (per repo standard).
+
+## Watch-outs
+
+- **Strict-mode interplay:** with `allow_signatures=False` (the protocol default), an unsatisfied signature makes `validate_bundle` *raise* (`ValidateBundleError` from the strict refusal) — the report fields only matter on the lenient path. Don't try to populate them on the failure path; failures are RFC 7807 problems per the protocol docstring.
+- **Downstream — CORRECTED 2026-06-12:** the original assumption here ("pipelex-api serializes whatever `validate` returns, fields appear automatically") is **wrong**. `pipelex-api`'s `/validate` route does NOT call `PipelexMTHDSProtocol.validate` — it builds its own strict `ValidateResponse` pydantic envelope (`api/routes/pipelex/validate.py`), calling `validate_bundle` directly (direct mode) or `act_dry_validate` (Temporal mode), and neither that envelope nor `DryValidateResult` carries `pending_signatures`. Surfacing the verdict on the hosted `/validate` therefore needs explicit changes — now part of a broader protocol-surface alignment (the full consistency pass also found `/models` divergence, `pipe_structures` shape conflicts, and a duplicated protocol-version constant). Live plan: workspace root `wip/mthds-protocol-surface-alignment.md` (supersedes `../pipelex-api/wip/validate-pending-signatures-envelope.md`).
+- A related deliberate omission: `validate all` / `validate pipe` intentionally omit `pending_signatures` (it's a per-bundle, top-down-build nudge — rationale in the comments at `pipelex/builder/operations/validate_ops.py` `validate_all` and `pipelex/cli/agent_cli/commands/validate/_validate_core.py`). The protocol `validate` is bundle-shaped, so it takes the field; don't propagate it to the all/pipe surfaces. The original feature record is Task 1 in [`recursive-followups.md`](recursive-followups.md).
diff --git a/wip/recursivity/recursive-followups.md b/wip/recursivity/recursive-followups.md
new file mode 100644
index 000000000..ac7bd11a8
--- /dev/null
+++ b/wip/recursivity/recursive-followups.md
@@ -0,0 +1,58 @@
+# Handoff — recursive-building runtime follow-ups (pipelex)
+
+> **Status: ✅ BOTH DONE** — shipped on `feature/Support-recursive-design`. Task 1 (`pending_signatures` on validate) and Task 2 (normalized contract conformance) are implemented and verified. The detail below is kept as the record of what was built.
+
+Two follow-ups on the pipelex side, surfaced during the `mthds-plugins` design review. Both build on the additive multi-file model already shipped on this branch (`feature/Support-recursive-design`; see `../../TODOS.md` for Parts A + B). Neither blocks the additive model; both make it robust/complete. Independent of each other — land in either order.
+
+Verify after each: `make agent-test` (green) + `make agent-check` (clean).
+
+---
+
+## Task 1 — Expose the unsatisfied-signature set on a successful lenient validate ✅ DONE
+
+> Shipped: `validate bundle` now emits `pending_signatures: string[]` (library-wide namespaced refs still typed `PipeSignature`; empty when complete) in the JSON envelope and as a "Pending signatures" markdown section, on agent-CLI + builder surfaces.
+
+**Why.** The `mthds-plugins` PostToolUse hook wants a non-blocking "these pipes are still unimplemented" nudge on a *successful* `--allow-signatures` run (design.md §5.2). Today the reachable-signature list is surfaced only on *strict* failure (`SignaturesNotAllowedError`); a lenient success emits no machine-readable list of what remains.
+
+**Key simplification (from Part A).** Once a concrete reconciles with a signature, the signature is *replaced* in the merged library. So "unsatisfied signatures" = exactly the pipes still typed `PipeSignature` in the assembled library. No `{signatures} − {concretes}` arithmetic needed — just enumerate `is_signature` pipes.
+
+**Where.**
+- `pipelex/pipeline/validate_bundle.py` — `ValidateBundleResult` (l.39) already carries `pipes: list[PipeAbstract]`. Add a projection next to `build_validated_pipes` (l.57):
+
+ ```python
+ def build_pending_signatures(pipes: list[PipeAbstract]) -> list[str]:
+ """Qualified refs of pipes still declared as PipeSignature (unsatisfied headers)."""
+ return sorted(pipe.pipe_ref for pipe in pipes if pipe.is_signature)
+ ```
+
+ (`PipeAbstract.is_signature` and `.pipe_ref` already exist.)
+- Surface it on the agent-CLI validate JSON envelope, next to `validated_pipes` — find the surface that calls `build_validated_pipes` (the `pipelex-agent validate bundle` command under `pipelex/cli/agent_cli/.../validate/`). Add a `pending_signatures` array. Mirror on the plain `pipelex validate bundle` command if it emits structured output. A one-line human note on success ("N pipe(s) still PipeSignature: …") is optional.
+
+**Scope nuance — compute from the library, not `result.pipes`.** For the file-path path, when the file is already loaded `result.pipes` is only *that file's* pipes (l.262-265). The hook validates one file at a time but wants the *whole-library* pending set. Compute pending from the assembled library (`library.pipe_library`), not from `result.pipes`, so the answer is library-wide regardless of which file triggered the run.
+
+**Tests.** Lenient validate of a bundle with unsatisfied headers → `pending_signatures` lists them; after every header has a concrete definition → empty. Fold into the additive integration test (`tests/integration/pipelex/libraries/test_additive_multi_file_library.py`).
+
+---
+
+## Task 2 — Proper (normalized) contract conformance, replacing raw-string `contract_equals` ✅ DONE
+
+> Shipped: header↔definition contracts reconcile by concept identity (bare ≡ qualified, `Text` ≡ `native.Text`, structural multiplicity); genuinely different concepts or differing multiplicity still error; refinement substitutability stays deferred.
+
+**Why.** `PipeBlueprint.contract_equals` (pipe_blueprint.py:111-120) compares raw strings. But Part B resolves concept refs flexibly (bare ↔ domain-qualified), so a header `output = "Brief"` and a definition `output = "thisdomain.Brief"` denote the *same* concept yet fail `contract_equals` → a false mismatch. Raw-string is not a proper check.
+
+**Scope: normalize for _identity_** — bare↔qualified, whitespace, multiplicity parsed structurally. This is **not** refinement substitutability (covariant output / contravariant inputs); that stays deferred (`mthds-plugins/wip/deferred-issues.md` → "Substitutable contract conformance…").
+
+**Normalization (reuse existing helpers).** For each concept spec:
+- Parse multiplicity with `parse_concept_with_multiplicity` (already used in `PipeBlueprint.generic_validate_output`) → `(concept_ref_or_code, multiplicity)`.
+- Canonicalize the ref: native (`NativeConceptCode`) → keep the native code; cross-package (`QualifiedRef.has_cross_package_prefix`) → keep; external-domain qualified → keep; bare / same-domain → `ConceptFactory.make_concept_ref_with_domain(domain_code, code)`.
+- Compare canonical `(qualified_ref, multiplicity)` tuples: `inputs` as a `name → tuple` dict (`None` ≡ `{}`), `output` as a tuple.
+
+**Domain context.** `contract_equals` lives on the blueprint, which doesn't carry its domain. The caller does: `_reconcile_pipe_collision` (library_crate_factory.py:136) runs inside the merge loop that has `domain_code` (l.59), and both declarations share the domain (same `pipe_ref`). So pass `domain_code` into `_reconcile_pipe_collision` and into the comparison. Suggest a focused free function `pipelex/libraries/contract_match.py::contracts_match(a, b, *, domain_code) -> bool` (mirroring `collision_messages.py` / `concept_reference_validation.py`), and replace the `existing.blueprint.contract_equals(incoming.blueprint)` call at l.166. Retire `contract_equals` or keep it as a thin raw fallback — your call.
+
+**Tests.** Header `Brief` + def `thisdomain.Brief` reconcile; whitespace / multiplicity-spelling variants reconcile; native refs reconcile; genuinely different concepts or differing multiplicity still mismatch. Update any existing exact-match tests that assumed raw-string equality.
+
+**Boundary.** Refinement-aware substitutability stays deferred — see `mthds-plugins/wip/deferred-issues.md`.
+
+---
+
+These two follow-ups are tracked from the design doc: Task 1 backs design.md §5.2/§5.4 (the leftover-signature nudge), Task 2 backs §2.7/§4.5 (the exact-match contract rule, which this upgrades from raw-string to normalized).
diff --git a/wip/recursivity/review-followups.md b/wip/recursivity/review-followups.md
new file mode 100644
index 000000000..889d36425
--- /dev/null
+++ b/wip/recursivity/review-followups.md
@@ -0,0 +1,21 @@
+# Deferred polish — additive multi-file library (from pre-landing /review)
+
+> **Status: DEFERRED (P3 only).** Surfaced by the pre-landing `/review` on `feature/Support-recursive-design` (PR #970) via independent adversarial + testing + maintainability reviewers. None are bugs; the review verdict was **ship**. Both PR bots (greptile 5/5, cubic clean) and the full suite were green. These are recorded so they aren't lost — pick up only if touching this area again. Not worth re-triggering a CI/bot cycle on their own.
+
+## Documentation / clarity nits
+
+- **`domain_metadata_merge.py` summary line slightly overclaims "order-independent."** The merge is order-independent for the omission cases (a membership-only sibling never overrides a declared value), but two files declaring *different* non-empty values is genuinely first-seen-wins (it always warns). The docstring body already lists this case correctly ("both non-empty and different -> keep the first, warn"); only the one-line summary reads as if every case were order-independent. If editing this file, soften the summary to name the warned-conflict exception.
+
+- **`library_crate_factory.py` `_reconcile_pipe_collision` tie-break drops a losing signature's `description` silently.** When two `PipeSignature`s for the same pipe have matching contracts but different `description`s, the deterministic `min(...)` tie-break keeps one and discards the other's description with no warning. This is harmless in practice — signature descriptions are advisory and a concrete definition's description wins outright once it arrives — but it's a silent drop. If touching reconciliation, add a one-line comment noting header descriptions are advisory (or warn, only if a real need appears; a warning here would be over-engineering for the DAG-forward-declared-by-multiple-callers edge).
+
+- **`library_crate_factory.py` `or ""` coercion asymmetry.** The crate-factory merge coerces `merge_domain_metadata_field(...) or ""` because `DomainBlueprint.description` is non-optional, while the `DomainLibrary` merge of the same field needs no coercion because `Domain.description` is `str | None`. Behavior is correct; a one-line comment at the `or ""` would save a future reader the double-take.
+
+## Test-coverage gap (low confidence)
+
+- **`validate_bundle.py` `LibraryLoadingError` structured-forwarding branch is exercised but not asserted with a *populated* payload.** The `except LibraryError` arm forwards `blueprint_validation_errors` / `pipe_concept_validation_errors` when the error is a `LibraryLoadingError`. The generic-`LibraryError` `else` branch is well covered (undeclared concept/pipe). The `isinstance(LibraryLoadingError)` branch is reached only by the cycle-detection test, whose error carries *empty* lists — so no test proves a populated structured payload survives onto the resulting `ValidateBundleError` (which the CLI renders). A regression that collapsed the two branches would not be caught. If revisiting: one integration test driving a `LibraryLoadingError` with non-empty validation-error lists through `validate_bundle` and asserting the forwarded fields are populated (not `None`).
+
+## Explicitly NOT worth doing (recorded so they aren't re-raised)
+
+- `contracts_match` input-name divergence (same arity, same specs, different variable name): transitively covered by the dict comparison; a dedicated case would be over-testing.
+- The `contract_match` `match is None` defensive return for a cross-package spec in `inputs`/`output`: documented as an impossible-in-blueprints input handled defensively; do not add a test for it.
+- The inline undeclared-ref message in `concept_reference_validation.py`: fine as a one-off; only centralize next to `duplicate_ref_msg` if a third such message appears.
diff --git a/wip/recursivity/signature-taxonomy-refactor.html b/wip/recursivity/signature-taxonomy-refactor.html
new file mode 100644
index 000000000..be95fd37f
--- /dev/null
+++ b/wip/recursivity/signature-taxonomy-refactor.html
@@ -0,0 +1,705 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1.0" />
+<title>PipeSignature: contract, not pipe type — taxonomy eviction</title>
+<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
+<style>
+ :root {
+ --bg: #0f1117;
+ --panel: #171a23;
+ --panel-2: #1d212c;
+ --ink: #e6e8ee;
+ --ink-dim: #a4abbb;
+ --ink-faint: #717789;
+ --accent: #7aa2ff;
+ --accent-2: #5ad1b3;
+ --warn: #f0b35e;
+ --bad: #ef6f6f;
+ --good: #5ad19a;
+ --border: #2a2f3d;
+ --code-bg: #0c0e14;
+ --add: #1f3a2b;
+ --add-ink: #8be0a8;
+ --del: #3a2026;
+ --del-ink: #f08f9c;
+ --radius: 12px;
+ --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
+ --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
+ }
+ * { box-sizing: border-box; }
+ html { scroll-behavior: smooth; }
+ body {
+ margin: 0;
+ background: var(--bg);
+ color: var(--ink);
+ font-family: var(--sans);
+ line-height: 1.62;
+ font-size: 16px;
+ }
+ .wrap { max-width: 940px; margin: 0 auto; padding: 0 24px 120px; }
+ header.hero {
+ padding: 56px 24px 40px;
+ background:
+ radial-gradient(1200px 400px at 20% -10%, rgba(122,162,255,0.16), transparent 60%),
+ radial-gradient(900px 380px at 95% 0%, rgba(90,209,179,0.12), transparent 55%);
+ border-bottom: 1px solid var(--border);
+ }
+ .hero-inner { max-width: 940px; margin: 0 auto; }
+ .eyebrow {
+ text-transform: uppercase;
+ letter-spacing: 0.14em;
+ font-size: 12px;
+ font-weight: 700;
+ color: var(--accent-2);
+ margin: 0 0 12px;
+ }
+ h1 { font-size: 34px; line-height: 1.18; margin: 0 0 14px; letter-spacing: -0.01em; }
+ h1 code { font-size: 0.82em; }
+ .sub { color: var(--ink-dim); font-size: 17px; margin: 0; max-width: 760px; }
+ .badges { margin-top: 22px; display: flex; gap: 10px; flex-wrap: wrap; }
+ .badge {
+ font-size: 12.5px; font-weight: 600;
+ padding: 5px 11px; border-radius: 999px;
+ border: 1px solid var(--border); background: var(--panel);
+ color: var(--ink-dim);
+ display: inline-flex; gap: 7px; align-items: center;
+ }
+ .badge.green { color: var(--good); border-color: rgba(90,209,154,0.4); }
+ .badge .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
+
+ h2 {
+ font-size: 24px; margin: 52px 0 16px; letter-spacing: -0.01em;
+ padding-bottom: 8px; border-bottom: 1px solid var(--border);
+ }
+ h3 { font-size: 18.5px; margin: 32px 0 10px; color: var(--ink); }
+ h2 .num {
+ color: var(--accent); font-variant-numeric: tabular-nums;
+ margin-right: 10px; font-weight: 700;
+ }
+ p { margin: 12px 0; }
+ a { color: var(--accent); text-decoration: none; }
+ a:hover { text-decoration: underline; }
+ code {
+ font-family: var(--mono); font-size: 0.88em;
+ background: var(--code-bg); border: 1px solid var(--border);
+ padding: 1px 6px; border-radius: 6px; color: #d8dcff;
+ }
+ strong { color: #fff; font-weight: 650; }
+ em { color: var(--ink); }
+
+ /* TL;DR */
+ .tldr {
+ margin: 28px 0 8px;
+ background: linear-gradient(180deg, var(--panel) 0%, var(--panel-2) 100%);
+ border: 1px solid var(--border);
+ border-left: 4px solid var(--accent);
+ border-radius: var(--radius);
+ padding: 22px 26px;
+ }
+ .tldr h2 { border: 0; margin: 0 0 6px; font-size: 20px; }
+ .tldr .lead { font-size: 17px; color: var(--ink); margin: 0 0 14px; }
+ .tldr ul { margin: 10px 0 0; padding-left: 20px; }
+ .tldr li { margin: 7px 0; color: var(--ink-dim); }
+ .tldr li strong { color: #fff; }
+
+ /* callouts */
+ .note, .principle {
+ border: 1px solid var(--border); border-radius: var(--radius);
+ padding: 16px 20px; margin: 20px 0; background: var(--panel);
+ }
+ .note { border-left: 4px solid var(--accent-2); }
+ .note .label {
+ font-size: 12px; text-transform: uppercase; letter-spacing: .08em;
+ font-weight: 700; color: var(--accent-2); margin: 0 0 6px;
+ }
+ .principle { border-left: 4px solid var(--warn); }
+ .principle .label {
+ font-size: 12px; text-transform: uppercase; letter-spacing: .08em;
+ font-weight: 700; color: var(--warn); margin: 0 0 6px;
+ }
+
+ /* TOC */
+ .toc {
+ background: var(--panel); border: 1px solid var(--border);
+ border-radius: var(--radius); padding: 18px 22px; margin: 28px 0;
+ }
+ .toc-title { font-size: 12.5px; text-transform: uppercase; letter-spacing: .1em; color: var(--ink-faint); font-weight: 700; margin: 0 0 10px; }
+ .toc ol { margin: 0; padding-left: 22px; columns: 2; column-gap: 36px; }
+ .toc li { margin: 5px 0; }
+ @media (max-width: 640px) { .toc ol { columns: 1; } }
+
+ /* diagrams */
+ .diagram {
+ background: var(--panel); border: 1px solid var(--border);
+ border-radius: var(--radius); padding: 18px; margin: 22px 0;
+ overflow-x: auto; text-align: center;
+ }
+ .diagram .cap {
+ text-align: center; color: var(--ink-faint); font-size: 13px;
+ margin-top: 12px; font-style: italic;
+ }
+ .mermaid { display: flex; justify-content: center; }
+
+ /* tabs */
+ .tabs { margin: 22px 0; border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; }
+ .tab-bar { display: flex; flex-wrap: wrap; background: var(--panel-2); border-bottom: 1px solid var(--border); }
+ .tab-btn {
+ appearance: none; border: 0; background: transparent; cursor: pointer;
+ color: var(--ink-dim); font-family: var(--sans); font-size: 13.5px; font-weight: 600;
+ padding: 11px 16px; border-bottom: 2px solid transparent;
+ }
+ .tab-btn:hover { color: var(--ink); }
+ .tab-btn.active { color: #fff; border-bottom-color: var(--accent); background: var(--panel); }
+ .tab-panel { display: none; }
+ .tab-panel.active { display: block; }
+ .tab-panel .filelabel {
+ font-family: var(--mono); font-size: 12px; color: var(--ink-faint);
+ padding: 9px 16px 0; background: var(--code-bg);
+ }
+
+ /* code blocks & diffs */
+ pre {
+ margin: 0; background: var(--code-bg);
+ overflow-x: auto; padding: 16px 18px;
+ font-family: var(--mono); font-size: 13px; line-height: 1.55;
+ color: #cdd2e0;
+ }
+ pre.diff { padding: 14px 0; }
+ .diff .ln { display: block; padding: 0 18px; white-space: pre; }
+ .diff .add { background: var(--add); color: var(--add-ink); }
+ .diff .del { background: var(--del); color: var(--del-ink); }
+ .diff .ctx { color: #9aa0b3; }
+ .diff .hdr { color: var(--ink-faint); }
+ .diff .meta { color: var(--accent); }
+ .standalone-code {
+ border: 1px solid var(--border); border-radius: var(--radius);
+ overflow: hidden; margin: 20px 0;
+ }
+ .standalone-code .filelabel {
+ font-family: var(--mono); font-size: 12px; color: var(--ink-faint);
+ padding: 9px 16px; background: var(--panel-2); border-bottom: 1px solid var(--border);
+ }
+
+ /* details / foldables */
+ details {
+ border: 1px solid var(--border); border-radius: var(--radius);
+ margin: 16px 0; background: var(--panel); overflow: hidden;
+ }
+ details summary {
+ cursor: pointer; padding: 14px 18px; font-weight: 600; color: var(--ink);
+ list-style: none; display: flex; align-items: center; gap: 10px;
+ user-select: none;
+ }
+ details summary::-webkit-details-marker { display: none; }
+ details summary::before {
+ content: "▶"; color: var(--accent); font-size: 11px; transition: transform .15s ease;
+ }
+ details[open] summary::before { transform: rotate(90deg); }
+ details summary:hover { background: var(--panel-2); }
+ details .body { padding: 4px 20px 18px; border-top: 1px solid var(--border); }
+ details .body > *:first-child { margin-top: 14px; }
+
+ /* tables */
+ table { border-collapse: collapse; width: 100%; margin: 20px 0; font-size: 14px; }
+ th, td { text-align: left; padding: 9px 12px; border-bottom: 1px solid var(--border); vertical-align: top; }
+ th { color: var(--ink-faint); font-size: 12px; text-transform: uppercase; letter-spacing: .06em; font-weight: 700; }
+ td code { font-size: 0.85em; }
+ tbody tr:hover { background: var(--panel); }
+
+ ul.clean { list-style: none; padding-left: 0; }
+ ul.clean li { padding-left: 26px; position: relative; margin: 9px 0; }
+ ul.clean li::before { content: "›"; position: absolute; left: 8px; color: var(--accent); font-weight: 700; }
+
+ .pill { font-family: var(--mono); font-size: 12px; padding: 1px 7px; border-radius: 5px; }
+ .pill.keep { background: rgba(90,209,154,0.13); color: var(--good); border: 1px solid rgba(90,209,154,0.3); }
+ .pill.gone { background: rgba(239,111,111,0.12); color: var(--bad); border: 1px solid rgba(239,111,111,0.3); }
+
+ footer { margin-top: 60px; padding-top: 20px; border-top: 1px solid var(--border); color: var(--ink-faint); font-size: 13px; }
+ .kbd { font-family: var(--mono); font-size: 12px; background: var(--panel-2); border: 1px solid var(--border); border-radius: 5px; padding: 1px 6px; }
+</style>
+</head>
+<body>
+
+<header class="hero">
+ <div class="hero-inner">
+ <p class="eyebrow">Refactor · pipe taxonomy</p>
+ <h1><code>PipeSignature</code> is a contract, not an executable pipe type</h1>
+ <p class="sub">We evicted <code>PipeSignature</code> from the <code>PipeType</code> / <code>PipeCategory</code> taxonomy. A signature stays a <code>PipeAbstract</code> (so the dry-run engine can still mock it), but it is no longer pretending to be a sibling of <code>PipeLLM</code> or <code>PipeSequence</code>.</p>
+ <div class="badges">
+ <span class="badge green"><span class="dot"></span>Landed</span>
+ <span class="badge"><span class="dot"></span><code>make tb</code> · <code>agent-check</code> · <code>agent-test</code> green</span>
+ <span class="badge"><span class="dot"></span>MTHDS schema: no diff</span>
+ <span class="badge"><span class="dot"></span>Breaking: <code>PipeCategory.PIPE_SIGNATURE</code> removed</span>
+ </div>
+ </div>
+</header>
+
+<div class="wrap">
+
+ <!-- TL;DR -->
+ <div class="tldr">
+ <h2>TL;DR</h2>
+ <p class="lead">A pipe <em>has</em> a signature (its contract). A <code>PipeSignature</code> is that contract <strong>alone</strong> — no body. It was a member of <code>PipeType</code>/<code>PipeCategory</code>, which framed it as a way of <em>running</em> next to <code>PipeLLM</code>/<code>PipeSequence</code>. It isn't one. We pulled it out of the executable taxonomy.</p>
+ <ul>
+ <li><strong>Removed</strong> <code>PipeType.PIPE_SIGNATURE</code> and <code>PipeCategory.PIPE_SIGNATURE</code>. The two enums now describe <em>only</em> things that execute (operator vs controller).</li>
+ <li><strong>Identity by class, not enum.</strong> <code>is_signature</code> is now a class fact — base returns <code>False</code>, <code>PipeSignature</code> / <code>PipeSignatureBlueprint</code> override to <code>True</code> — instead of reading an enum field. Every existing call site keeps working unchanged.</li>
+ <li><strong>It stays a <code>PipeAbstract</code>.</strong> The dry-run engine dispatches over <code>PipeAbstract</code>, and a signature must be dry-runnable (verify inputs, mock output). A signature carries <code>type = "PipeSignature"</code> with <code>pipe_category = None</code>.</li>
+ <li><strong>One honest allowlist.</strong> A new <code>PIPE_SIGNATURE_TYPE_TAG</code> + <code>valid_pipe_type_tags()</code> expresses "legal <code>type</code> = executable kinds ∪ the signature tag" as the single source of truth for the three validators that gate it.</li>
+ <li><strong>Breaking but tiny.</strong> Anything matching on <code>PipeCategory.PIPE_SIGNATURE</code> must drop that arm. <code>signature_for</code> is kept (mthds-plugins depends on it); its two guard validators are deleted because the rejection is now <em>structural</em>.</li>
+ <li><strong>Invisible to the wire.</strong> The blueprint union discriminates on <code>type</code> (unchanged), so the generated MTHDS JSON Schema produced <strong>no diff</strong>.</li>
+ </ul>
+ </div>
+
+ <div class="toc">
+ <p class="toc-title">Contents</p>
+ <ol>
+ <li><a href="#diagnosis">The diagnosis</a></li>
+ <li><a href="#decision">The principle</a></li>
+ <li><a href="#before-after">Before / after taxonomy</a></li>
+ <li><a href="#keystone">The keystone: identity by class</a></li>
+ <li><a href="#diffs">Critical code changes</a></li>
+ <li><a href="#runtime">Runtime behaviour</a></li>
+ <li><a href="#scope">Scope: spec layer stays put</a></li>
+ <li><a href="#kept">What we kept &amp; deferred</a></li>
+ <li><a href="#touchpoints">Touch-point index</a></li>
+ </ol>
+ </div>
+
+ <!-- DIAGNOSIS -->
+ <h2 id="diagnosis"><span class="num">1</span>The diagnosis</h2>
+ <p><code>PipeType</code> and <code>PipeCategory</code> were each doing <strong>two jobs</strong>:</p>
+ <ul class="clean">
+ <li><strong>Job 1 — parse-time allowlist.</strong> "Is this <code>type</code> legal under <code>[pipe.X]</code>?" (<code>value in PipeType.value_list()</code>, in three validators.)</li>
+ <li><strong>Job 2 — executable taxonomy.</strong> <code>PipeType.category</code> → operator vs controller; the orchestration role.</li>
+ </ul>
+ <p>A signature only needs Job 1 — <code>type = "PipeSignature"</code> is a real thing you write. But the <em>only</em> way to clear the allowlist was to join the enum, which <strong>forced</strong> a <code>.category</code> and dragged it into Job 2 as a peer of the real kinds. <code>PipeCategory.PIPE_SIGNATURE</code> was the scar.</p>
+
+ <div class="diagram">
+ <div class="mermaid">
+flowchart TB
+ SIG["PipeSignature<br/><span>type = 'PipeSignature' is a real tag</span>"]:::sig
+ SIG -->|"only needs"| J1
+ SIG -.->|"forced side effect"| J2
+
+ subgraph OVER["One enum, two jobs (overloaded)"]
+ direction TB
+ J1["JOB 1 — parse-time allowlist<br/>is this 'type' legal under [pipe.X]?"]:::ok
+ J2["JOB 2 — executable taxonomy<br/>operator vs controller · how it runs"]:::bad
+ end
+
+ J2 --> SCAR["PipeCategory.PIPE_SIGNATURE<br/>peer of OPERATOR / CONTROLLER<br/>— the scar"]:::scar
+
+ classDef sig fill:#1d2740,stroke:#7aa2ff,color:#dbe3ff;
+ classDef ok fill:#16271f,stroke:#5ad19a,color:#bdeed4;
+ classDef bad fill:#2a1d24,stroke:#ef6f6f,color:#f3c4c4;
+ classDef scar fill:#2a1d24,stroke:#ef6f6f,color:#f3c4c4,stroke-dasharray: 4 3;
+ </div>
+ <div class="cap">A signature only ever needed Job 1. Joining the enum to clear it dragged it into Job 2.</div>
+ </div>
+
+ <p><strong>The fix separates the two jobs:</strong> the allowlist becomes "executable kinds ∪ the signature tag"; the enums shrink back to executable kinds only. As a bonus, <code>PipeType.category</code> is a <em>total</em> function again — its <code>match</code> is cleanly exhaustive over <code>{OPERATOR, CONTROLLER}</code>.</p>
+
+ <!-- DECISION -->
+ <h2 id="decision"><span class="num">2</span>The principle</h2>
+ <p><code>PipeSignature</code> stays a <code>PipeAbstract</code> subclass (the dry-run engine dispatches over <code>PipeAbstract</code>, and a signature must be dry-runnable) — but it leaves the executable taxonomy.</p>
+
+ <div class="principle">
+ <p class="label">The four rules</p>
+ <ul style="margin:6px 0 0; padding-left:18px">
+ <li><strong><code>PipeAbstract</code> = the substrate.</strong> A contract-bearing graph node: <code>inputs</code> / <code>output</code> / <code>description</code>, dry-runnable. A <code>PipeSignature</code> is that substrate with <em>nothing added</em>. It stays here.</li>
+ <li><strong><code>PipeType</code> / <code>PipeCategory</code> = the executable taxonomy.</strong> How a pipe runs and whether it orchestrates. A signature does not run → it is in <strong>neither</strong>.</li>
+ <li><strong>Identity by class, not by enum field.</strong> <code>is_signature</code> is the keystone — it stops reading <code>pipe_category</code> and becomes a class fact.</li>
+ <li><strong>The runtime <code>PipeSignature</code> is a dry-run shim</strong> of a blueprint-layer contract. Live-run always errors; dry-run mocks the declared output, and only under <code>--allow-signatures</code>.</li>
+ </ul>
+ </div>
+
+ <!-- BEFORE/AFTER -->
+ <h2 id="before-after"><span class="num">3</span>Before / after taxonomy</h2>
+ <div class="diagram">
+ <div class="mermaid">
+flowchart LR
+ subgraph B["BEFORE — signature is a peer kind"]
+ direction TB
+ BC["PipeCategory"]:::cat
+ BC --> BO["PIPE_OPERATOR"]:::ok
+ BC --> BCo["PIPE_CONTROLLER"]:::ok
+ BC --> BS["PIPE_SIGNATURE"]:::bad
+ BT["PipeType"]:::cat
+ BT --> BTo["PipeLLM, PipeExtract, …"]:::ok
+ BT --> BTc["PipeSequence, PipeBatch, …"]:::ok
+ BT --> BTs["PipeSignature"]:::bad
+ end
+ classDef cat fill:#1d2740,stroke:#7aa2ff,color:#dbe3ff,font-weight:bold;
+ classDef ok fill:#16271f,stroke:#3f7a5f,color:#bdeed4;
+ classDef bad fill:#2a1d24,stroke:#ef6f6f,color:#f3c4c4;
+ </div>
+ <div class="mermaid">
+flowchart LR
+ subgraph A["AFTER — executable taxonomy (the only members)"]
+ direction TB
+ AC["PipeCategory"]:::cat
+ AC --> AO["PIPE_OPERATOR"]:::ok
+ AC --> ACo["PIPE_CONTROLLER"]:::ok
+ AT["PipeType"]:::cat
+ AT --> ATo["PipeLLM, PipeExtract, …"]:::ok
+ AT --> ATc["PipeSequence, PipeBatch, …"]:::ok
+ end
+ subgraph OUT["Outside · tolerated by the allowlist"]
+ direction TB
+ SIG["PipeSignature<br/>type = allowlist tag<br/>pipe_category = None<br/>is_signature = True (by class)"]:::sig
+ end
+ classDef cat fill:#1d2740,stroke:#7aa2ff,color:#dbe3ff,font-weight:bold;
+ classDef ok fill:#16271f,stroke:#3f7a5f,color:#bdeed4;
+ classDef sig fill:#1d2b2a,stroke:#5ad1b3,color:#bff0e4;
+ </div>
+ <div class="cap">The signature stops being a <em>member</em> of the taxonomy and becomes an outsider the allowlist tolerates.</div>
+ </div>
+
+ <table>
+ <thead><tr><th>Aspect</th><th>Before</th><th>After</th></tr></thead>
+ <tbody>
+ <tr><td><code>PipeType</code> membership</td><td><span class="pill gone">PIPE_SIGNATURE</span> present</td><td>executable kinds only</td></tr>
+ <tr><td><code>PipeCategory</code> membership</td><td><span class="pill gone">PIPE_SIGNATURE</span> present</td><td><code>PIPE_OPERATOR</code>, <code>PIPE_CONTROLLER</code></td></tr>
+ <tr><td>signature <code>type</code></td><td><code>"PipeSignature"</code> (a <code>PipeType</code>)</td><td><code>"PipeSignature"</code> (allowlist tag only)</td></tr>
+ <tr><td>signature <code>pipe_category</code></td><td><code>"PipeSignature"</code></td><td><code>None</code></td></tr>
+ <tr><td><code>is_signature</code></td><td><code>PipeCategory(self.pipe_category) is …PIPE_SIGNATURE</code></td><td>class fact: base <code>False</code>, override <code>True</code></td></tr>
+ <tr><td><code>PipeType.category</code></td><td>partial (signature arm → non-exec category)</td><td>total over <code>{OPERATOR, CONTROLLER}</code></td></tr>
+ <tr><td><code>signature_for</code> guard</td><td>dedicated <code>reject_…</code> validator ×2</td><td>structural (not a valid <code>PipeType</code>)</td></tr>
+ </tbody>
+ </table>
+
+ <!-- KEYSTONE -->
+ <h2 id="keystone"><span class="num">4</span>The keystone: identity by class</h2>
+ <p>Everything hinges on one property moving from "read an enum field" to "ask the class." Because every existing call site already calls <code>is_signature</code>, swapping its <em>implementation</em> propagates the new model everywhere for free.</p>
+
+ <div class="diagram">
+ <div class="mermaid">
+classDiagram
+ class PipeAbstract {
+ +is_signature() bool
+ }
+ class PipeBlueprint {
+ +is_signature() bool
+ }
+ class PipeSignature {
+ +is_signature() bool
+ +pipe_category None
+ }
+ class PipeSignatureBlueprint {
+ +is_signature() bool
+ +pipe_category None
+ }
+ PipeAbstract <|-- PipeSignature : override True
+ PipeAbstract <|-- PipeLLM : inherits False
+ PipeAbstract <|-- PipeSequence : inherits False
+ PipeBlueprint <|-- PipeSignatureBlueprint : override True
+ </div>
+ <div class="cap">The base says "not a signature"; only the signature classes say otherwise. No enum is consulted.</div>
+ </div>
+
+ <div class="standalone-code">
+ <div class="filelabel">pipelex/core/pipes/pipe_abstract.py — the keystone diff</div>
+ <pre class="diff"><span class="ln ctx"> @property</span>
+<span class="ln ctx"> def is_signature(self) -> bool:</span>
+<span class="ln del">- return PipeCategory(self.pipe_category) is PipeCategory.PIPE_SIGNATURE</span>
+<span class="ln add">+ # Identity by class, not by enum field: the base is never a signature;</span>
+<span class="ln add">+ # `PipeSignature` overrides this to True. (`pipe_category` no longer encodes signature-ness.)</span>
+<span class="ln add">+ return False</span></pre>
+ </div>
+ <div class="standalone-code">
+ <div class="filelabel">pipelex/pipe_signature/pipe_signature.py — the override</div>
+ <pre class="diff"><span class="ln add">+ @property</span>
+<span class="ln add">+ @override</span>
+<span class="ln add">+ def is_signature(self) -> bool:</span>
+<span class="ln add">+ return True</span></pre>
+ </div>
+ <p>Same pair on <code>PipeBlueprint</code> (base <code>False</code>) and <code>PipeSignatureBlueprint</code> (override <code>True</code>).</p>
+
+ <!-- DIFFS -->
+ <h2 id="diffs"><span class="num">5</span>Critical code changes</h2>
+
+ <div class="tabs" id="difftabs">
+ <div class="tab-bar">
+ <button class="tab-btn active" data-tab="t-enums">Shrink the enums</button>
+ <button class="tab-btn" data-tab="t-allow">Honest allowlist</button>
+ <button class="tab-btn" data-tab="t-valid">Tolerant validators</button>
+ <button class="tab-btn" data-tab="t-factory">Factory branch</button>
+ <button class="tab-btn" data-tab="t-cat">pipe_category → None</button>
+ <button class="tab-btn" data-tab="t-guards">Delete guards</button>
+ </div>
+
+ <div class="tab-panel active" id="t-enums">
+ <div class="filelabel">pipelex/core/pipes/pipe_blueprint.py</div>
+ <pre class="diff"><span class="ln ctx"> class PipeCategory(StrEnum):</span>
+<span class="ln ctx"> PIPE_OPERATOR = "PipeOperator"</span>
+<span class="ln ctx"> PIPE_CONTROLLER = "PipeController"</span>
+<span class="ln del">- PIPE_SIGNATURE = "PipeSignature"</span>
+<span class="ln ctx"> </span>
+<span class="ln ctx"> @property</span>
+<span class="ln ctx"> def is_controller(self) -> bool:</span>
+<span class="ln ctx"> match self:</span>
+<span class="ln ctx"> case PipeCategory.PIPE_CONTROLLER:</span>
+<span class="ln ctx"> return True</span>
+<span class="ln del">- case PipeCategory.PIPE_OPERATOR | PipeCategory.PIPE_SIGNATURE:</span>
+<span class="ln add">+ case PipeCategory.PIPE_OPERATOR:</span>
+<span class="ln ctx"> return False</span>
+<span class="ln ctx"> </span>
+<span class="ln ctx"> class PipeType(StrEnum):</span>
+<span class="ln ctx"> ...</span>
+<span class="ln ctx"> PIPE_SEQUENCE = "PipeSequence"</span>
+<span class="ln del">- PIPE_SIGNATURE = "PipeSignature"</span>
+<span class="ln ctx"> </span>
+<span class="ln ctx"> @property</span>
+<span class="ln ctx"> def category(self) -> PipeCategory:</span>
+<span class="ln ctx"> match self:</span>
+<span class="ln ctx"> ...</span>
+<span class="ln ctx"> case PipeType.PIPE_SEQUENCE:</span>
+<span class="ln ctx"> return PipeCategory.PIPE_CONTROLLER</span>
+<span class="ln del">- case PipeType.PIPE_SIGNATURE:</span>
+<span class="ln del">- return PipeCategory.PIPE_SIGNATURE</span></pre>
+ <p style="padding:0 4px 4px; color:var(--ink-dim); font-size:14px">Both <code>match</code> blocks stay exhaustive — now over the two executable values. <code>.category</code> is once again total.</p>
+ </div>
+
+ <div class="tab-panel" id="t-allow">
+ <div class="filelabel">pipelex/core/pipes/pipe_blueprint.py — new single source of truth</div>
+ <pre class="diff"><span class="ln add">+# A signature is NOT an executable pipe kind: it is deliberately absent from `PipeType` and</span>
+<span class="ln add">+# `PipeCategory`. This is the one extra `type` tag the parse-time allowlists admit beyond the</span>
+<span class="ln add">+# executable kinds (a signature blueprint carries `type = "PipeSignature"`, `pipe_category = None`).</span>
+<span class="ln add">+PIPE_SIGNATURE_TYPE_TAG = "PipeSignature"</span>
+<span class="ln add">+</span>
+<span class="ln add">+def valid_pipe_type_tags() -> list[str]:</span>
+<span class="ln add">+ """Every legal `type` string under `[pipe.X]`: the executable `PipeType` kinds plus the</span>
+<span class="ln add">+ signature tag. Single source of truth for the three layers (`PipeBlueprint`,</span>
+<span class="ln add">+ `PipeAbstract`, `PipeSpec`) that gate it."""</span>
+<span class="ln add">+ return [*PipeType.value_list(), PIPE_SIGNATURE_TYPE_TAG]</span></pre>
+ <p style="padding:0 4px 4px; color:var(--ink-dim); font-size:14px">A bare module-level string — <em>not</em> an import of <code>PipeSignatureBlueprint</code> into the base module (that would be a cycle). All three validators now read <code>valid_pipe_type_tags()</code> and list the tag in their error messages, so it shows up as a legal value.</p>
+ </div>
+
+ <div class="tab-panel" id="t-valid">
+ <div class="filelabel">pipelex/core/pipes/pipe_blueprint.py &amp; pipe_abstract.py — shared validators (same shape on both)</div>
+ <pre class="diff"><span class="ln ctx"> @field_validator("type", mode="after")</span>
+<span class="ln ctx"> def validate_pipe_type(cls, value: Any) -> Any:</span>
+<span class="ln del">- if value not in PipeType.value_list():</span>
+<span class="ln del">- msg = f"Invalid pipe type '{value}'. Must be one of: {PipeType.value_list()}"</span>
+<span class="ln add">+ allowed = valid_pipe_type_tags()</span>
+<span class="ln add">+ if value not in allowed:</span>
+<span class="ln add">+ msg = f"Invalid pipe type '{value}'. Must be one of: {allowed}"</span>
+<span class="ln ctx"> raise ValueError(msg)</span>
+<span class="ln ctx"> </span>
+<span class="ln ctx"> @field_validator("pipe_category", mode="after")</span>
+<span class="ln ctx"> def validate_pipe_category(cls, value: Any) -> Any:</span>
+<span class="ln del">- if value not in PipeCategory.value_list():</span>
+<span class="ln add">+ # `None` unambiguously means "signature"; every executable pipe pins a Literal.</span>
+<span class="ln add">+ if value is not None and value not in PipeCategory.value_list():</span>
+<span class="ln ctx"> raise ValueError(...)</span>
+<span class="ln ctx"> </span>
+<span class="ln ctx"> @model_validator(mode="after")</span>
+<span class="ln ctx"> def validate_pipe_category_based_on_type(self) -> Self:</span>
+<span class="ln add">+ if self.is_signature:</span>
+<span class="ln add">+ # Outside the executable taxonomy: skip the type↔category consistency check</span>
+<span class="ln add">+ # that would coerce `PipeType(self.type)` and raise.</span>
+<span class="ln add">+ return self</span>
+<span class="ln ctx"> pipe_type = PipeType(self.type) # was unconditional</span>
+<span class="ln ctx"> ...</span></pre>
+ <p style="padding:0 4px 4px; color:var(--ink-dim); font-size:14px">Three small allowances: admit the tag, admit <code>None</code> category, early-return for signatures before the coercion. <code>is_signature</code> is class-based, so it's reliable at model-validation time.</p>
+ </div>
+
+ <div class="tab-panel" id="t-factory">
+ <div class="filelabel">pipelex/core/pipes/pipe_factory.py</div>
+ <pre class="diff"><span class="ln del">- pipe_type = PipeType(blueprint.type)</span>
+<span class="ln del">- pipe_category = pipe_type.category</span>
+<span class="ln del">- factory_class_name = f"{pipe_type.value}Factory"</span>
+<span class="ln add">+ # A signature is outside the executable taxonomy: its `type` is not a `PipeType`</span>
+<span class="ln add">+ # member and it has no category, so resolve the factory by name and skip the coercion.</span>
+<span class="ln add">+ pipe_category: PipeCategory | None</span>
+<span class="ln add">+ if blueprint.is_signature:</span>
+<span class="ln add">+ pipe_category = None</span>
+<span class="ln add">+ factory_class_name = f"{blueprint.type}Factory" # "PipeSignatureFactory"</span>
+<span class="ln add">+ else:</span>
+<span class="ln add">+ pipe_type = PipeType(blueprint.type)</span>
+<span class="ln add">+ pipe_category = pipe_type.category</span>
+<span class="ln add">+ factory_class_name = f"{pipe_type.value}Factory"</span></pre>
+ <p style="padding:0 4px 4px; color:var(--ink-dim); font-size:14px">Resolve the factory by name from the string tag — no <code>PipeSignatureFactory</code> import → no cycle. The existing class-registry lookup downstream is unchanged.</p>
+ </div>
+
+ <div class="tab-panel" id="t-cat">
+ <div class="filelabel">pipelex/pipe_signature/pipe_signature.py &amp; pipe_signature_blueprint.py</div>
+ <pre class="diff"><span class="ln hdr"># runtime</span>
+<span class="ln ctx"> type: Literal["PipeSignature"] = "PipeSignature"</span>
+<span class="ln del">-pipe_category: Literal["PipeSignature"] = "PipeSignature"</span>
+<span class="ln add">+pipe_category: None = None</span>
+<span class="ln ctx"></span>
+<span class="ln hdr"># blueprint</span>
+<span class="ln ctx"> type: Literal["PipeSignature"] = "PipeSignature"</span>
+<span class="ln del">-pipe_category: Literal["PipeSignature"] = "PipeSignature"</span>
+<span class="ln add">+# Keep exclude=True — overriding the field type drops the base's Field(exclude=True)</span>
+<span class="ln add">+# unless re-specified, so it never serializes into `.mthds`.</span>
+<span class="ln add">+pipe_category: None = Field(default=None, exclude=True)</span></pre>
+ <p style="padding:0 4px 4px; color:var(--ink-dim); font-size:14px"><code>type</code> stays the discriminator. The union discriminates on <code>type</code>, not <code>pipe_category</code>, so <code>None</code> is invisible to parsing — and why the MTHDS schema didn't change.</p>
+ </div>
+
+ <div class="tab-panel" id="t-guards">
+ <div class="filelabel">pipe_signature_blueprint.py &amp; builder/pipe/pipe_signature_spec.py — both guards deleted</div>
+ <pre class="diff"><span class="ln del">- @field_validator("signature_for", mode="after")</span>
+<span class="ln del">- @classmethod</span>
+<span class="ln del">- def reject_signature_for_pipe_signature(cls, value: PipeType | None) -> PipeType | None:</span>
+<span class="ln del">- if value is PipeType.PIPE_SIGNATURE: # ← this enum member no longer exists</span>
+<span class="ln del">- msg = "A PipeSignature cannot have signature_for=PipeSignature."</span>
+<span class="ln del">- raise ValueError(msg)</span>
+<span class="ln del">- return value</span></pre>
+ <p style="padding:0 4px 4px; color:var(--ink-dim); font-size:14px">These referenced <code>PipeType.PIPE_SIGNATURE</code> — they would now <code>AttributeError</code> on every signature parse. Their intent is preserved <strong>structurally</strong>: <code>signature_for: PipeType | None</code> can no longer coerce <code>"PipeSignature"</code>, so Pydantic rejects it on its own with a clean error.</p>
+ </div>
+ </div>
+
+ <!-- RUNTIME -->
+ <h2 id="runtime"><span class="num">6</span>Runtime behaviour</h2>
+ <p>The runtime <code>PipeSignature</code> is a dry-run shim — fully determined by the contract, no body.</p>
+ <div class="diagram">
+ <div class="mermaid">
+flowchart TD
+ START["run_pipe() on a PipeSignature"]:::n --> MODE{run mode?}
+ MODE -->|LIVE| LIVE["validate_before_run sees is_signature + is_live<br/>→ raise PipeSignatureNotExecutableError"]:::bad
+ MODE -->|DRY| ALLOW{--allow-signatures?}
+ ALLOW -->|no| STRICT["strict validation refuses<br/>the pipeline depends on a signature"]:::bad
+ ALLOW -->|yes| MOCK["mint a mock output from the declared StuffSpec<br/>set_new_main_stuff → PipeOutput"]:::good
+ classDef n fill:#1d2740,stroke:#7aa2ff,color:#dbe3ff;
+ classDef bad fill:#2a1d24,stroke:#ef6f6f,color:#f3c4c4;
+ classDef good fill:#16271f,stroke:#5ad19a,color:#bdeed4;
+ </div>
+ <div class="cap">Live execution is always an error; dry-run mocks the declared output, gated on <code>--allow-signatures</code>.</div>
+ </div>
+
+ <details>
+ <summary>The <code>output_renderer</code> short-circuit</summary>
+ <div class="body">
+ <p><code>_collect_possible_outputs</code> used to coerce <code>PipeType(the_pipe.type)</code> unconditionally and listed <code>PipeType.PIPE_SIGNATURE</code> in its match. Both break once the enum member is gone, so we early-return before the coercion:</p>
+ <pre class="diff"><span class="ln add">+ if the_pipe.is_signature:</span>
+<span class="ln add">+ # Outside the `PipeType` taxonomy; contributes no concrete output options.</span>
+<span class="ln add">+ # Short-circuit before the `PipeType(...)` coercion, which would raise.</span>
+<span class="ln add">+ return []</span>
+<span class="ln ctx"> pipe_type = PipeType(the_pipe.type)</span>
+<span class="ln ctx"> ...</span>
+<span class="ln ctx"> | PipeType.PIPE_BATCH</span>
+<span class="ln ctx"> | PipeType.PIPE_PARALLEL</span>
+<span class="ln del">- | PipeType.PIPE_SIGNATURE</span>
+<span class="ln ctx"> ):</span>
+<span class="ln ctx"> return []</span></pre>
+ </div>
+ </details>
+
+ <details>
+ <summary>A welcome side effect — the headline feature reads truer</summary>
+ <div class="body">
+ <p><code>library_crate_factory._reconcile_pipe_collision</code> keys off <code>blueprint.is_signature</code>. After this change that means <strong>"a contract is fulfilled by an implementation,"</strong> not "swap pipe-type <code>PipeSignature</code> for pipe-type <code>PipeLLM</code>." <code>contract_match.contracts_match()</code> is untouched — the reconciliation logic didn't move, only the concept it expresses got honest.</p>
+ </div>
+ </details>
+
+ <!-- SCOPE -->
+ <h2 id="scope"><span class="num">7</span>Scope: the spec layer stays put</h2>
+ <p>The taxonomy correction lands at the <strong>blueprint + runtime</strong> layers. <code>../mthds-plugins</code> authors against the <strong>spec</strong> layer (<code>PipeSignatureSpec</code>), so that surface is left stable: it keeps its <code>type</code> / <code>pipe_category = "PipeSignature"</code> string literals as display tags (not typed as <code>PipeCategory</code>, and <code>to_blueprint()</code> never propagates them). The only spec edit was widening <code>PipeSpec.validate_pipe_type</code> via the same <code>valid_pipe_type_tags()</code> and dropping the broken <code>signature_for</code> guard.</p>
+ <div class="note">
+ <p class="label">Why the spec can keep a tag the blueprint drops</p>
+ <p style="margin:0">Blueprints are the MTHDS language reference (what <code>.mthds</code> parses into); specs are an authoring format for agents, each with a <code>to_blueprint()</code>. Spec fields may legitimately differ from blueprint fields — so a cosmetic <code>pipe_category</code> string on the spec is fine.</p>
+ </div>
+
+ <!-- KEPT -->
+ <h2 id="kept"><span class="num">8</span>What we kept &amp; what we deferred</h2>
+ <table>
+ <thead><tr><th>Item</th><th>Status</th><th>Why</th></tr></thead>
+ <tbody>
+ <tr><td><code>PipeSignature(PipeAbstract)</code></td><td><span class="pill keep">kept</span></td><td>Dry-run engine dispatches over <code>PipeAbstract</code>; a signature must be dry-runnable.</td></tr>
+ <tr><td><code>signature_for: PipeType | None</code></td><td><span class="pill keep">kept</span></td><td>Consumed by mthds-plugins. An advisory implementor hint; rejection of <code>"PipeSignature"</code> is now structural.</td></tr>
+ <tr><td><code>PIPE_SIGNATURES</code> registry group</td><td><span class="pill keep">kept</span></td><td>Its own registry group reinforces "not an operator/controller."</td></tr>
+ <tr><td><code>reject_signature_for_pipe_signature</code> ×2</td><td><span class="pill gone">deleted</span></td><td>Referenced the removed enum member; intent now enforced by the type.</td></tr>
+ <tr><td>Class-based <code>is_controller</code> (Step 1b)</td><td><span class="pill keep">deferred</span></td><td>Optional cleanliness, not correctness — see below.</td></tr>
+ <tr><td>Retire <code>signature_for</code> entirely</td><td><span class="pill keep">future</span></td><td>Once mthds-plugins no longer depends on it; likely fold the hint into <code>description</code>.</td></tr>
+ <tr><td>Derive <code>pipe_category</code> instead of storing</td><td><span class="pill keep">future</span></td><td>It must equal <code>PipeType(type).category</code> for executables and is <code>None</code> for signatures — redundant, could be computed.</td></tr>
+ </tbody>
+ </table>
+
+ <details>
+ <summary>Why <code>is_controller</code> was <em>not</em> converted to a class fact (deliberate)</summary>
+ <div class="body">
+ <p>We left <code>is_controller</code> reading the enum — it's <strong>cleanliness, not correctness</strong>, and converting it would do more harm:</p>
+ <ul class="clean">
+ <li>It already returns the right answer for a signature: <code>pipe_category</code> is <code>None</code>, <code>PipeCategory(None)</code> raises <code>ValueError</code>, and <code>is_controller_by_str</code>'s <code>except → False</code> handles it.</li>
+ <li>A class-based override would orphan <code>PipeCategory.is_controller</code> / <code>is_controller_by_str</code> into dead code (their only caller is <code>PipeAbstract.is_controller</code>).</li>
+ </ul>
+ <p>Revisit only if <code>is_controller</code> ever needs to stop touching <code>pipe_category</code> for another reason.</p>
+ </div>
+ </details>
+
+ <!-- TOUCHPOINTS -->
+ <h2 id="touchpoints"><span class="num">9</span>Touch-point index</h2>
+ <table>
+ <thead><tr><th>File</th><th>What changed</th></tr></thead>
+ <tbody>
+ <tr><td><code>core/pipes/pipe_blueprint.py</code></td><td>shrink both enums; add <code>PIPE_SIGNATURE_TYPE_TAG</code> + <code>valid_pipe_type_tags()</code>; <code>is_signature</code> → <code>False</code>; widen validators; early-return</td></tr>
+ <tr><td><code>core/pipes/pipe_abstract.py</code></td><td><code>is_signature</code> → <code>False</code> base; same validator widening</td></tr>
+ <tr><td><code>pipe_signature/pipe_signature.py</code></td><td><code>pipe_category: None = None</code>; <code>is_signature</code> override → <code>True</code></td></tr>
+ <tr><td><code>pipe_signature/pipe_signature_blueprint.py</code></td><td><code>pipe_category: None = Field(default=None, exclude=True)</code>; override → <code>True</code>; delete guard</td></tr>
+ <tr><td><code>core/pipes/pipe_factory.py</code></td><td>branch on <code>is_signature</code> around the <code>PipeType</code> coercion</td></tr>
+ <tr><td><code>core/pipes/output/output_renderer.py</code></td><td>early <code>is_signature</code> return; drop <code>PIPE_SIGNATURE</code> match arm</td></tr>
+ <tr><td><code>builder/pipe/pipe_spec.py</code></td><td>widen <code>validate_pipe_type</code> via <code>valid_pipe_type_tags()</code></td></tr>
+ <tr><td><code>builder/pipe/pipe_signature_spec.py</code></td><td>delete guard; soften docstring; keep tags + <code>signature_for</code></td></tr>
+ <tr><td><code>cli/agent_cli/commands/pipe_cmd.py</code></td><td><code>--type</code> help now lists <code>pipe_type_to_spec_class</code> keys, not <code>PipeType.value_list()</code></td></tr>
+ <tr><td><code>derived/mthds_schema.json</code></td><td>regenerated — <strong>no diff</strong></td></tr>
+ <tr><td>tests · docs · CHANGELOG · TODOS</td><td>updated to the new model (enum eviction locked in; surface reframed)</td></tr>
+ </tbody>
+ </table>
+
+ <details>
+ <summary>How the tests were updated</summary>
+ <div class="body">
+ <ul class="clean">
+ <li><code>test_pipe_blueprint_signature_enums.py</code> now locks in the eviction: members removed, tag not in either enum, coercion raises.</li>
+ <li><code>test_pipe_abstract_signature_surface.py</code> asserts the base descriptor returns <code>False</code> even for a stub whose <code>pipe_category == "PipeSignature"</code> — proving identity is class-based, not field-based.</li>
+ <li><code>test_pipe_signature.py</code> asserts <code>type == "PipeSignature"</code> and <code>pipe_category is None</code>.</li>
+ <li>Signature-rejection tests now pass the raw string <code>"PipeSignature"</code> and assert a plain Pydantic <code>ValidationError</code> (structural), not the old custom message.</li>
+ </ul>
+ </div>
+ </details>
+
+ <footer>
+ <p>Status: landed on <code>refactor/Pipe-signature</code> · gates green (<span class="kbd">make tb</span> · <span class="kbd">agent-check</span> · <span class="kbd">agent-test</span>) · MTHDS schema regeneration produced no diff. Companion to the additive multi-file libraries work.</p>
+ </footer>
+
+</div>
+
+<script>
+ // Tabs
+ document.querySelectorAll('.tabs').forEach(function (tabs) {
+ var btns = tabs.querySelectorAll('.tab-btn');
+ var panels = tabs.querySelectorAll('.tab-panel');
+ btns.forEach(function (btn) {
+ btn.addEventListener('click', function () {
+ btns.forEach(function (b) { b.classList.remove('active'); });
+ panels.forEach(function (p) { p.classList.remove('active'); });
+ btn.classList.add('active');
+ var panel = tabs.querySelector('#' + btn.dataset.tab);
+ if (panel) panel.classList.add('active');
+ });
+ });
+ });
+
+ // Mermaid
+ mermaid.initialize({
+ startOnLoad: true,
+ theme: 'dark',
+ themeVariables: {
+ background: '#171a23',
+ primaryColor: '#1d2740',
+ primaryTextColor: '#e6e8ee',
+ primaryBorderColor: '#2a2f3d',
+ lineColor: '#717789',
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
+ fontSize: '14px'
+ },
+ flowchart: { curve: 'basis', htmlLabels: true },
+ securityLevel: 'loose'
+ });
+</script>
+</body>
+</html>
diff --git a/wip/recursivity/signature-taxonomy-refactor.md b/wip/recursivity/signature-taxonomy-refactor.md
new file mode 100644
index 000000000..a2ad537d8
--- /dev/null
+++ b/wip/recursivity/signature-taxonomy-refactor.md
@@ -0,0 +1,215 @@
+# Refactor: `PipeSignature` is a blueprint-layer contract, not an executable pipe type
+
+> **Status:** ✅ implemented. Raised by review of the additive-multi-file PR: *"I disagree that it's a new type of pipe. Pipe signatures are a substrate of the `PipeAbstract`. Each pipe has a pipe signature."* This plan implemented the agreed reconciliation. All gates green (`make tb`, `make agent-check`, `make agent-test`); MTHDS schema regeneration produced **no diff** (the eviction is invisible to the generated schema — `pipe_category` is stripped from pipe defs and `type` is unchanged). **Step 1b (class-based `is_controller`) was deliberately skipped** — see [As-built notes](#as-built-notes).
+
+## The decision
+
+Keep `PipeSignature(PipeAbstract)` — it stays a `PipeAbstract` subclass, because the dry-run engine dispatches over `PipeAbstract` and a signature must be dry-runnable (verify inputs, mock output). But **evict it from the executable-kind taxonomy**: remove `PipeSignature` from the `PipeType` and `PipeCategory` enums, and identify "is this a signature?" by class, not by an enum field.
+
+`signature_for: PipeType | None` **stays as a field** for now (it is consumed by `../mthds-plugins` and we don't want to break that). Its two `reject_signature_for_pipe_signature` guard validators are **deleted** — see [the forced interaction](#the-signature_for-interaction) below.
+
+This is **not** the "Option A" collapse (a `signature = true` flag on a real operator type, optional bodies on `PipeLLM`, etc.). That was explicitly rejected: a signature is a contract that stands on its own, **not** a pending/incomplete version of a concrete pipe.
+
+## The diagnosis (why it ended up looking like a pipe type)
+
+`PipeType` and `PipeCategory` each silently do **two jobs**:
+
+1. A **parse-time allowlist** — "is this `type` string legal under `[pipe.X]`?" (`PipeBlueprint.validate_pipe_type`, `PipeAbstract.validate_pipe_type`, `PipeSpec.validate_pipe_type`, all checking `value in PipeType.value_list()`).
+2. The **executable-kind / orchestration-role taxonomy** — `PipeType.category` → operator vs controller; `PipeCategory.is_controller`.
+
+A signature legitimately belongs in job (1): `type = "PipeSignature"` is a real thing you write in a bundle. But the only way to clear that allowlist was to also become a `PipeType` member — which **forced** it to claim a `.category`, which dragged it into job (2) as a sibling of `PipeLLM`/`PipeSequence`. `PipeCategory.PIPE_SIGNATURE` (a peer of `PIPE_OPERATOR`/`PIPE_CONTROLLER`) is the visible scar. The fix separates the two jobs: the allowlist becomes "executable kinds ∪ the signature tag"; the taxonomy enums shrink back to executable kinds only.
+
+## The principle
+
+- **`PipeAbstract` = the substrate** (contract-bearing graph node: `inputs` / `output` / `description`, dry-runnable). A `PipeSignature` is that substrate with nothing added. It stays here. *(This is exactly the co-dev's "substrate of `PipeAbstract`".)*
+- **`PipeType` / `PipeCategory` = the executable taxonomy** (how a pipe runs and whether it orchestrates). A signature does not run, so it is in **neither**.
+- **Identity by class, not by enum field.** `is_signature` becomes a class fact (base returns `False`; `PipeSignature` / `PipeSignatureBlueprint` override to `True`), so it no longer reads `pipe_category`. Every existing `is_signature` call site keeps working unchanged — that property is the keystone.
+- **The runtime `PipeSignature` is the dry-run shim of a blueprint-layer contract.** Fully determined by the contract; carries no body. Live-run always errors; dry-run mocks, and only under `--allow-signatures`.
+
+## Scope decision: the spec layer stays put
+
+`../mthds-plugins` authors against the **spec** layer (`PipeSignatureSpec`, including `signature_for`). To keep that external surface stable, the spec layer keeps its `type = "PipeSignature"` and `pipe_category = "PipeSignature"` string literals — they are display/authoring tags, they are **not** typed as `PipeCategory`, and `PipeSignatureSpec.to_blueprint()` does not propagate `pipe_category` into the blueprint anyway. The only required spec-layer edits are: widen `PipeSpec.validate_pipe_type` to admit the signature tag, and delete the now-broken `signature_for` guard. The taxonomy correction lands at the **blueprint + runtime** layers, where it belongs.
+
+---
+
+## Implementation steps
+
+### Step 1 — Keystone: `is_signature` by class
+
+`pipelex/core/pipes/pipe_abstract.py` — replace the enum-based property (currently `return PipeCategory(self.pipe_category) is PipeCategory.PIPE_SIGNATURE`, lines 71-73) with a base that returns `False`:
+
+```python
+@property
+def is_signature(self) -> bool:
+ return False
+```
+
+`pipelex/pipe_signature/pipe_signature.py` — add the override:
+
+```python
+@property
+@override
+def is_signature(self) -> bool:
+ return True
+```
+
+`pipelex/core/pipes/pipe_blueprint.py` — same on `PipeBlueprint` (lines 107-109 → `return False`).
+`pipelex/pipe_signature/pipe_signature_blueprint.py` — add the `is_signature → True` override.
+
+**Step 1b (recommended, same principle, optional):** convert `PipeAbstract.is_controller` (lines 67-69) the same way — base `return False`, `PipeController` overrides `return True` — so `is_controller` also stops reading `pipe_category`. Without this, `is_controller` still works for a signature (it calls `PipeCategory.is_controller_by_str(None)`, which hits `except ValueError → False`), so 1b is cleanliness, not correctness. Do it unless we want the smallest possible diff.
+
+### Step 2 — Shrink the enums
+
+`pipelex/core/pipes/pipe_blueprint.py`:
+
+- `PipeCategory`: delete `PIPE_SIGNATURE = "PipeSignature"` (line 16). In `is_controller` (the match), drop `PipeCategory.PIPE_SIGNATURE` from the `case PipeCategory.PIPE_OPERATOR | PipeCategory.PIPE_SIGNATURE:` arm → `case PipeCategory.PIPE_OPERATOR:`. Still exhaustive over `{OPERATOR, CONTROLLER}`.
+- `PipeType`: delete `PIPE_SIGNATURE = "PipeSignature"` (line 54). In `.category`, delete the `case PipeType.PIPE_SIGNATURE: return PipeCategory.PIPE_SIGNATURE` arm (lines 85-86). `.category` is now a **total** function over executable kinds — which is the tidiness win that makes eviction strictly better than keeping it with an `Optional` return.
+
+### Step 3 — Tolerate the signature in the shared validators
+
+The signature's `type` ("PipeSignature") is no longer in `PipeType.value_list()`, and its `pipe_category` becomes `None` (Step 5). The base validators on **both** `PipeBlueprint` and `PipeAbstract` need three small allowances:
+
+- `validate_pipe_type` (field, after): admit the signature tag.
+
+ ```python
+ if value not in PipeType.value_list() and value != PipeSignatureBlueprint type tag "PipeSignature":
+ raise ...
+ ```
+
+ Express the allowlist honestly — define a module-level `PIPE_SIGNATURE_TYPE_TAG = "PipeSignature"` in `pipe_blueprint.py` and check `value not in PipeType.value_list() and value != PIPE_SIGNATURE_TYPE_TAG`. (Avoid importing `PipeSignatureBlueprint` into the base module — that's a cycle; a bare string constant is the right tool.)
+
+- `validate_pipe_category` (field, after): admit `None`.
+
+ ```python
+ if value is not None and value not in PipeCategory.value_list():
+ raise ...
+ ```
+
+ Only signatures carry `None` (executable subclasses pin `Literal["PipeOperator"|"PipeController"]`), so this is safe.
+
+- `validate_pipe_category_based_on_type` (model, after): early-return for signatures, before the `PipeType(self.type)` coercion that would now raise.
+
+ ```python
+ def validate_pipe_category_based_on_type(self) -> Self:
+ if self.is_signature:
+ return self
+ ...
+ ```
+
+ `is_signature` is class-based after Step 1, so this is reliable at model-validation time.
+
+### Step 4 — Factory: branch around the `PipeType` coercion
+
+`pipelex/core/pipes/pipe_factory.py` (lines 105-106) currently does `pipe_type = PipeType(blueprint.type)` then `pipe_category = pipe_type.category` — both raise for a signature. Branch on `is_signature` and resolve the factory by name from the string (no `PipeSignatureFactory` import → no cycle; the class-registry lookup already in place resolves it):
+
+```python
+if blueprint.is_signature:
+ pipe_category = None
+ factory_class_name = f"{blueprint.type}Factory" # "PipeSignatureFactory"
+else:
+ pipe_type = PipeType(blueprint.type)
+ pipe_category = pipe_type.category
+ factory_class_name = f"{pipe_type.value}Factory"
+```
+
+The existing registry lookup + `pipe_factory.make(pipe_category=pipe_category, ...)` call (lines 110-131) stays. `PipeSignatureFactory.make` already accepts `pipe_category: Any`; it ignores it and builds the shim.
+
+### Step 5 — Signature runtime + blueprint: `pipe_category` → `None`
+
+- `pipelex/pipe_signature/pipe_signature.py` (line 28): `pipe_category: Literal["PipeSignature"] = "PipeSignature"` → `pipe_category: None = None`. (`type` stays `Literal["PipeSignature"]` — it's the blueprint tag, still the discriminator string.)
+- `pipelex/pipe_signature/pipe_signature_blueprint.py` (line 18): → `pipe_category: None = Field(default=None, exclude=True)`. **Keep `exclude=True`** — overriding the field type drops the base's `Field(exclude=True)` unless re-specified, and we still don't want `pipe_category` serialized into round-tripped `.mthds`.
+
+The discriminated union (`PipeBlueprintUnion`) discriminates on `type`, not `pipe_category`, so `None` here is invisible to parsing.
+
+### Step 6 — `output_renderer` guard
+
+`pipelex/core/pipes/output/output_renderer.py`: line 32 `PipeType(the_pipe.type)` raises for a signature, and the match arm (lines 99-110) lists `PipeType.PIPE_SIGNATURE`. Add an early return and drop the arm:
+
+```python
+if the_pipe.is_signature:
+ return []
+pipe_type = PipeType(the_pipe.type)
+...
+case (PipeType.PIPE_FUNC | ... | PipeType.PIPE_PARALLEL): # PIPE_SIGNATURE removed
+ return []
+```
+
+Still exhaustive over the shrunken `PipeType`.
+
+### Step 7 — Delete the `signature_for` guards (keep the field) {#the-signature_for-interaction}
+
+`pipelex/pipe_signature/pipe_signature_blueprint.py` (lines 24-30) and `pipelex/builder/pipe/pipe_signature_spec.py` (lines 53-59): **delete** both `reject_signature_for_pipe_signature` validators. They reference `PipeType.PIPE_SIGNATURE`, which no longer exists → they would raise `AttributeError` whenever a signature is parsed. Their intent (forbid `signature_for=PipeSignature`) is now enforced structurally: `signature_for: PipeType | None` can no longer coerce the string `"PipeSignature"`, so Pydantic rejects it with a clean validation error.
+
+`signature_for` itself, `PipeSignatureFactory`'s `signature_for=blueprint.signature_for` pass-through (line 32), and `PipeSignatureSpec.to_blueprint`'s `signature_for=self.signature_for` (line 67) all **stay**. Soften the docstrings that say "cannot itself be `PipeSignature`" (`pipe_signature_spec.py` lines 42-43) since the enum now enforces it.
+
+### Step 8 — Spec layer: widen `validate_pipe_type`
+
+`pipelex/builder/pipe/pipe_spec.py` (lines 79-85): same widening as Step 3's `validate_pipe_type` — admit the signature tag so `PipeSignatureSpec` still validates. No other spec-layer change (see [scope decision](#scope-decision-the-spec-layer-stays-put)); `pipe_spec_map.py:27` (`"PipeSignature": PipeSignatureSpec`) is a string-keyed map and is unaffected.
+
+---
+
+## ⛳ Checkpoint — run the core gate before docs
+
+After Steps 1-8 (all code), this is the risky core. Run and get green before touching prose:
+
+- `make tb` — boot/config load (catches enum + Pydantic field breakage fast).
+- `.venv/bin/pipelex-dev generate-mthds-schema` — regenerate `derived/mthds_schema.json` (the `PipeSignatureBlueprint` definition still exists in the union; `_PIPE_INTERNAL_FIELDS = {"pipe_category"}` still strips the field). Commit the regenerated schema.
+- `make agent-check` — ruff / pyright / mypy / plxt.
+- `make agent-test` — full suite. Expect edits in the signature/taxonomy unit tests that asserted `PipeCategory.PIPE_SIGNATURE` or `signature_for` rejection messages; update them to the new model.
+
+### Step 9 — Docs / CHANGELOG / TODOS reframe
+
+- `docs/building-methods/pipes/signature-pipes.md` — stop framing it as "a new type of pipe." Frame: every pipe *has* a signature (its contract); a `PipeSignature` is the contract alone — a blueprint-layer declaration whose runtime form is a dry-run-only mock shim, deliberately outside the executable `PipeType`/`PipeCategory` taxonomy.
+- `TODOS.md` change #1 ("Pipe signature ↔ concrete reconciliation") — reword from "replace pipe-type `PipeSignature` with pipe-type `PipeLLM`" to "**a contract fulfilled by an implementation**" (the reconciliation table is unchanged; `contracts_match` is unchanged).
+- `CHANGELOG.md` `[Unreleased]` — note: `PipeSignature` moved out of the `PipeType`/`PipeCategory` taxonomy; `PipeCategory.PIPE_SIGNATURE` removed (breaking for anything matching on it); `signature_for` retained.
+
+---
+
+## A welcome side effect
+
+The headline feature reads truer. `library_crate_factory._reconcile_pipe_collision` keys off `blueprint.is_signature` (lines 169-190) — after this it means **"a contract is fulfilled by an implementation,"** not "swap pipe-type `PipeSignature` for pipe-type `PipeLLM`." `contract_match.contracts_match()` is untouched.
+
+## Out of scope / future
+
+- **Eventually retire `signature_for`.** Kept now only for `../mthds-plugins`. It is an advisory implementor hint pointing at an *implementable* kind — it is **not** the signature's underlying type (a signature has no underlying type). Revisit once mthds-plugins no longer depends on it; likely fold any hint into `description` rather than a typed field.
+- **`pipe_category` is itself redundant** — it must equal `PipeType(type).category` for executable pipes and is now `None` for signatures. It could later be derived rather than stored. Not in this change.
+- **`is_controller` class-conversion** (Step 1b) can be deferred if minimizing diff.
+
+## Touch-point index
+
+| File | What |
+| --- | --- |
+| `pipelex/core/pipes/pipe_blueprint.py` | shrink both enums; `PipeBlueprint.is_signature` → `False`; widen `validate_pipe_type` / `validate_pipe_category`; `validate_pipe_category_based_on_type` early-return; add `PIPE_SIGNATURE_TYPE_TAG` |
+| `pipelex/core/pipes/pipe_abstract.py` | `is_signature` → `False` base; same validator widening; (1b) `is_controller` → `False` base |
+| `pipelex/pipe_signature/pipe_signature.py` | `pipe_category: None = None`; `is_signature` override → `True` |
+| `pipelex/pipe_signature/pipe_signature_blueprint.py` | `pipe_category: None = Field(default=None, exclude=True)`; `is_signature` override → `True`; delete guard validator |
+| `pipelex/pipe_signature/pipe_signature_factory.py` | no change (still passes `signature_for`) |
+| `pipelex/pipe_controllers/pipe_controller.py` | (1b only) `is_controller` override → `True` |
+| `pipelex/core/pipes/pipe_factory.py` | branch on `is_signature` around the `PipeType` coercion |
+| `pipelex/core/pipes/output/output_renderer.py` | early `is_signature` return; drop `PIPE_SIGNATURE` match arm |
+| `pipelex/builder/pipe/pipe_spec.py` | widen `validate_pipe_type` |
+| `pipelex/builder/pipe/pipe_signature_spec.py` | delete guard validator; soften docstring; keep tags + `signature_for` |
+| `derived/mthds_schema.json` | regenerate |
+| tests + docs + CHANGELOG | per Steps 8-9 |
+
+`registry_models.py` (`PIPE_SIGNATURES` / `PIPE_SIGNATURES_FACTORY` ClassVars) **stays** — keeping signatures as their own registry group reinforces "not an operator/controller."
+
+## Checklist
+
+- [x] Step 1 — `is_signature` class-based (abstract + blueprint + overrides); (1b) `is_controller` — **1b skipped on purpose** (see below)
+- [x] Step 2 — `PIPE_SIGNATURE` out of `PipeType` + `PipeCategory` (+ match arms)
+- [x] Step 3 — base validators tolerate the signature tag + `None` category + early-return
+- [x] Step 4 — factory branch
+- [x] Step 5 — signature `pipe_category` → `None` (keep blueprint `exclude=True`)
+- [x] Step 6 — `output_renderer` guard
+- [x] Step 7 — delete `signature_for` guards, keep the field
+- [x] Step 8 — spec `validate_pipe_type` widened
+- [x] ⛳ `make tb` + schema regen (no diff) + `make agent-check` + `make agent-test` green
+- [x] Step 9 — docs / CHANGELOG / TODOS reframed
+
+## As-built notes
+
+- **Step 1b (class-based `is_controller`) skipped — deliberate.** The plan flagged 1b as optional cleanliness, not correctness. Doing it would turn `PipeCategory.is_controller` and `PipeCategory.is_controller_by_str` into dead code (their only remaining caller is `PipeAbstract.is_controller`), and removing that dead code would diverge from Step 2's "edit the `is_controller` match arm" instruction. Keeping the base `PipeAbstract.is_controller` reading `PipeCategory.is_controller_by_str(self.pipe_category)` is already correct for a signature: `pipe_category` is now `None`, `PipeCategory(None)` raises `ValueError`, and the `except ValueError → False` path returns `False`. So `is_controller` stays correct, the two `PipeCategory` helpers stay legitimately used, and there is no dead code. The keystone (`is_signature` by class) is fully implemented. Revisit 1b only if `is_controller` ever needs to stop touching `pipe_category` for another reason.
+- **Allowlist expressed honestly.** A module-level `PIPE_SIGNATURE_TYPE_TAG = "PipeSignature"` in `pipe_blueprint.py` is the single source of the signature tag; `validate_pipe_type` on `PipeBlueprint`, `PipeAbstract`, and `PipeSpec` each check `value not in PipeType.value_list() and value != PIPE_SIGNATURE_TYPE_TAG`, and their error messages list `[*PipeType.value_list(), PIPE_SIGNATURE_TYPE_TAG]` so the signature tag shows up as a legal value.
+- **`signature_for` rejection is now structural.** Both `reject_signature_for_pipe_signature` guards (blueprint + spec) were deleted; the field is typed `PipeType | None` and `PipeSignature` is no longer a `PipeType`, so Pydantic rejects `signature_for = "PipeSignature"` on its own. Tests were updated to pass the raw string and assert `ValidationError`.
+- **Tests updated to the new model:** `test_pipe_blueprint_signature_enums.py` now locks in the eviction (members removed, tag not in either enum, coercion raises); `test_pipe_abstract_signature_surface.py` asserts the base descriptor returns `False` even for a stub whose `pipe_category == "PipeSignature"` (identity is class-based); `test_pipe_signature.py` asserts `type == "PipeSignature"` and `pipe_category is None`.
diff --git a/wip/signature-based-validation/signature-based-validation.md b/wip/signature-based-validation/signature-based-validation.md
index 735299a48..8825d5d12 100644
--- a/wip/signature-based-validation/signature-based-validation.md
+++ b/wip/signature-based-validation/signature-based-validation.md
@@ -54,6 +54,14 @@ After `dev` was merged in, the review bots surfaced reconciliation issues; the c
- **Strict whole-bundle docstrings clarified** (on the then-`dry_run_pipes`, now `BundleValidator.validate_pipes` — see the Post-#956 note below — and on `PipeSignatureSpec`): whole-bundle strict rejects any bundle containing a signature; `--pipe` / `--allow-signatures` are the escape hatches.
- A separate `.pipelex/plxt.toml` "schema rule clobbers formatting" report was reviewed and confirmed a **false positive** (taplo merges formatting across matching rules; schema is resolved independently) — no change.
+## Review fixes (additive-library completeness, 2026-06-07)
+
+A second review pass found three paths that still did per-file / pre-merge work, breaking the same-domain authoring the merged crate is meant to resolve. The concept side had moved same-domain resolution to the merged level (`validate_concept_references_in_blueprints` in the loader); these three completed the same move for the pipe side and the remaining loaders. All confirmed against the code and fixed with regression tests:
+
+- **Qualified same-domain pipe refs now resolve across sibling files.** The per-file `validate_local_pipe_references` `@model_validator` on `PipelexBundleBlueprint` eagerly rejected a qualified same-domain step ref (`research.find_key_findings`) unless the target pipe was declared in the *same* file — while the bare form was already deferred (the exact asymmetry the concept side had already removed). In an additive library the concrete can live in a sibling file, reconciled by `LibraryCrateFactory`. Every other branch of the validator was already a no-op, so it is removed entirely; a genuinely missing ref is still caught post-merge by `validate_pipe_library_with_libraries` (`get_required_pipe` → `PipeNotFoundError` → `LibraryError`). The shared `collect_pipe_references` helper stays (used by `visibility_utils` and the dependency loader). — `tests/integration/pipelex/libraries/test_additive_multi_file_library.py` (`test_qualified_same_domain_sibling_pipe_ref_resolves`, `test_undeclared_qualified_pipe_ref_surfaces_clean_error`); the now-obsolete `tests/unit/pipelex/core/bundles/test_pipelex_bundle_blueprint_pipe_validation.py` was removed (it only exercised the deleted validator).
+- **Concepts-only loading now validates concept references.** `LibraryManager.load_concepts_only_from_blueprints` skipped `validate_concept_references_in_blueprints` (only the full `load_from_blueprints` ran it), so the `pipelex structures` / `load_concepts_only` path accepted a dangling `concept_ref` / `item_concept_ref` and left an unrebuildable schema in the library. It now runs the same merged validator (with `already_loaded_concept_refs` for cross-batch resolution) before adding the batch's concepts. — `tests/integration/pipelex/pipeline/test_load_concepts_only.py` (`test_load_concepts_only_rejects_dangling_concept_ref`, `..._item_concept_ref`).
+- **Dependency packages now load through the crate merge.** `LibraryManager._load_single_dependency` built pipes per-blueprint and called `add_new_pipe` directly, so a multi-file dependency (a `PipeSignature` header + concrete sibling) collided on the duplicate pipe ref — swallowed by the per-pipe `except (PipeLibraryError, ValidationError)` as a warning, silently dropping one declaration (load-order dependent: a signature-only survivor is non-executable). It now builds a `LibraryCrate` from the dependency's blueprints first (signature/concrete reconciliation + normalized contract check + duplicate detection) and runs `validate_concept_references_in_blueprints`, then loads the reconciled `crate.pipes` (export filter and synthetic-helper handling preserved). The per-pipe handler now catches only `ValidationError` (a single malformed blueprint stays lenient); a genuine duplicate definition raises from the crate instead of warning — aligning dependencies with the main load path. — `tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py`.
+
## Architecture (Option A, as built)
Three layers, parallel additions; the discriminator stays `type`: