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.
PipeSignature is not a type — declare signatures by omitting the type (#1023)
Louis Choquele9412f717674
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 956ebded1..b23d2d840 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,11 @@# Changelog+## [Unreleased]++### Changed++- **`PipeSignature` is not a pipe type (Breaking):** A signature is now declared by **omitting** `type` — a `[pipe.x]` section with no `type` and nothing but the contract (`description`, `output`, optional `inputs`, optional `signature_for`) *is* a `PipeSignature`. Writing `type = "PipeSignature"` explicitly is rejected with a migration error ("`PipeSignature` is no longer a pipe type — delete the `type` line"), and a typeless section that declares any non-contract field is a hard error naming the field. The `pipelex-agent pipe` authoring command mirrors this: a typeless JSON spec (no `type`) renders a `[pipe.x]` section with no type line, and `--type PipeSignature` is rejected. **MTHDS JSON Schema shape change:** the signature arm no longer carries a `type` property (an explicit tag now fails schema validation), so the downstream schema copies (`mthds`, `vscode-pipelex`, `mthds-ui`) must be re-synced on the next release via the `mthds-schema-sync` skill.+## [v0.37.0] - 2026-07-04### Highlightsdiff --git a/TODOS.md b/TODOS.mdindex 7c0c670f2..05f768b90 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,113 +1,173 @@-# Cookbook "hello plugin" → real inference-backend plugin (Option B)+# Implementation plan — PipeSignature is not a type-Status: **CHECKPOINT B CLEARED — TRACK COMPLETE (2026-07-03).** Phases 0–4 done and ALL COMMITTED. Pipelex (`feature/More-plugins`): `2f9b7e1d9` (optional_routes fix), `dee230f46` (LLM worker fold, breaking), plus the docs+tracker commit carrying this file. Cookbook (`dev`): `ecb231c` (the whole example; root `pyproject.toml`/`uv.lock` editable pin deliberately left uncommitted — flip to `pipelex==X.Y.Z` at release, see caveat below). Only remaining action = release ordering (step 3 below). This tracker is retired.+**Branch:** `feature/PipeSignature-not-a-type`+**Design doc:** [`wip/pipe-signature-not-a-type.md`](wip/pipe-signature-not-a-type.md) — read this first for the *why*.+**Status:** Phase 3 complete (code + tests + docs green) · pending Checkpoint-3 cold review + commit SHA · this is the final phase-## NEXT SESSION — start here+## Goal in one line-1. **Commit slicing first** (user to approve slices). This worktree (`_plugins`, branch `feature/More-plugins`) holds four separable concerns — do NOT mix them:- - `optional_routes` factory fix: `pipelex/cogt/model_routing/routing_profile_factory.py` + `tests/unit/pipelex/cogt/model_routing/test_routing_profile_optional_routes.py` + its CHANGELOG "Fixed" entry.- - LLM worker fold (breaking): `llm_worker_abstract.py` (folded), `llm_worker_internal_abstract.py` (deleted), `llm_utils.py` + `llm_generate.py` (dump gating moved), `inference_manager{,_protocol}.py` (legacy setter removed), 6 re-parented workers under `pipelex/plugins/`, reworked tests (`test_worker_error_enrichment`, `test_external_plugin`, `test_llm_gen_text`, `test_setup_inference_workers`, factory/manager types) + the two CHANGELOG "Changed" entries.- - Orchestrator-plugins docs from a PRIOR session (unrelated to this track — `docs/under-the-hood/orchestrator-plugins.md` etc.).- - `TODOS.md` (this tracker).- Cookbook side = one coherent commit (example package, `.pipelex/inference/` config, `.mthds`, README×2, CHANGELOG, `test_bundles.py`, mypy exclude) — but the `[tool.uv.sources]` editable pin in `pyproject.toml`/`uv.lock` must NOT ship (see editable-pin caveat below).-2. **Phase 4 — docs rewrite** (checkboxes below). Also re-check `docs/under-the-hood/inference-backend-plugins.md`'s worker section against the folded base (constructor now takes `inference_model`; no lifecycle gotchas left to document).-3. **Release ordering**: pipelex release > 0.36.0 (breaking changelog) → flip cookbook pin to `pipelex==X.Y.Z` → cookbook release. Before the pipelex release, grep `pipelex-temporal` + `pipelex-mistralai-workflows` for LLM worker subclasses / `set_llm_worker_from_external_plugin` (expected: none — both are orchestrator-only).+Drop `type = "PipeSignature"` from the language: a `[pipe.x]` section with **no `type`** and **nothing but the contract** (`description` + `output`, optional `inputs`, optional `signature_for`) **is** a `PipeSignature`. Anything else without a `type` is a hard error.-All gates were green at session end (2026-07-03): pipelex `make agent-check` + `make tb` + FULL `make agent-test`; cookbook `make agent-check` + `make agent-test` + hello-plugin real run end-to-end.+## Settled decisions (from the design doc)-## Goal+- **D1** — Signatures only. Concrete pipes keep explicit `type`. No inference from fields (impossible anyway — `prompt` is shared by PipeLLM and PipeImgGen).+- **D2** — Typeless + any non-contract field ⇒ **hard error**, no leniency, no type-guessing. Legal typeless keys are exactly `{description, inputs, output, signature_for, source}`.+- **D3** — Explicit `type = "PipeSignature"` ⇒ **rejected** with a migration error. No transitional alias.+- **D4** — Keep the optional `signature_for` hint.-Replace the legacy cookbook example `pipelex-cookbook/examples/c_advanced/using_inference_plugins/` with a genuine entry-point plugin that demonstrates the real plugin system. Today that example is a single `.mthds` file whose `model` field references the handle `llm_plugin_example_using_openai` — a name **defined nowhere** (not in the cookbook's `.pipelex/inference/`, not in the core kit). "Plugin" in its name is pre-plugin-system vocabulary meaning "custom model config entry"; the example has only ever run as DRY RUN (see `pipelex-cookbook/.pipelex/traces/`). Decision taken with the user (2026-07-03): **Option B** — make it an actual `pipelex.plugins` entry-point plugin, not a config-only reframe.+## Phasing rationale (why this order)-## Background: the plugin system (cold-start summary)+`make agent-check` runs `plxt-lint`, which **regenerates the JSON schema from the Python models and then lints every `.mthds` file against it** (Makefile:842-845). So the language-schema generator and the fixture migration are gate-locked: fixtures can only drop the tag once the schema accepts typeless sections. To keep every checkpoint green *and* reviewable in isolation, we go **additive first, breaking last**:-The pipelex repo (this worktree, `_plugins`) has a discovery-based plugin system. Everything below is verified against the current tree:+- **Phase 1** makes typeless-signatures work at runtime *and* in the schema, while the old explicit tag still parses (both accepted). Tested with inline TOML/dicts so no fixture files move yet.+- **Phase 2** mirrors the same additive support in the spec (authoring) layer.+- **Phase 3** flips to rejecting the old tag, migrates all fixtures, rewords rendering, and updates docs — the one breaking phase.-- **Contract** (`pipelex/plugins/contract.py`): a plugin is any object satisfying the `@runtime_checkable` `PipelexPlugin` protocol — `name: str`, `targets_api: int` (must equal `PLUGIN_API_VERSION`, currently **2**), and `register(self, registrar) -> None`. `register` is **side-effect-free**: it may only call registrar menu methods — no I/O, no SDK import, no client construction. Heavy work goes inside the `make_worker` closures.-- **Discovery** (`pipelex/plugins/discovery.py`): `build_registrar` iterates `BUILTIN_PLUGINS` then external entry points in group **`pipelex.plugins`**. An entry point may resolve to a plugin instance or a zero-arg factory returning one. Denylist via `plugins.disabled` config; fail-loud on duplicates/version mismatch/broken plugin.-- **Inference seam** (`pipelex/plugins/inference_backend_registry.py`): `registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="<token>", make_worker=...)`. A model's `sdk` field selects the backend factory; worker factories hold no match over SDK strings. `MakeWorkerFn` is called as `make_worker(*, inference_model: InferenceModelSpec, backend: InferenceBackend, sdk_clients: SdkClientRegistry, reporting_delegate: ReportingProtocol | None) -> InferenceWorkerAbstract`. Use `require_sdk(...)` inside `make_worker` for optional-dependency guards.-- **Minimal LLM worker**: subclass `LLMWorkerAbstract` (`pipelex/cogt/llm/llm_worker_abstract.py`); since the fold (see follow-up below) the abstract surface is just `_gen_text` + `_gen_object` — the base takes `inference_model` in `__init__`, owns the job lifecycle, and derives capability flags from the spec.-- **Optional companion**: `registrar.add_model_lister(sdk="<token>", lister=...)` — powers `pipelex show models`.-- **Reference implementations**: smallest builtin = `pipelex/plugins/blackboxai/blackboxai_plugin.py` (one `add_inference_backend`, lazy imports inside `_make_..._worker`). External entry-point precedents = `pipelex-temporal` (`pipelex_temporal/temporal_plugin.py`) and `pipelex-mistralai-workflows`.-- **Canonical authoring doc**: `docs/under-the-hood/inference-backend-plugins.md` (the "acme" walkthrough — the cookbook example should be its living counterpart).-- **Verification command**: `pipelex plugins list` prints every discovered plugin (origin builtin/external, status, API version, contributions).+One commit per phase (repo convention). Nothing pushed until the user says so.-Model config layer (how a `.mthds` `model` handle reaches the plugin): the cookbook's `.pipelex/inference/backends.toml` declares backends keyed by name (`[hello]`, `enabled`, `api_key`...); per-backend model files `backends/<name>.toml` declare model sections with `[defaults]` carrying `sdk = "<token>"` — the section header is the model handle referenced from `.mthds`. The `add-model` skill (in this repo's `.claude/skills/`) documents the full add-a-model procedure including routing profiles.+----## Decisions+## Fan-out convention for `/code-review` (used at every checkpoint)-- **D1 — worker shape**: a deterministic, zero-key "hello" echo worker (returns a canned/derived completion) so the example runs everywhere with no credentials; the rewritten docs page points to `inference-backend-plugins.md` for wrapping a real SDK. Rationale: cookbook examples must be runnable; the seam being demonstrated is discovery/registration, not OpenAI usage. (Override here if we'd rather wrap the OpenAI SDK.)-- **D2 — package location**: the plugin package lives inside the example dir, e.g. `examples/c_advanced/using_inference_plugins/hello_inference_plugin/` with its own `pyproject.toml`, installed with `uv pip install -e` (cookbook already uses uv). It is NOT a dependency of the cookbook's root `pyproject.toml` — installing it is the demonstrated step.-- **D3 — naming**: retire the dangling handle `llm_plugin_example_using_openai`. New names: plugin `hello-inference` (entry-point name `hello_inference`), sdk token `hello`, backend `[hello]`, model handle e.g. `hello-1`. No `pipelex_` prefix anywhere user-facing that belongs to the example.+Spawn the reviewer as a **fresh Sonnet-5 sub-agent with NO inherited context** (`subagent_type: general-purpose`, `model: sonnet` — **not** `fork`, which would inherit this plan). Hand it *only* a pointer to the changes:-## Phases+> Run the `/code-review` skill on the changes in `<commit SHA>` (or `git diff <base>..HEAD`, or the unstaged working tree). We want clean, solid software — flag over-engineering, dead code, and any correctness bug. Report findings only; do not fix.-### Phase 0 — Recon in the cookbook repo+Do **not** pass the plan, the design doc, the decisions, or any rationale. Let the review land cold. Triage its findings back in TODOS.md (fix / defer-to-wip / refute) before clearing the checkpoint.-- [x] Verify how a custom backend + model file wires end-to-end in the cookbook's current `.pipelex/` layout: add a scratch `[hello]` backend + `backends/hello.toml` model with `sdk = "hello"` and confirm the failure mode is `InferenceBackendNotFoundError` for `(llm, hello)` (proves config resolves and the missing piece is exactly the plugin). **DONE** — exact friendly message confirmed: "No inference backend registered for sdk 'hello' in the llm family. Is its plugin installed and enabled?".-- [x] Confirm whether routing profiles (`.pipelex/inference/routing_profiles.toml`) need an entry for a directly-referenced model handle, or whether `model = { model = "hello-1" }` in `.mthds` bypasses routing. **ANSWERED: routing is NOT bypassed.** `ModelManager.build_deck` routes every known model through the active profile; a DEFAULT match whose backend lacks the model spec **silently drops the model from the deck** (only the `internal` backend is tried as fallback). So the example needs an exact route. We use `optional_routes = { "hello-1" = "hello" }` in the active `all_pipelex_gateway` profile — optional routes only apply when the target backend is enabled, so the entry is inert if `[hello]` is disabled. **This surfaced a real core bug (fixed here, see below).**-- [x] ~~Check the cookbook's pinned `pipelex` version supports the plugin system~~ — resolved 2026-07-03: the cookbook now sources `pipelex` **editable from this worktree** (`pipelex-cookbook/pyproject.toml` `[tool.uv.sources] pipelex = { path = "../_plugins", editable = true }`), so it runs against this tree's tip. Any pipelex-side change needed for the example is made HERE and is live in the cookbook immediately.+----### Phase 1 — The plugin package (in `pipelex-cookbook`) — DONE+## Phase 0 — Baseline (quick)-- [x] Create `examples/c_advanced/using_inference_plugins/hello_inference_plugin/` with `pyproject.toml`: distribution name `hello-inference-plugin`, entry point `hello_inference = "hello_inference_plugin.hello_plugin:HelloInferencePlugin"` (module path deviates from the plan's `hello_inference_plugin:...` — no-re-exports rule forbids defining the class in `__init__.py`; layout mirrors the builtins' `<name>_plugin.py`), dependency on `pipelex`, hatchling build, `py.typed` marker (needed by the cookbook's mypy).-- [x] Implement `HelloInferencePlugin` in `hello_inference_plugin/hello_plugin.py`: `name = "hello_inference"`, `targets_api = PLUGIN_API_VERSION`, side-effect-free `register`, worker import deferred into the `_make_hello_llm_worker` closure.-- [x] Implement `HelloLLMWorker(LLMWorkerAbstract)` in `hello_llm_worker.py`: deterministic `_gen_text` (canned haiku + word-count token usage), `_gen_object` raises `LLMCapabilityError`; capability flags come from the model spec via the base class. (An earlier gotcha — workers had to call `llm_job.llm_job_before_start` themselves or reporting crashed on a `None` duration — was eliminated by folding `LLMWorkerInternalAbstract` into `LLMWorkerAbstract` in core, see below.)-- [x] Bonus TAKEN: `registrar.add_model_lister(sdk="hello", lister=...)` in `hello_list.py` — reads the models from the backend config (no remote API), lights up `pipelex show models hello`.+- [x] Confirm branch is green from a clean state: `make agent-check && make agent-test`. — both green (exit 0).+- [x] Note the baseline SHA here for the Phase-1 review diff base: `04434f78586b328e080fd76b50bf46b00e0b6765`.-### Phase 2 — Config + method files (in `pipelex-cookbook`) — DONE+----- [x] `[hello]` backend added to `.pipelex/inference/backends.toml` (enabled, no key), `backends/hello.toml` declares `hello-1` with `sdk = "hello"`, and `optional_routes = { "hello-1" = "hello" }` added to the active `all_pipelex_gateway` profile in `routing_profiles.toml`.-- [x] `hello_plugin.mthds` references `hello-1`; dangling handle `llm_plugin_example_using_openai` retired.+## Phase 1 — Additive typeless-signature support (blueprint + language schema)-### Phase 3 — End-to-end verification (in `pipelex-cookbook`) — DONE+The heart of the change. Make "no type + contract-only ⇒ signature" true at runtime and in the schema. Keep the old explicit tag parsing for now (rejection is Phase 3).-- [x] `uv pip install -e examples/c_advanced/using_inference_plugins/hello_inference_plugin` (left installed in the cookbook venv).-- [x] `pipelex plugins list` shows `hello_inference | external | registered | 2 | inference backend llm:hello + model lister hello`.-- [x] Dry run AND real run green — real run outputs the deterministic haiku, zero keys. `pipelex show models hello` lists `hello-1`.-- [x] Negative check: after uninstall, run fails with the friendly "No inference backend registered for sdk 'hello' in the llm family. Is its plugin installed and enabled?" — and the DRY RUN still passes without the plugin (worker creation is lazy), so cookbook CI needs nothing installed.-- [x] Housekeeping: example README written (install → discover → run → failure mode → docs link); cookbook CHANGELOG `[Unreleased]` entry; root README bullet under "Advanced Methods"; `tests/e2e/test_bundles.py` stale special-cases removed (`NEEDS_OPENAI_KEY` and `GHA_DISABLED` both emptied — the example no longer needs a key nor a GHA skip); cookbook `pyproject.toml` mypy `exclude` gains the nested plugin dir (module-name clash: resolve as the installed package, not via `examples/` traversal).-- Gates: cookbook `make agent-check` + `make agent-test` green; all `tests/e2e/test_bundles.py` dry-run cases pass (hello_plugin auto-discovered, no special-casing). Pipelex-side `make agent-check` green + targeted cogt tests pass.+- [x] Introduce a single named constant for the legal signature-only key set `{description, inputs, output, signature_for, source}`. → `SIGNATURE_ONLY_KEYS` (frozenset) added next to `PIPE_SIGNATURE_TYPE_TAG` in `pipelex/core/pipes/pipe_blueprint.py`. Single source of truth for blueprint + (Phase 2) spec layers.+- [x] Extend the `pipe` `mode="before"` validator in `pipelex/core/bundles/pipelex_bundle_blueprint.py` (`validate_pipe_keys`) with per-section normalization (new helper `_normalize_typeless_signature`):+ - `type` present (or an already-built blueprint instance / non-dict) → untouched.+ - `type` absent, keys ⊆ `SIGNATURE_ONLY_KEYS` → inject internal `type = "PipeSignature"` so the union routes to `PipeSignatureBlueprint`.+ - `type` absent, any other key present → raise the **teaching error** (names the offending field(s), states the rule, gives both fixes; does **not** guess a type).+ - `type = "PipeSignature"` written explicitly → still accepted this phase.+- [x] Route the teaching error through the existing categorizer → new `MISSING_PIPE_TYPE` value on `PipeValidationErrorType` + `_categorize_missing_pipe_type_error` in `validation_error_categorizer.py` (the error is raised on the aggregate `pipe` field, so the pipe_code is recovered from the message; sits alongside `UNKNOWN_PIPE_TYPE`, category `blueprint_validation`).+- [x] Schema generator `pipelex/language/mthds_schema_generator.py`: **`_require_type_on_pipe_definitions` now skips the signature arm**, leaving its `type` OPTIONAL (Pydantic already emits `enum: ["PipeSignature"]` with a default). **Deviation from the literal checklist wording, intentional for Phase 1:** the design doc / this bullet describe the *end-state* (remove `type` from the signature arm → an explicit tag then fails the schema). Doing that in Phase 1 breaks every still-tagged fixture under `plxt-lint` (verified: `error[schema]: Additional properties are not allowed ('type' ...)`). Since Phase 1 is additive (both forms accepted, **no fixtures move yet**), the arm keeps `type` optional. Disambiguation verified for all cases: typeless contract → 1 match (signature arm); typeless+stray → 0; concrete typed → 1 (own arm); explicit `PipeSignature` → 1 (still valid); typo'd type → 0. **Removing `type` from the arm + migrating fixtures is the gate-locked Phase-3 breaking step.**+- [x] Regenerate the derived schema (`.venv/bin/pipelex-dev generate-mthds-schema`) — runs clean; `plxt lint` clean across all fixtures.+- [x] Tests (inline TOML/dicts — no fixture files yet), in `tests/integration/pipelex/pipe_signature/test_pipe_signature_in_blueprint_union.py`:+ - typeless contract ⇒ `PipeSignatureBlueprint`, `is_signature is True`, `pipe_category is None`.+ - contract with **no `inputs`** is valid.+ - typeless + a stray field ⇒ teaching error (asserts message names the field + both fixes).+ - explicit `type = "PipeSignature"` still accepted.+ - typeless header vs. typed definition reconciles (concrete wins) — added to `tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py`.+ - categorizer routing: `MISSING_PIPE_TYPE` structured item with pipe locator — added to `tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.py`.+- [x] Schema tests in `tests/unit/pipelex/language/test_mthds_schema.py`: typeless contract validates; typeless + stray field fails; typo'd `type` fails; explicit tag still validates (Phase-1 guard); `type`-required test now excludes the signature arm.+- [x] `make agent-check && make agent-test` green (full suite, exit 0).-**CHECKPOINT A — CLEARED 2026-07-03.** Working end-to-end in the cookbook. NOT committed yet in either repo (user to arbitrate commit slicing; this worktree also has unrelated uncommitted orchestrator-plugins docs).+### ⛔ CHECKPOINT 1 — STOP-#### Follow-up DONE (in this worktree): LLM worker family symmetry (fold `LLMWorkerInternalAbstract` → `LLMWorkerAbstract`)+- [x] Commit the phase (one commit). Record SHA: `e864b82486f00502206c6aa11b609b5256392e30`.+- [x] Update the **Cold-start snapshot** below (what changed, where the seam lives, what's verified, what's next).+- [x] **Fan out** a fresh Sonnet-5 `/code-review` sub-agent on this commit's diff, per the fan-out convention above. Triage findings here:+ - Findings: cold Sonnet-5 review, no blocker/major (core mechanism verified correct: fresh dicts/no input mutation, deterministic message order, sound pipe-code regex recovery, correct Draft-4 `oneOf` disambiguation). Minor/nits only:+ - **F1 (minor)** — a typeless section that is a subset of the allowed keys but omits a required contract field (`description`/`output`) is injected as a signature, then fails with a bare uncategorized pydantic "Field required" residual (dropped from structured `validation_errors[]`). Reviewer confirmed **not a regression** (concrete `PipeLLM` missing `output` behaves identically today) and the safety invariant holds (errors, never silent mock).+ - **F2 (nit)** — the `source` comment on `SIGNATURE_ONLY_KEYS` overstated present behavior.+ - **F3 (nit)** — message↔categorizer coupling; already guarded (marker comment + integration test).+ - **F4 (nit)** — hardcoded counts in TODOS.+ - **F5 (context)** — spec layer not yet mirrored = Phase 2 by design.+ - Actions taken / deferred-to-wip: **F1** → added guard test `test_typeless_section_missing_required_contract_field_still_errors` (pins the safety invariant) + **deferred** the broader categorization-completeness fix to `wip/pipe-signature-not-a-type.md` (it's a pre-existing general gap whose fix also changes concrete-pipe categorization — out of scope here). **F2** → comment corrected (kept `source` per D2). **F3** → no change (adequately guarded). **F4** → counts removed. **F5** → no action (next phase). All folded into the Phase-1 commit (amended); revised SHA recorded below.+- [ ] Only then proceed to Phase 2.-Decided with the user right after Checkpoint A: `LLMWorkerInternalAbstract` was a remnant of the pre-plugin-system "fake plugin" era, and the base `LLMWorkerAbstract` had a hole in its template method (external workers had to call `llm_job_before_start` themselves or reporting crashed). Fixed structurally, matching the other three families:+----- `LLMWorkerAbstract.__init__` now takes `inference_model`; the base owns the lifecycle (`llm_job_before_start`, spec-driven capability checks, constraints, spec-based OTel names). `LLMWorkerInternalAbstract` deleted; all builtin LLM workers re-parented.-- Legacy `set_llm_worker_from_external_plugin` (manager + protocol) removed — pre-plugin-system path registering spec-less worker classes by handle; its test reworked to drive an out-of-tree `LLMWorkerAbstract` subclass with a real spec.-- Import-cycle lesson (user cares): `pipelex/hub.py` imports the worker ABCs at module level, and `pipelex.config.get_config` imports the hub — so **nothing in hub's import closure may import `pipelex.config` at module level**. The dump gating that caused this moved to the `llm_generate` funnel; `dump_prompt`/`dump_response_from_text_gen` in `llm_utils` are config-gated internally (llm_utils left hub's closure when the ABC dropped it). NO lazy imports. Pre-existing deeper inversion flagged, not fixed: `config.py → hub` and `configs.py → aws_config.py → hub` mean the config layer sits ON TOP of the hub — a future refactor could move the config singleton below the hub and dissolve this class of cycle for good.-- Cookbook side: `HelloLLMWorker` shrank to `_gen_text` + `_gen_object` only (the teaching outcome we wanted); breaking changelog entries added in pipelex CHANGELOG `[Unreleased]`.+## Phase 2 — Spec (authoring) layer-#### Core bug found & fixed during Phase 0 (in this worktree)+Mirror the additive support so AI-authored specs get the identical clean surface. Specs are the builder convenience format (`pipelex/builder/pipe/`); they convert via `to_blueprint()`.-`RoutingProfileFactory.make_routing_profile` (`pipelex/cogt/model_routing/routing_profile_factory.py`) parsed + validated `optional_routes` from `routing_profiles.toml` but never passed it to the built `RoutingProfile` — TOML optional routes silently did nothing (nothing in the tree used them; zero test coverage). Fixed (one-line pass-through), new test module `tests/unit/pipelex/cogt/model_routing/test_routing_profile_optional_routes.py` (factory pass-through + enabled/disabled gating), CHANGELOG `[Unreleased]` entry added. **Consequence for the cookbook:** its `[Unreleased]` note says the example requires `pipelex` > 0.36.0 — the cookbook-side release must wait for (or pin past) the pipelex release carrying this fix. Related pre-existing wart spotted, NOT fixed: `RoutingProfile.get_backend_match_for_model` mutates `self.routes` in place when merging optional routes (`possible_routes = self.routes` without copy) — harmless today (idempotent merge), flag if it ever bites.+- [x] Add the same `mode="before"` normalization wherever spec dicts are validated into `PipeSpecUnion`. **The one production dispatch site for raw typeless dicts is `PipelexBundleSpec.pipe: dict[str, PipeSpecUnion]`** (`pipelex/builder/bundle_spec.py`) — added a `@field_validator("pipe", mode="before")` (`validate_pipe_keys`) that mirrors the blueprint layer. To avoid message drift with the categorizer marker (Phase-1 F3), the normalizer was **extracted into a single shared free function** `normalize_typeless_signature_section(pipe_code, *, pipe_section, allowed_keys)` in `pipelex/core/pipes/pipe_blueprint.py` (next to `SIGNATURE_ONLY_KEYS`); both the blueprint's `validate_pipe_keys` and the spec's now call it. The blueprint's old `_normalize_typeless_signature` classmethod was removed. **Key-set difference:** a spec section carries the structural `pipe_code` field (the blueprint uses the dict key), so the spec passes `SIGNATURE_ONLY_SPEC_KEYS = SIGNATURE_ONLY_KEYS | {"pipe_code"}` (defined in `bundle_spec.py`).+ - **Second candidate site investigated & ruled out:** `pipe_ops.py` `parse_pipe_spec` (`spec_class.model_validate`) and its only caller, the agent-CLI single-pipe `pipe` command (`pipe_cmd.py`), **always resolve an explicit type upstream** — `pipe_cmd.py:266` hard-errors if neither `--type` nor a `type` key is given, and `parse_pipe_spec` sets `spec_data["type"]` before validating. So a typeless dict never reaches that `model_validate`; no normalization is reachable there in Phase 2. `--type PipeSignature` still works there today (it's in `pipe_type_to_spec_class`). **Phase-3 gap flagged** (see below).+- [x] Confirm whether the spec layer has its own JSON-schema surface (e.g. a build/authoring API schema). If yes, apply the same signature-arm treatment; if no, note it here so the next session doesn't re-investigate: **No dedicated authoring schema.** The only generated/committed JSON Schema is `derived/mthds_schema.json`, produced from the **blueprint** layer (`mthds_schema_generator.py` → `PipelexBundleBlueprint.model_json_schema()`, handled in Phase 1). The spec models (`PipeSpecUnion` / `PipelexBundleSpec`) call `model_json_schema()` only ad-hoc for dry-run mock formats (`json_schema_extra={"mock_format": ...}`); the signature spec already hides its internal tags with `SkipJsonSchema[...]` on `type`/`pipe_category`. Nothing to regenerate or sync for the spec layer.+- [x] Tests: typeless spec ⇒ `PipeSignatureSpec` ⇒ `to_blueprint()` ⇒ `PipeSignatureBlueprint` with matching contract; typeless spec + stray field ⇒ teaching error. → `tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py` (also covers `signature_for` hint, explicit-tag-still-accepted Phase-2 guard, typed-section-untouched, already-built-instance passthrough).+- [x] `make agent-check && make agent-test` green. — agent-check: ruff/plxt/pyright-0/mypy-0/keyword-only all pass; full agent-test exit 0 ("All tests passed").-### Phase 4 — Docs rewrite (in the pipelex repo, this worktree) — DONE 2026-07-03+**Phase-3 gap flagged (single-pipe signature authoring):** once Phase 3 rejects the explicit `type = "PipeSignature"`, the agent-CLI single-pipe `pipe` command will have **no way to author a signature** (can't pass `--type PipeSignature` any more, and `pipe_cmd.py` errors on absent type). Phase-3 decision: either (a) make `pipe_cmd.py`/`parse_pipe_spec` route a typeless spec to `PipeSignatureSpec`, or (b) accept that signatures are only authored at the bundle level. Not implemented now (belongs with the breaking phase).-- [x] Rewrote `docs/cookbook/using-inference-plugins.md`: what a plugin is (entry point + `PipelexPlugin` + registrar), package layout, model-config side (`.pipelex/inference/`, optional route), install + `pipelex plugins list` + run walkthrough, failure mode, links to `under-the-hood/inference-backend-plugins.md`. Stale `.pipelex/pipelex.toml` claim gone; GitHub badge now points at the example dir. Also updated the stale blurb in `docs/cookbook/index.md`.-- [x] Audited `docs/features/llm-integration.md` — contains no plugin terminology at all (nothing to fix); the stale "plugins" mention was the cookbook page's own link text, now rewritten. Workspace-wide grep: no other legacy "plugin = config entry" language in docs (remaining "plugin" hits are the unrelated Claude Code skills plugin page).-- [x] Re-checked `docs/under-the-hood/inference-backend-plugins.md` worker section against the folded base: acme example already passes `inference_model` to the worker, no lifecycle gotchas documented — one stale bit found & fixed: lookup-miss error is `InferenceBackendNotFoundError`, not `NotImplementedError` (the doc's own fail-loud table already had it right).-- [x] `make docs-check` (strict mkdocs build) green.-- [x] Changelog entry under `[Unreleased]` (brief docs entry under "Changed").+### ⛔ CHECKPOINT 2 — STOP-**CHECKPOINT B (final)** — Phase 4 work all done; **only the commits remain** (user to approve the slices from "NEXT SESSION" step 1, plus these Phase 4 docs edits which ride with the tracker/docs concern or their own docs slice). Once committed in both repos, note the commit SHAs here and retire/archive this tracker. Release ordering reminder (step 3 above) still applies before shipping either side.--## Cross-repo map--| Repo | Work |-|---|---|-| `pipelex-cookbook` | plugin package, backend/model config, `.mthds`, run verification (Phases 0–3) |-| `pipelex` (this worktree `_plugins`) | docs page rewrite + terminology audit (Phase 4), plus any core change the example surfaces |--**Editable-pin caveat**: the cookbook's `[tool.uv.sources]` editable pin on `../_plugins` is a local dev convenience (set by the user 2026-07-03) and must NOT ship: before merging/releasing the cookbook side, flip back to a PyPI `pipelex==X.Y.Z` pin carrying whatever core changes this work needed (same playbook as the pipelex-api editable-pin precedent — editable local paths break CI). If the example needs no core change, the flip-back is to the current release.--## Gotchas for a cold start--- `register` must stay side-effect-free and import-light; anything heavy goes inside `make_worker`. Discovery runs `build_registrar` at boot AND in `pipelex plugins list`.-- `targets_api` must equal `PLUGIN_API_VERSION` (2) or discovery fails loud with `PluginApiVersionMismatchError`.-- The keyword-only-arguments convention is enforced on `pipelex/` source only, but the example package should follow it anyway — it's teaching material.-- Worker subclass signatures must match `LLMWorkerAbstract` exactly (use `@override`); the reporting/telemetry plumbing is inherited, don't reimplement it.-- Don't edit `docs/errors/` pages by hand (generated); nothing here should need new error classes anyway.-- Stale-terminology precedent: on 2026-07-03 we already fixed "CLI-build command harvest" leftovers in `contract.py`, `discovery.py`, and `inference-backend-plugins.md` — same spirit applies to any old "LLM plugin" config-speak found during Phase 4.+- [x] Commit the phase. Record SHA: `34fd87849866a37f0f0005b725de7ff21960ebe5` → **amended after review to `b52b4e8df5a21c2d521d59bd1a08b1d65e028f28`**.+- [x] Update the **Cold-start snapshot** below.+- [x] **Fan out** a fresh Sonnet-5 `/code-review` sub-agent on this commit's diff (fan-out convention). Triage:+ - Findings: cold Sonnet-5 review, **no blocker/major**. The shared-helper extraction was verified behavior-identical (full diff compare + all blueprint/schema/reconciliation/structured-error suites + new spec tests pass); before-validator confirmed to handle None / non-dict / raw-dict / already-built-instance identically to the blueprint. Two minor findings + one nit, both in the areas flagged for scrutiny:+ - **F1 (minor)** — `SIGNATURE_ONLY_SPEC_KEYS` reused `SIGNATURE_ONLY_KEYS` wholesale, carrying the **blueprint-only `source`** into the spec allowlist. `PipeSpec` has no `source` (extra="forbid"), so a typeless section with `source` was injected then failed with a raw pydantic `extra_forbidden` instead of the clean teaching error — defeating the Phase-2 goal for that key.+ - **F2 (minor)** — the spec's `validate_pipe_keys` only mirrored the *normalization* half of the blueprint's, not the **snake_case dict-key check**. A non-snake_case `[pipe.X]` key slipped through the spec layer and only failed later (worse-shaped, wrapped) in `to_blueprint()`. Docstring over-claimed "mirrors the blueprint layer."+ - **F3 (nit)** — the static teaching message lists only `description`/`inputs`/`output`, not `signature_for`/`source`/`pipe_code`.+ - Actions taken / deferred: **F1 → fixed** — `SIGNATURE_ONLY_SPEC_KEYS = (SIGNATURE_ONLY_KEYS - {"source"}) | {"pipe_code"}`; the allowlist now reflects the spec's real field surface. Guard test `test_typeless_with_blueprint_only_source_field_raises_teaching_error` (asserts teaching error, not raw `extra_forbidden`). **F2 → fixed** — added the same `is_pipe_code_valid` dict-key check to the spec's `validate_pipe_keys` (now a full mirror; docstring updated). Guard test `test_invalid_pipe_dict_key_rejected_at_spec_level`. **F3 → refuted** (no change) — intentional pedagogical simplification; the message teaches the core contract, optional/structural keys are deliberately omitted (same disposition as Phase-1 F2). *(Pre-existing key-vs-`pipe_code`-field reconciliation smell the reviewer noted in passing is out of scope — orthogonal to signatures, not introduced here.)* All folded into the Phase-2 commit (amended); revised SHA recorded below.+- [ ] Only then proceed to Phase 3.++---++## Phase 3 — Breaking cleanup, fixture migration, docs++The one breaking phase: reject the old tag, migrate every bundle, reword rendering, update docs. Everything below lands green together because schema regeneration + fixture migration are gate-locked.++- [x] Blueprint before-validator: `type = "PipeSignature"` written explicitly ⇒ **migration error** (D3). Implemented in the **shared** `normalize_typeless_signature_section` (`pipe_blueprint.py`) via `explicit_signature_tag_migration_message(pipe_code)` — so blueprint AND spec layers reject it from one source. Message: "Pipe `<code>` sets `type = "PipeSignature"`, which is no longer a pipe type. Delete the `type` line — a pipe with no `type` and no implementation is a signature (contract only)."+- [x] Spec before-validator: same rejection (shared helper — free).+- [x] **Round-trip safety (new, load-bearing):** `PipeSignatureBlueprint.type` now `Field(exclude=True)` so a signature never serializes its tag. This keeps the `bundle_elaborator.py:94` dump→revalidate round-trip typeless (re-injected), while a **user-written** tag still reaches the validator and is rejected. Verified: signature dump has no `type`, round-trip routes to `PipeSignatureBlueprint`, explicit tag rejected, typeless still routes. (No direct single-pipe `PipeBlueprintUnion` validation exists — all pipe-dict validation flows through `validate_pipe_keys`, which re-injects.)+- [x] **Migration error categorized** → `UNKNOWN_PIPE_TYPE` (a *declared-but-invalid* type — an explicit `type = "PipeSignature"` DID declare a type; it is just no longer valid). Deliberately **not** `MISSING_PIPE_TYPE`, which the enum documents as the *no-type-declared* case — that stays reserved for the typeless-with-stray-field teaching error. The two markers map to the two distinct categories; pipe-code recovered from the shared ``Pipe `<code>``` prefix. *(This split corrected a first-pass mislabel — Louis flagged that a written tag can't be "missing.")*+- [x] **Single-pipe authoring (Phase-2 gap — decision: typeless→signature, Louis chose uniform):** `parse_pipe_spec(pipe_type: str | None)` now routes a typeless spec to `PipeSignatureSpec` and rejects `pipe_type="PipeSignature"` with the migration error; `pipe_cmd.py` allows absent `--type`; `pipe_type_to_spec_class` no longer lists `PipeSignature` (not a selectable type); both TOML renderers (`pipe_ops.pipe_spec_to_toml` **and** `pipe_cmd._pipe_spec_to_toml`) omit the `type` line for a signature.+- [x] Schema generator: `_normalize_type_on_pipe_definitions` (renamed from `_require_type_...`) now **removes `type` from the signature arm entirely** — an explicit tag fails the schema as an extra property under `additionalProperties: false`. Regenerated `derived/mthds_schema.json` (42 defs). Verified against the Draft-4 validator: typeless contract ✓, typeless+stray ✗, explicit tag ✗, concrete ✓, typo'd type ✗. `plxt-lint` passes over the migrated typeless fixtures.+- [x] Migrate the 8 bundle fixtures — `type = "PipeSignature"` line deleted from each (9 lines total; `write_research_brief.mthds` had 2). They are now the typeless regression corpus. Comments referencing the *concept* `PipeSignature` left intact (still accurate).+- [x] `pipe_signature_spec.py` `rendered_pretty`: drops the `Type: PipeSignature (...)` line → "Signature (contract only)". `pipe_category` field retained (taxonomy-refactor scope decision) but comment updated (no longer surfaced).+- [x] Tests: migration error asserted at blueprint, spec, and single-pipe layers; categorizer → `MISSING_PIPE_TYPE` (new `test_explicit_signature_tag_is_a_categorized_blueprint_item`); typeless single-pipe → signature + no-type TOML (both renderers); schema `test_explicit_signature_tag_is_rejected` + coverage-guard fixed for the typeless arm; all Phase-1/2 "explicit tag still accepted" guard tests **flipped** to rejection; inline-TOML test bundles migrated to typeless.+- [x] Docs — taught "omit the type" and removed the idiom **only where it appeared**: `signature-pipes.md` (Parameters table drops the `type` row + teaching lead-in; 3 examples de-tagged; "Replacing a signature" reworded), `index.md` (typeless framing), `pipelex/cli/agent_cli/CLAUDE.md` (`pipe` row). **The other plan-listed docs needed NO change** — `validate.md`, `agent-cli.md`, the error pages, and `error-model.md` reference the *concept* `PipeSignature` / `--allow-signatures` / `pending_signatures` / the runtime error, none of which teach the `type =` idiom (avoided gratuitous churn).+- [x] CHANGELOG.md — added `[Unreleased]` section (there was none) with the **breaking** entry + the MTHDS-JSON-Schema shape-change note (downstream copies re-sync gated on release).+- [x] `make agent-check` green (ruff/plxt/pyright-0/mypy-0/keyword-only) **and** full `make agent-test` green ("All tests passed").++### ⛔ CHECKPOINT 3 — STOP (final)++- [x] Commit the phase. Record SHA: **`843673324`** (amended from `702f2eff5` to fold the two review fixes — F1 categorizer split + F2 renderer `signature_for`).+- [x] Update the **Cold-start snapshot** below to the finished state.+- [x] **Fan out** a fresh Sonnet-5 `/code-review` sub-agent on this commit's diff (fresh, no inherited context; 10 finder angles + empirical REPL checks of the round-trip and Draft-4 schema). Triage:+ - **Angles verified clean:** the explicit-tag round-trip false-positive (traced every dump→revalidate; only `bundle_elaborator.py:94` exists, and the `exclude=True` keeps it typeless) and the Draft-4 `oneOf` disambiguation (ran the real generated schema through `jsonschema.Draft4Validator`). No bug in either — corroborates our own checks.+ - **F1 (major) — categorizer mislabel.** Explicit `type = "PipeSignature"` was bucketed `MISSING_PIPE_TYPE`, but a type *was* declared → should be `UNKNOWN_PIPE_TYPE` (per the enum's own docstring + the sibling `union_tag_invalid` branch that already buckets a typo'd type there). **Already caught by Louis independently and fixed** before the review returned → split `_categorize_typeless_pipe_error`: no-type→`MISSING_PIPE_TYPE`, retired-tag→`UNKNOWN_PIPE_TYPE`; test asserts the new type *and* that it is not also `MISSING_PIPE_TYPE`.+ - **F2 (minor) — renderer drift.** `pipe_ops.add_type_specific_fields` never emitted `signature_for` for a signature, while `pipe_cmd._add_type_specific_fields` does — silent loss of the hint through `pipe_ops.pipe_spec_to_toml` (pre-existing; that fn has no in-repo prod caller, only tests). **Fixed** — added the mirroring `PipeSignatureSpec` branch so the two renderers stay faithful copies; new `test_signature_toml_preserves_signature_for_hint` guards it.+ - No other correctness issues; reviewer confirmed the shared-helper design and the two before-validators are sound faithful mirrors.+- [x] **Gated cross-repo follow-up recorded:** the MTHDS JSON Schema copies in `mthds`, `vscode-pipelex`, `mthds-ui` now drift — the signature arm no longer carries a `type` property (an explicit `type = "PipeSignature"` fails those schemas too). Propagate via the `mthds-schema-sync` skill from the workspace root, **gated on the released pipelex version** — NOT on this branch. Flagged in the CHANGELOG `[Unreleased]` entry.+- [x] Hand back to the user for review / merge decision (do not push unprompted). **Phase 3 complete — the whole feature has landed. Awaiting Louis' merge call. Nothing pushed.**++---++## Invariants to preserve (regression guardrails — do not break)++- Reconciliation keys off `is_signature` class identity (`library_crate_factory.py:170-201`): concrete beats signature, contracts must match, two matching signatures tie-break deterministically. Untouched by this change — add a regression test, don't refactor.+- Strict validation still refuses bundles that contain a signature; `--allow-signatures` still dry-runs signatures as mocks (`validate_bundle.py`, `cli/commands/validate/_validate_core.py`). Keyed off the pending-signatures set / `is_signature`. Untouched.+- `PipeSignature` stays a valid **internal** discriminator value (the before-validator injects it); it is only rejected as a **user-written** value. Don't remove it from `valid_pipe_type_tags()` without confirming the injected value still passes `validate_pipe_type`.++---++## Cold-start snapshot (updated at each checkpoint)++> Keep this current so a fresh session can resume with zero re-investigation. Template to fill at each checkpoint:+>+> - **Phase reached / last green SHA:** …+> - **What changed and where the seam lives:** …+> - **What is verified (tests/gates run):** …+> - **Open threads / review findings deferred:** …+> - **Exact next action:** …++- **Phase reached / last green SHA:** **Phase 3 complete** — the breaking cleanup is done, the feature is fully landed (code + tests + docs green). Baseline = `04434f78586b328e080fd76b50bf46b00e0b6765`. Phase-1 = `e864b82486f00502206c6aa11b609b5256392e30`. Phase-2 = `b52b4e8df5a21c2d521d59bd1a08b1d65e028f28`. **Phase-3 commit SHA = `843673324`** (amended once to fold the cold-review F1/F2 fixes). Baseline still `04434f785`; nothing pushed.+- **What changed and where the seam lives (Phase 3, breaking):**+ - **Rejection is single-source.** `normalize_typeless_signature_section` (`pipe_blueprint.py`) now raises `explicit_signature_tag_migration_message(pipe_code)` when a raw dict names `type = "PipeSignature"`. Both `PipelexBundleBlueprint.validate_pipe_keys` and `PipelexBundleSpec.validate_pipe_keys` inherit it. `parse_pipe_spec` (single-pipe) rejects `pipe_type="PipeSignature"` with the same message-builder.+ - **Serialization invariant (the subtle bit).** `PipeSignatureBlueprint.type` is now `Field(exclude=True)`. A signature never serializes its tag, so (a) `.mthds` export stays typeless and (b) the `bundle_elaborator.py:94` dump→revalidate round-trip yields a typeless section that `validate_pipe_keys` re-injects — the tag only appears in a raw section when a **user** wrote it, which is exactly what we reject. No false positives.+ - **Schema.** `_normalize_type_on_pipe_definitions` deletes `type` from the signature arm (was: left optional). Explicit tag now fails the schema (extra property under `additionalProperties: false`). `derived/mthds_schema.json` regenerated.+ - **Single-pipe authoring (Louis' decision: uniform typeless→signature).** `parse_pipe_spec(pipe_type: str | None)`; `pipe_cmd.py` allows absent `--type`; `PipeSignature` dropped from `pipe_type_to_spec_class`; both TOML renderers omit the `type` line for a signature.+ - **Categorizer.** Migration error → `UNKNOWN_PIPE_TYPE` (a declared-but-invalid type; distinct from the typeless-only `MISSING_PIPE_TYPE`). Second marker `_EXPLICIT_SIGNATURE_TAG_MARKER`; pipe-code from the shared ``Pipe `<code>``` prefix.+- **What is verified (tests/gates run):** `make agent-check` fully green (ruff/plxt/pyright-0/mypy-0/keyword-only; schema regenerated + `plxt-lint` clean over the migrated typeless fixtures). Targeted builder/language/signature/libraries/cli + pipeline/cli/e2e suites green. Full `make agent-test` green ("All tests passed").+- **Invariants confirmed untouched:** reconciliation keys off `is_signature`; `PipeSignature` stays a valid **internal** discriminator (injected value still passes `validate_pipe_type` — `valid_pipe_type_tags()` still lists it); strict/`--allow-signatures` validation semantics unchanged.+- **Open threads / review findings deferred (both in `wip/pipe-signature-not-a-type.md` → "Deferred follow-ups"):**+ 1. Categorizing the bare pydantic residual for a typeless section missing a *required* contract field (pre-existing general gap; safety invariant guarded by a test).+ 2. **New (Phase-3 finding):** spec-layer `PipeSpec.inputs` is **required**, unlike the optional blueprint `inputs` — so a no-inputs signature is authorable at the blueprint/`.mthds` level but not via the spec/single-pipe path. Pre-existing, orthogonal to the tag removal; fixing it (make spec `inputs` optional) touches every spec — deferred.+- **Exact next action:** Checkpoint-3 cold `/code-review` fan-out on the Phase-3 commit diff (fresh Sonnet-5, no inherited context), triage findings, record the cross-repo schema-sync follow-up, hand back to Louis for merge decision. **This is the final phase — nothing pushed.**diff --git a/docs/building-methods/pipes/index.md b/docs/building-methods/pipes/index.mdindex 1f4d52719..bd8b1e060 100644--- a/docs/building-methods/pipes/index.md+++ b/docs/building-methods/pipes/index.md@@ -15,7 +15,7 @@ A pipeline is composed of pipes. There are two fundamental types of pipes you wi* **[Pipe Operators](./pipe-operators/index.md)**: These are the "workers" of your pipeline. They perform concrete actions like calling an LLM (`PipeLLM`), extracting text from a document (`PipeExtract`), searching the web (`PipeSearch`), or running a Python function (`PipeFunc`). Each operator is a specialized tool designed for a specific task.* **[Pipe Controllers](./pipe-controllers/index.md)**: These are the "managers" of your pipeline. They don't perform tasks themselves but orchestrate the execution flow of other pipes. They define the logic of your method, such as running pipes in sequence (`PipeSequence`), in parallel (`PipeParallel`), or based on a condition (`PipeCondition`).-A third, design-time-only kind of pipe — **[Signature Pipes](./signature-pipes.md)** (`PipeSignature`) — lets you stub a pipe's contract (inputs and output) without an implementation. Signatures dry-run as mocks under `--allow-signatures`, so you can sketch a pipeline top-down before writing each operator. Strict validation refuses pipelines that still depend on a signature.+A third, design-time-only kind of pipe — **[Signature Pipes](./signature-pipes.md)** — lets you stub a pipe's contract (inputs and output) by declaring it with no `type` and no implementation: a typeless, contract-only pipe *is* a signature. Signatures dry-run as mocks under `--allow-signatures`, so you can sketch a pipeline top-down before writing each operator. Strict validation refuses pipelines that still depend on a signature.## Designing a Pipeline: Composition in MTHDSdiff --git a/docs/building-methods/pipes/signature-pipes.md b/docs/building-methods/pipes/signature-pipes.mdindex ce6dcce33..dfa74d185 100644--- a/docs/building-methods/pipes/signature-pipes.md+++ b/docs/building-methods/pipes/signature-pipes.md@@ -26,9 +26,10 @@ Signatures let an agent (or a human author) build a complete, dry-runnable bundl## MTHDS Parameters+A signature has **no `type`** — omitting the type *is* what makes a pipe a signature. A `[pipe.x]` section that declares only the contract below (and nothing else) is a signature. Adding any other field means you are describing an implementation, which must name its `type`; and writing `type = "PipeSignature"` explicitly is an error (`PipeSignature` is not a pipe type — delete the line).+| Parameter | Type | Description | Required || ------------------- | ------ | ------------------------------------------------------------------------------------------------------------ | -------- |-| `type` | string | Always `"PipeSignature"`. | Yes || `description` | string | Human-readable purpose of the contract. | Yes || `inputs` | object | Mapping of input variable names to concept references. Multiplicity is supported (`Doc[]`, `Image[3]`). | No || `output` | string | The concept the signature promises to produce. Multiplicity is supported. | Yes |@@ -50,13 +51,12 @@ main_pipe = "summarize_doc"SigDocument = "A document concept used for testing signatures."[pipe.summarize_doc]-type = "PipeSignature"description = "Produces a summary of a document (contract only)."inputs = { doc = "SigDocument" }output = "Text"```-Validating this in strict mode fails (the main pipe *is* a signature). Validating it with `--allow-signatures` succeeds and dry-runs to a mock `Text`.+No `type` line — that is what makes `summarize_doc` a signature. Validating this in strict mode fails (the main pipe *is* a signature). Validating it with `--allow-signatures` succeeds and dry-runs to a mock `Text`.### A signature inside a `PipeSequence`@@ -78,7 +78,6 @@ output = "Text"prompt = "Extract text from $doc."[pipe.summarize_extracted]-type = "PipeSignature"description = "Summarize extracted text (contract only)."inputs = { extracted = "Text" }output = "MixSummary"@@ -110,7 +109,6 @@ FuseImage = "An image."FuseReport = "A report."[pipe.fuse_docs_and_images]-type = "PipeSignature"description = "Combine docs and exactly 3 images (contract only)."inputs = { docs = "FuseDoc[]", images = "FuseImage[3]" }output = "FuseReport"@@ -143,7 +141,7 @@ When `--all` runs in strict mode, signature pipes themselves are skipped during## 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.+When you are ready to implement, add a `type` to the pipe (a signature has none) and 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.```toml[pipe.summarize_extracted]diff --git a/pipelex/builder/bundle_spec.py b/pipelex/builder/bundle_spec.pyindex d1b412e05..6e371d9c8 100644--- a/pipelex/builder/bundle_spec.py+++ b/pipelex/builder/bundle_spec.py@@ -1,4 +1,4 @@-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Any, castfrom pydantic import ConfigDict, Field, ValidationError, field_validator, model_validatorfrom rich.console import Group@@ -13,6 +13,8 @@ from pipelex.core.bundles.pipe_sorter import sort_pipes_by_dependenciesfrom pipelex.core.bundles.pipelex_bundle_blueprint import PipeBlueprintUnion, PipelexBundleBlueprintfrom pipelex.core.domains.exceptions import DomainCodeErrorfrom pipelex.core.domains.validation import validate_domain_code+from pipelex.core.pipes.pipe_blueprint import SIGNATURE_ONLY_KEYS, normalize_typeless_signature_section+from pipelex.core.pipes.validation import is_pipe_code_validfrom pipelex.core.stuffs.structured_content import StructuredContentfrom pipelex.tools.misc.pretty import PrettyPrintablefrom pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error@@ -20,6 +22,14 @@ from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_errorif TYPE_CHECKING:from pipelex.core.concepts.concept_blueprint import ConceptBlueprint+# The spec layer's typeless-signature allowlist is the shared blueprint contract set adapted to the+# spec's actual field surface: drop `source` (a blueprint-only field — `PipeSpec` has no `source` and+# forbids extras, so a typeless section carrying it must hit the teaching error, not be injected and+# then rejected with a raw pydantic message) and add the structural `pipe_code` field (the blueprint+# uses the dict key; the spec section carries it explicitly). Any other key on a typeless section+# still triggers the teaching error.+SIGNATURE_ONLY_SPEC_KEYS: frozenset[str] = (SIGNATURE_ONLY_KEYS - {"source"}) | {"pipe_code"}+class PipelexBundleSpec(StructuredContent):"""Complete spec of a Pipelex bundle TOML definition.@@ -72,6 +82,34 @@ class PipelexBundleSpec(StructuredContent):raise ValueError(msg) from excreturn domain_code+ @field_validator("pipe", mode="before")+ @classmethod+ def validate_pipe_keys(cls, pipe: Any) -> Any:+ """Validate pipe codes and normalize typeless sections before the discriminated union runs.++ Full mirror of `PipelexBundleBlueprint.validate_pipe_keys`: each dict key (the pipe code) is+ rejected up front if not snake_case, then each section is normalized. A spec `[pipe.x]`+ section with no `type` whose keys are exactly the signature contract+ (`SIGNATURE_ONLY_SPEC_KEYS`) has the internal `PipeSignature` discriminator injected, so the+ union routes it to `PipeSignatureSpec` — the author never writes the tag. A typeless section+ that declares anything more is describing an implementation without naming its type, which is+ a hard error. A section that already names a `type` (or is an already-built spec instance+ rather than a raw dict) passes through untouched.+ """+ if pipe is None:+ return None+ if not isinstance(pipe, dict):+ # Let the field type raise its own "should be a dict" error.+ return pipe+ typed_pipe = cast("dict[Any, Any]", pipe)+ normalized: dict[Any, Any] = {}+ for pipe_code, pipe_section in typed_pipe.items():+ if isinstance(pipe_code, str) and not is_pipe_code_valid(pipe_code=pipe_code):+ msg = f"Pipe code '{pipe_code}' is not a valid pipe code. Must be in snake_case."+ raise ValueError(msg)+ normalized[pipe_code] = normalize_typeless_signature_section(pipe_code, pipe_section=pipe_section, allowed_keys=SIGNATURE_ONLY_SPEC_KEYS)+ return normalized+@model_validator(mode="after")def validate_main_pipe(self) -> "PipelexBundleSpec":if not self.pipe or (self.main_pipe not in self.pipe):diff --git a/pipelex/builder/operations/pipe_ops.py b/pipelex/builder/operations/pipe_ops.pyindex 0f30b1f73..e892f989d 100644--- a/pipelex/builder/operations/pipe_ops.py+++ b/pipelex/builder/operations/pipe_ops.py@@ -11,6 +11,7 @@ import tomlkitfrom pydantic import ValidationErrorfrom tomlkit.items import Table+from pipelex.builder.bundle_spec import SIGNATURE_ONLY_SPEC_KEYSfrom pipelex.builder.pipe.exceptions import PipeSpecErrorfrom pipelex.builder.pipe.pipe_batch_spec import PipeBatchSpecfrom pipelex.builder.pipe.pipe_compose_spec import PipeComposeSpec@@ -22,9 +23,15 @@ from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpecfrom pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpecfrom pipelex.builder.pipe.pipe_search_spec import PipeSearchSpecfrom pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec+from pipelex.builder.pipe.pipe_signature_spec import PipeSignatureSpecfrom pipelex.builder.pipe.pipe_spec import PipeSpecfrom pipelex.builder.pipe.pipe_spec_map import pipe_type_to_spec_classfrom pipelex.builder.pipe.pipe_structure_spec import PipeStructureSpec+from pipelex.core.pipes.pipe_blueprint import (+ PIPE_SIGNATURE_TYPE_TAG,+ explicit_signature_tag_migration_message,+ normalize_typeless_signature_section,+)# Aliases that agents may use instead of "pipe_code". First found is promoted when canonical key is absent; extras are dropped._PIPE_CODE_ALIASES = ("pipe", "the_pipe_code", "code", "name", "pipe_name", "pipe_ref")@@ -86,23 +93,96 @@ def _normalize_prompt_aliases(data: dict[str, Any]) -> None:data.pop(alias)-def parse_pipe_spec(spec_data: Any, *, pipe_type: str) -> PipeSpec:+def _normalize_output(data: dict[str, Any]) -> Any | None:+ """Canonicalize output authoring aliases in-place: promote ``output_concept`` / ``output_type`` →+ ``output``, and flatten a dict-shaped ``output`` to its concept string.++ Returns the displaced original ``output`` value when an alias overrode an existing ``output`` (so a+ typed caller can retry with the alias then fall back to the original), else ``None``. Runs for both+ the typeless-signature and typed paths so the same authoring conveniences apply to signatures.+ """+ # Accept output aliases (e.g. "output_concept", "output_type") for "output".+ # When both "output" and an alias coexist, try the alias value first (agents often put+ # the correct concept name in the alias), falling back to the original "output" value.+ output_fallback: Any | None = None+ for output_alias in _OUTPUT_ALIASES:+ if output_alias not in data:+ continue+ alias_value = data.pop(output_alias)+ if "output" not in data:+ data["output"] = alias_value+ else:+ output_fallback = data["output"]+ data["output"] = alias_value+ # First alias wins — drop any remaining aliases without using them.+ for remaining_alias in _OUTPUT_ALIASES:+ data.pop(remaining_alias, None)+ break++ # Accept output as dict → extract the concept string+ # Agents sometimes structure the output like inputs (as a dict).+ # Handle {"type": "ConceptName"} and single-item dicts like {"result": "Text"}.+ if "output" in data and isinstance(data["output"], dict):+ output_dict: dict[str, Any] = data["output"]+ if "concept_ref" in output_dict:+ data["output"] = output_dict["concept_ref"]+ elif "type" in output_dict:+ data["output"] = output_dict["type"]+ elif len(output_dict) == 1:+ data["output"] = next(iter(output_dict.values()))+ return output_fallback+++def parse_pipe_spec(spec_data: Any, *, pipe_type: str | None) -> PipeSpec:"""Parse and validate a PipeSpec from JSON-like data.Args:spec_data: Raw data for the pipe spec (untrusted JSON-like input).- pipe_type: The type of pipe (e.g., "PipeLLM", "PipeSequence").+ pipe_type: The type of pipe (e.g., "PipeLLM", "PipeSequence"), or ``None`` when the caller+ supplied no type. A typeless spec is a signature when it declares only the contract+ (``description``, ``inputs``, ``output``, ``signature_for``), else a teaching error. An+ explicit ``"PipeSignature"`` is rejected with the migration error — a signature has no type.Returns:Validated PipeSpec instance of the correct type.Raises:- ValueError: If the pipe type is invalid.+ ValueError: If the pipe type is invalid, or the retired ``"PipeSignature"`` tag is passed, or a+ typeless spec declares more than the contract.PipeSpecError: If the top-level value is not a mapping, ``steps`` /``branches`` is not a list, or an entry within them is not a mapping.Carries the INPUT error domain.ValidationError: If Pydantic validation of the assembled spec fails."""+ # Validate the top-level shape first so a non-mapping caller input (scalar / list / None) surfaces+ # as a typed, INPUT-domain PipeSpecError instead of a bare TypeError / ValueError, and so the+ # typeless-signature routing below can operate on a dict.+ if not isinstance(spec_data, dict):+ msg = f"Pipe spec must be a mapping, got {type(spec_data).__name__}"+ raise PipeSpecError(msg)+ # Work on a copy to avoid mutating the caller's dict.+ spec_data = dict(cast("dict[str, Any]", spec_data))++ # Canonicalize pipe_code aliases up front so the typeless-signature routing and the migration+ # message both see the real pipe code.+ _normalize_pipe_code_aliases(spec_data)++ # Canonicalize output authoring aliases (output_concept/output_type, dict output) up front so both+ # the typeless-signature path and every typed pipe see a canonical `output` — a signature keeps the+ # same authoring conveniences as typed pipes. The typed path reuses the returned fallback for its+ # retry-then-fall-back below; the typeless path takes the canonical value directly.+ output_fallback = _normalize_output(spec_data)++ # A signature is typeless. Reject the retired explicit `type = "PipeSignature"` tag, and route a+ # typeless contract-only spec to `PipeSignatureSpec` via the shared normalizer (which injects the+ # internal tag, or raises the same teaching error as the bundle layer for a stray field). This+ # mirrors `PipelexBundleSpec.validate_pipe_keys` for the single-pipe authoring surface.+ if pipe_type == PIPE_SIGNATURE_TYPE_TAG:+ raise ValueError(explicit_signature_tag_migration_message(spec_data.get("pipe_code")))+ if pipe_type is None:+ normalized = normalize_typeless_signature_section(spec_data.get("pipe_code"), pipe_section=spec_data, allowed_keys=SIGNATURE_ONLY_SPEC_KEYS)+ return PipeSignatureSpec.model_validate(normalized)+if pipe_type not in pipe_type_to_spec_class:valid_types = list(pipe_type_to_spec_class.keys())msg = f"Invalid pipe type '{pipe_type}'. Must be one of: {valid_types}"@@ -110,23 +190,9 @@ def parse_pipe_spec(spec_data: Any, *, pipe_type: str) -> PipeSpec:spec_class = pipe_type_to_spec_class[pipe_type]- # Validate the top-level shape before iterating so a non-mapping caller input- # (scalar / list / None) surfaces as a typed, INPUT-domain PipeSpecError- # instead of a bare TypeError / ValueError from ``dict(...)`` below.- if not isinstance(spec_data, dict):- msg = f"Pipe spec must be a mapping, got {type(spec_data).__name__}"- raise PipeSpecError(msg)- spec_data = cast("dict[str, Any]", spec_data)-- # Work on a copy to avoid mutating the caller's dict- spec_data = dict(spec_data)-- # Add type to spec_data if not present+ # Add type to spec_dataspec_data["type"] = pipe_type- # Accept common aliases for "pipe_code" at the top level- _normalize_pipe_code_aliases(spec_data)-# Accept common aliases for "prompt" (e.g. "prompt_template")_normalize_prompt_aliases(spec_data)@@ -148,38 +214,8 @@ def parse_pipe_spec(spec_data: Any, *, pipe_type: str) -> PipeSpec:else:spec_data.pop("expression")- # Accept output aliases (e.g. "output_concept", "output_type") for "output".- # When both "output" and an alias coexist, try the alias value first (agents often put- # the correct concept name in the alias), falling back to the original "output" value.- output_fallback: Any | None = None- for output_alias in _OUTPUT_ALIASES:- if output_alias not in spec_data:- continue- alias_value = spec_data.pop(output_alias)- if "output" not in spec_data:- spec_data["output"] = alias_value- else:- output_fallback = spec_data["output"]- spec_data["output"] = alias_value- # First alias wins — drop any remaining aliases without using them.- for remaining_alias in _OUTPUT_ALIASES:- spec_data.pop(remaining_alias, None)- break-- # Accept output as dict → extract the concept string- # Agents sometimes structure the output like inputs (as a dict).- # Handle {"type": "ConceptName"} and single-item dicts like {"result": "Text"}.- if "output" in spec_data and isinstance(spec_data["output"], dict):- output_dict: dict[str, Any] = spec_data["output"]- if "concept_ref" in output_dict:- spec_data["output"] = output_dict["concept_ref"]- elif "type" in output_dict:- spec_data["output"] = output_dict["type"]- elif len(output_dict) == 1:- spec_data["output"] = next(iter(output_dict.values()))-- # When an output alias conflicted with an existing "output", try the alias value first- # and fall back to the original value if validation fails.+ # When an output alias conflicted with an existing "output" (see `_normalize_output` above), try the+ # alias value first and fall back to the original value if validation fails.if output_fallback is not None:try:return spec_class.model_validate(spec_data)@@ -297,6 +333,12 @@ def add_type_specific_fields(pipe_spec: PipeSpec, *, pipe_table: Table) -> None:elif isinstance(pipe_spec, PipeFuncSpec):pipe_table.add("function_name", pipe_spec.function_name)+ elif isinstance(pipe_spec, PipeSignatureSpec):+ # A signature is typeless, but the optional `signature_for` hint still round-trips. Mirrors+ # `pipe_cmd._add_type_specific_fields` so the two TOML renderers stay faithful copies.+ if pipe_spec.signature_for is not None:+ pipe_table.add("signature_for", pipe_spec.signature_for)+def pipe_spec_to_toml(pipe_spec: PipeSpec) -> str:"""Convert a PipeSpec to TOML string format.@@ -310,8 +352,10 @@ def pipe_spec_to_toml(pipe_spec: PipeSpec) -> str:doc = tomlkit.document()pipe_item_table = tomlkit.table()- # Add type- pipe_item_table.add("type", pipe_spec.type)+ # Add type — a signature is typeless (no type line; omitting the type IS the signature); every+ # concrete pipe names its type.+ if not isinstance(pipe_spec, PipeSignatureSpec):+ pipe_item_table.add("type", pipe_spec.type)# Add descriptionpipe_item_table.add("description", pipe_spec.description)diff --git a/pipelex/builder/pipe/pipe_signature_spec.py b/pipelex/builder/pipe/pipe_signature_spec.pyindex 54e742aa0..e2a75c603 100644--- a/pipelex/builder/pipe/pipe_signature_spec.py+++ b/pipelex/builder/pipe/pipe_signature_spec.py@@ -44,12 +44,18 @@ class PipeSignatureSpec(PipeSpec):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"+ # Internal `PipeSpecUnion` discriminator, never written by the author and never rendered as a+ # "type" line (a signature is typeless). `SkipJsonSchema` keeps it out of the authoring schema;+ # `exclude=True` keeps it out of `model_dump()` so a dump→revalidate round-trip stays typeless and+ # re-injects the tag (mirrors `PipeSignatureBlueprint.type`) instead of tripping the migration error.+ type: SkipJsonSchema[Literal["PipeSignature"]] = Field(default="PipeSignature", exclude=True)+ # Spec-layer authoring tag only: NOT propagated by `to_blueprint()`, which leaves the blueprint+ # (and runtime) at `pipe_category = None` because a signature is outside the executable taxonomy.+ # Retained per the scope decision in wip/recursivity/signature-taxonomy-refactor.md; no longer+ # surfaced in `rendered_pretty` (a signature now renders as "Signature (contract only)", with no+ # type/category line). `exclude=True` (like `type`) keeps it out of `model_dump()` so it is not a+ # stray key on a round-trip.+ pipe_category: SkipJsonSchema[Literal["PipeSignature"]] = Field(default="PipeSignature", exclude=True)signature_for: PipeType | None = Field(default=None,description="Intended downstream pipe type when this signature is implemented (optional hint for agents).",@@ -70,7 +76,7 @@ class PipeSignatureSpec(PipeSpec):if title:pipe_group.renderables.append(Text(title, style="bold"))pipe_group.renderables.append(Text.from_markup(f"Pipe Signature: [red]{escape(self.pipe_code)}[/red]\n", style="bold"))- pipe_group.renderables.append(Text.from_markup(f"Type: [bold magenta]{self.type}[/bold magenta] ({self.pipe_category})\n"))+ pipe_group.renderables.append(Text.from_markup("[bold magenta]Signature[/bold magenta] (contract only)\n"))pipe_group.renderables.append(Text.from_markup(f"Description: [yellow italic]{escape(self.description)}[/yellow italic]\n"))if not self.inputs:diff --git a/pipelex/builder/pipe/pipe_spec_map.py b/pipelex/builder/pipe/pipe_spec_map.pyindex ef4a45c45..3406e7863 100644--- a/pipelex/builder/pipe/pipe_spec_map.py+++ b/pipelex/builder/pipe/pipe_spec_map.py@@ -8,10 +8,13 @@ from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpecfrom pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpecfrom pipelex.builder.pipe.pipe_search_spec import PipeSearchSpecfrom pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec-from pipelex.builder.pipe.pipe_signature_spec import PipeSignatureSpecfrom pipelex.builder.pipe.pipe_spec import PipeSpecfrom pipelex.builder.pipe.pipe_structure_spec import PipeStructureSpec+# Concrete, user-selectable pipe types only. `PipeSignature` is deliberately absent: a signature is+# not a selectable type — it is the typeless case. The single-pipe authoring path (`parse_pipe_spec`)+# routes a typeless spec to `PipeSignatureSpec` directly and rejects an explicit `type = "PipeSignature"`+# with a migration error before ever consulting this map.pipe_type_to_spec_class: dict[str, type[PipeSpec]] = {"PipeFunc": PipeFuncSpec,"PipeImgGen": PipeImgGenSpec,@@ -24,5 +27,4 @@ pipe_type_to_spec_class: dict[str, type[PipeSpec]] = {"PipeCondition": PipeConditionSpec,"PipeParallel": PipeParallelSpec,"PipeSequence": PipeSequenceSpec,- "PipeSignature": PipeSignatureSpec,}diff --git a/pipelex/cli/agent_cli/CLAUDE.md b/pipelex/cli/agent_cli/CLAUDE.mdindex 8fe7425b6..9a349288c 100644--- a/pipelex/cli/agent_cli/CLAUDE.md+++ b/pipelex/cli/agent_cli/CLAUDE.md@@ -82,7 +82,7 @@ commands/| `lint` | Lints a .mthds/.toml/.plx file for errors (delegates to plxt) || `inputs` | Generates example input JSON for a pipe/bundle/method (pipe\|bundle\|method subcommands) || `concept` | Converts a JSON concept spec into raw TOML (stdout) |-| `pipe` | Converts a JSON pipe spec (typed) into raw TOML (stdout) |+| `pipe` | Converts a JSON pipe spec into raw TOML (stdout). A spec with a `type` (via `--type` or a `type` key) is that concrete pipe; a **typeless** spec (no `type`) is a signature and renders a `[pipe.x]` section with no type line. An explicit `type = "PipeSignature"` is rejected with a migration error — `PipeSignature` is not a type. || `models` | Lists available model presets, aliases, and waterfalls. `--format markdown\|json` (success, default: markdown) + `--error-format markdown\|json` (errors, defaults to `--format`'s value) || `check-model` | Validates a model reference and suggests alternatives if invalid. `--type`/`-t` for model category, `--format markdown\|json` (success, default: markdown) + `--error-format markdown\|json` (errors, defaults to `--format`'s value) || `doctor` | Checks config, credentials, models health. `--global`/`-g` for global dir. `--format markdown\|json` (success, default: markdown) + `--error-format markdown\|json` (errors, defaults to `--format`'s value) |diff --git a/pipelex/cli/agent_cli/commands/pipe_cmd.py b/pipelex/cli/agent_cli/commands/pipe_cmd.pyindex 6d8fa3d75..93179bf95 100644--- a/pipelex/cli/agent_cli/commands/pipe_cmd.py+++ b/pipelex/cli/agent_cli/commands/pipe_cmd.py@@ -45,8 +45,10 @@ def _pipe_spec_to_toml(pipe_spec: PipeSpec) -> str:doc = tomlkit.document()pipe_item_table = tomlkit.table()- # Add type- pipe_item_table.add("type", pipe_spec.type)+ # Add type — a signature is typeless (no type line; omitting the type IS the signature); every+ # concrete pipe names its type.+ if not isinstance(pipe_spec, PipeSignatureSpec):+ pipe_item_table.add("type", pipe_spec.type)# Add descriptionpipe_item_table.add("description", format_toml_string(pipe_spec.description))@@ -184,7 +186,13 @@ def _add_type_specific_fields(pipe_spec: PipeSpec, *, pipe_table: tomlkit.TOMLDodef pipe_cmd(pipe_type: Annotated[str | None,- typer.Option("--type", "--pipe-type", "--pipe_type", "-t", help=f"Pipe type. Must be one of: {list(pipe_type_to_spec_class)}"),+ typer.Option(+ "--type",+ "--pipe-type",+ "--pipe_type",+ "-t",+ help=f"Pipe type. Must be one of: {list(pipe_type_to_spec_class)}. Omit for a signature (contract only, no type).",+ ),] = None,spec: Annotated[str | None,@@ -226,9 +234,19 @@ def pipe_cmd(]}+ PipeSignature (contract only — omit the type): a pipe with no type and no implementation is a+ signature. Omit --type (and any "type" key) and declare only the contract:+ {+ "pipe_code": "summarize_doc",+ "description": "Produces a summary of a document.",+ "inputs": {"doc": "Document"},+ "output": "Text"+ }+Examples:pipelex-agent pipe --type PipeLLM --spec '{"pipe_code": "summarize", ...}'pipelex-agent pipe --type PipeSequence --spec-file pipe.json+ pipelex-agent pipe --spec '{"pipe_code": "summarize_doc", "description": "...", "output": "Text"}'"""# Validate that exactly one of spec or spec_file is providedif spec is None and spec_file is None:@@ -256,14 +274,26 @@ def pipe_cmd(elif "pipe_type" in spec_data:spec_data.pop("pipe_type")- # Resolve pipe type: CLI option takes precedence, then extract from spec JSON- resolved_pipe_type: str+ # Resolve pipe type: CLI option takes precedence, then extract from spec JSON, else None (typeless).+ # A typeless spec is a signature — parse_pipe_spec routes it to PipeSignatureSpec (or raises a+ # teaching error if it declares more than the contract). An explicit "PipeSignature" is rejected+ # there with a migration error — a signature has no type.+ resolved_pipe_type: str | Noneif pipe_type is not None:resolved_pipe_type = pipe_typeelif "type" in spec_data:- resolved_pipe_type = spec_data.pop("type")+ raw_pipe_type = spec_data.pop("type")+ if raw_pipe_type is None:+ # A signature is authored by OMITTING the `type` key — an explicit null is not the same as+ # absent, and must not silently collapse to a typeless signature.+ agent_error(+ "A JSON `type` key cannot be null. Delete the `type` key — a pipe with no `type` and no "+ "implementation is a signature (contract only).",+ error_type="ArgumentError",+ )+ resolved_pipe_type = raw_pipe_typeelse:- agent_error("Pipe type must be provided either via --type or as 'type' in the JSON spec", error_type="ArgumentError")+ resolved_pipe_type = None# Validate and convert spectry:diff --git a/pipelex/core/bundles/pipelex_bundle_blueprint.py b/pipelex/core/bundles/pipelex_bundle_blueprint.pyindex 4756aa033..290f7ae44 100644--- a/pipelex/core/bundles/pipelex_bundle_blueprint.py+++ b/pipelex/core/bundles/pipelex_bundle_blueprint.py@@ -1,4 +1,4 @@-from typing import Annotated+from typing import Annotated, Any, castfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validatorfrom pydantic.json_schema import SkipJsonSchema@@ -9,6 +9,7 @@ from pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.concepts.validation import is_concept_code_validfrom pipelex.core.domains.exceptions import DomainCodeErrorfrom pipelex.core.domains.validation import validate_domain_code+from pipelex.core.pipes.pipe_blueprint import normalize_typeless_signature_sectionfrom pipelex.core.pipes.validation import is_pipe_code_validfrom pipelex.core.pipes.variable_multiplicity import parse_concept_with_multiplicityfrom pipelex.pipe_controllers.batch.pipe_batch_blueprint import PipeBatchBlueprint@@ -124,14 +125,29 @@ class PipelexBundleBlueprint(BaseModel):@field_validator("pipe", mode="before")@classmethod- def validate_pipe_keys(cls, pipe: dict[str, PipeBlueprintUnion] | None) -> dict[str, PipeBlueprintUnion] | None:+ def validate_pipe_keys(cls, pipe: Any) -> Any:+ """Validate pipe codes and normalize typeless sections before the discriminated union runs.++ A `[pipe.x]` section with no `type` whose keys are exactly the signature contract+ (`SIGNATURE_ONLY_KEYS`) is normalized by injecting the internal `PipeSignature`+ discriminator, so the union routes it to `PipeSignatureBlueprint` — the author never writes+ the tag. A typeless section that declares anything more is describing an implementation+ without naming its type, which is a hard error. A section that already names a `type` (or is+ an already-built blueprint instance rather than a raw dict) passes through untouched.+ """if pipe is None:return None- for pipe_code in pipe:- if not is_pipe_code_valid(pipe_code=pipe_code):+ if not isinstance(pipe, dict):+ # Let the field type raise its own "should be a dict" error.+ return pipe+ typed_pipe = cast("dict[Any, Any]", pipe)+ normalized: dict[Any, Any] = {}+ for pipe_code, pipe_section in typed_pipe.items():+ if isinstance(pipe_code, str) and not is_pipe_code_valid(pipe_code=pipe_code):msg = f"Pipe code '{pipe_code}' is not a valid pipe code. Must be in snake_case."raise ValueError(msg)- return pipe+ normalized[pipe_code] = normalize_typeless_signature_section(pipe_code, pipe_section=pipe_section)+ return normalized@model_validator(mode="after")def validate_main_pipe(self) -> "PipelexBundleBlueprint":diff --git a/pipelex/core/interpreter/validation_error_categorizer.py b/pipelex/core/interpreter/validation_error_categorizer.pyindex dd5cebdb1..4770057eb 100644--- a/pipelex/core/interpreter/validation_error_categorizer.py+++ b/pipelex/core/interpreter/validation_error_categorizer.py@@ -14,6 +14,15 @@ from pipelex.core.pipes.handle_pipe_errors import extract_wrapped_pipe_validatioPIPELEX_BUNDLE_BLUEPRINT_DOMAIN_FIELD = "domain"PIPELEX_BUNDLE_BLUEPRINT_SOURCE_FIELD = "source"+# Distinctive fragments of the two type-tag errors raised by the `pipe` before-validators (via+# `normalize_typeless_signature_section` in `pipe_blueprint.py`, shared by the blueprint and spec+# layers). Kept in sync with those single-source messages. They map to DIFFERENT structured+# categories — no-type-declared is `MISSING_PIPE_TYPE`, the retired-tag-declared is `UNKNOWN_PIPE_TYPE`+# (a declared-but-invalid type) — and both name the pipe as ``Pipe `<code>``` so the pipe code is+# recoverable from the message. See `_categorize_typeless_pipe_error`.+_MISSING_PIPE_TYPE_MARKER = "has no `type` but declares"+_EXPLICIT_SIGNATURE_TAG_MARKER = "is no longer a pipe type"+def _extract_variable_names_from_message(message: str) -> list[str] | None:"""Extract variable names from error messages like 'Missing input variable(s): var1, var2.'"""@@ -72,6 +81,49 @@ def _categorize_input_validation_error(return None+def _categorize_typeless_pipe_error(+ message: str,+ *,+ domain: str | None,+ source: str | None,+) -> PipelexBundleBlueprintValidationErrorData | None:+ """Categorize the two type-tag errors raised by the `pipe` before-validator.++ They are distinct failure modes and get distinct `error_type`s:++ - A `[pipe.x]` section with **no** `type` that declares more than the signature contract →+ `MISSING_PIPE_TYPE` (the author is describing an implementation but named no type).+ - A section that writes the retired explicit `type = "PipeSignature"` → `UNKNOWN_PIPE_TYPE` (a+ `type` **was** declared, but it is no longer a valid pipe type — the same category as a typo'd+ type; the message carries the specific migration guidance).++ Both are raised on the aggregate `pipe` field, so their pydantic `loc` carries no pipe code —+ recover it from the shared ``Pipe `<code>``` prefix so agent/API surfaces get a clean, located item.++ Args:+ message: The error message from the validation+ domain: Domain code+ source: Source file path++ Returns:+ Categorized error data, or None if not one of the two type-tag errors+ """+ if _MISSING_PIPE_TYPE_MARKER in message:+ error_type = PipeValidationErrorType.MISSING_PIPE_TYPE+ elif _EXPLICIT_SIGNATURE_TAG_MARKER in message:+ error_type = PipeValidationErrorType.UNKNOWN_PIPE_TYPE+ else:+ return None+ pipe_code_match = re.search(r"Pipe `([^`]+)`", message)+ return PipelexBundleBlueprintValidationErrorData(+ error_type=error_type,+ domain_code=domain,+ source=source,+ pipe_code=pipe_code_match.group(1) if pipe_code_match else None,+ message=message,+ )++def _categorize_syntax_validation_error(message: str,*,@@ -252,6 +304,17 @@ def categorize_blueprint_validation_error(message=message,)+ # Type-tag errors from the before-validator (raised on the aggregate `pipe` field, so the+ # pipe_code is recovered from the message rather than the bare `loc`): a typeless section+ # declaring more than the contract → MISSING_PIPE_TYPE; the retired explicit tag → UNKNOWN_PIPE_TYPE.+ missing_type_error = _categorize_typeless_pipe_error(+ message=message,+ domain=domain,+ source=source,+ )+ if missing_type_error:+ return missing_type_error+# Try to categorize input validation errors (missing/unused inputs)input_error = _categorize_input_validation_error(message=message,diff --git a/pipelex/core/pipes/exceptions.py b/pipelex/core/pipes/exceptions.pyindex 0d3a2a13e..028de102b 100644--- a/pipelex/core/pipes/exceptions.py+++ b/pipelex/core/pipes/exceptions.py@@ -111,6 +111,10 @@ class PipeValidationErrorType(StrEnum):LLM_OUTPUT_CANNOT_BE_IMAGE = "llm_output_cannot_be_image"INVALID_PIPE_CODE_SYNTAX = "invalid_pipe_code_syntax"UNKNOWN_PIPE_TYPE = "unknown_pipe_type"+ # A `[pipe.x]` section declared no `type` yet carries fields beyond the signature contract+ # (`description`, `inputs`, `output`). The author is describing an implementation without naming+ # its type — the counterpart to UNKNOWN_PIPE_TYPE (a declared-but-invalid type).+ MISSING_PIPE_TYPE = "missing_pipe_type"BATCH_ITEM_NAME_COLLISION = "batch_item_name_collision"# Wiring / reference-resolution failures, detected when validating a pipe's contract against thediff --git a/pipelex/core/pipes/pipe_blueprint.py b/pipelex/core/pipes/pipe_blueprint.pyindex 9424c8cb4..936aeb671 100644--- a/pipelex/core/pipes/pipe_blueprint.py+++ b/pipelex/core/pipes/pipe_blueprint.py@@ -1,6 +1,6 @@import refrom abc import ABC-from typing import Any, final+from typing import Any, cast, finalfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator@@ -15,6 +15,76 @@ from pipelex.types import Self, StrEnum# executable kinds (a signature blueprint carries `type = "PipeSignature"`, `pipe_category = None`).PIPE_SIGNATURE_TYPE_TAG = "PipeSignature"+# The exact set of keys a *typeless* `[pipe.x]` section may declare and still be a signature+# (contract only). A section with no `type` whose keys are a subset of this set is normalized to a+# `PipeSignature`; any other key present means the author is describing an implementation, which must+# name its `type` — that is a hard error (see `normalize_typeless_signature_section` below). `source`+# is a non-user blueprint field, admitted defensively so this set matches `PipeSignatureBlueprint`'s+# writable contract; it is unreachable via the stray-key path today (a section carrying `source` was+# dumped from a blueprint, so it also carries `type`, which short-circuits before this set is+# consulted). Single source of truth for the blueprint and spec (authoring) layers — the spec layer+# reuses it augmented with its structural `pipe_code` field (see `SIGNATURE_ONLY_SPEC_KEYS`).+SIGNATURE_ONLY_KEYS: frozenset[str] = frozenset({"description", "inputs", "output", "signature_for", "source"})++# The contract keys advertised to authors in the typeless-signature teaching message, in display order.+# Deliberately NOT derived from `SIGNATURE_ONLY_KEYS` / `SIGNATURE_ONLY_SPEC_KEYS`: those admit internal+# keys never written by an author (`source`, and the spec layer's structural `pipe_code`) that must not+# leak into a user-facing message. Kept here so the message can never drift from the advertisable set.+_ADVERTISABLE_SIGNATURE_KEYS: tuple[str, ...] = ("description", "inputs", "output", "signature_for")+++def explicit_signature_tag_migration_message(pipe_code: Any) -> str:+ """The migration error for a section that still writes the retired `type = "PipeSignature"` tag.++ Starts with ``Pipe `<code>``` so the validation-error categorizer recovers the pipe code from the+ message (the error is raised on the aggregate `pipe` field, which carries no pipe code in its+ pydantic `loc`). Single source of truth for the blueprint and spec layers and the single-pipe+ authoring path (`parse_pipe_spec`).+ """+ return (+ f'Pipe `{pipe_code}` sets `type = "PipeSignature"`, which is no longer a pipe type. '+ "Delete the `type` line — a pipe with no `type` and no implementation is a signature (contract only)."+ )+++def normalize_typeless_signature_section(pipe_code: Any, *, pipe_section: Any, allowed_keys: frozenset[str] = SIGNATURE_ONLY_KEYS) -> Any:+ """Inject the internal `PipeSignature` tag on a typeless contract-only section, reject a typeless+ section that declares more than the contract, and reject a section that still writes the retired+ explicit `type = "PipeSignature"` tag. Non-dict values (already-built pipe instances) and sections+ that name a concrete `type` pass through unchanged.++ Shared by the blueprint (`PipelexBundleBlueprint`) and spec (`PipelexBundleSpec`) `pipe`+ before-validators so both teaching messages — whose exact wording the validation-error categorizer+ keys off (`_MISSING_PIPE_TYPE_MARKER` / `_EXPLICIT_SIGNATURE_TAG_MARKER` in+ `validation_error_categorizer.py`) — have a single source of truth. `allowed_keys` differs per+ layer: the spec section additionally carries the structural `pipe_code` field, so it passes+ `SIGNATURE_ONLY_SPEC_KEYS`.++ The injected tag never re-enters this function: it is returned in a fresh dict that downstream+ validation consumes directly, and `PipeSignatureBlueprint` excludes `type` from its serialization,+ so an internal dump→revalidate round-trip yields a typeless section (re-injected here), not the+ tag. The tag therefore appears in a raw section only when a user wrote it — which is what we reject.+ """+ if not isinstance(pipe_section, dict):+ return pipe_section+ typed_section = cast("dict[str, Any]", pipe_section)+ if "type" in typed_section:+ if typed_section["type"] == PIPE_SIGNATURE_TYPE_TAG:+ raise ValueError(explicit_signature_tag_migration_message(pipe_code))+ return typed_section+ stray_keys = [key for key in typed_section if key not in allowed_keys]+ if stray_keys:+ stray = ", ".join(f"`{key}`" for key in stray_keys)+ allowed = ", ".join(f"`{key}`" for key in _ADVERTISABLE_SIGNATURE_KEYS)+ msg = (+ f"Pipe `{pipe_code}` has no `type` but declares {stray}. "+ f"A pipe with no `type` may declare only {allowed} — that is a "+ "signature (contract only). To implement it, add the appropriate `type` (`PipeLLM`, `PipeImgGen`, …). "+ f"To keep it a contract, remove {stray}."+ )+ raise ValueError(msg)+ return {**typed_section, "type": PIPE_SIGNATURE_TYPE_TAG}+class PipeCategory(StrEnum):PIPE_OPERATOR = "PipeOperator"@@ -88,10 +158,13 @@ class PipeType(StrEnum):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.+ """Every legal `type` string a pipe blueprint may carry: 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 the tag is the INTERNAL discriminator the before-validator injects for a+ typeless section, so the injected value must pass the `type` field validator and therefore belongs+ in this allowlist. It is never written by users: an explicit `type = "PipeSignature"` is rejected+ upstream in the before-validator (`normalize_typeless_signature_section`). Single source of truth+ for the three layers (`PipeBlueprint`, `PipeAbstract`, `PipeSpec`) that gate `type`."""return [*PipeType.value_list(), PIPE_SIGNATURE_TYPE_TAG]diff --git a/pipelex/language/mthds_schema_generator.py b/pipelex/language/mthds_schema_generator.pyindex 8aa19cea1..286d700ab 100644--- a/pipelex/language/mthds_schema_generator.py+++ b/pipelex/language/mthds_schema_generator.py@@ -10,12 +10,13 @@ from __future__ import annotationsimport copyfrom typing import TYPE_CHECKING, Any, cast, get_args-if TYPE_CHECKING:- from collections.abc import Callable-from pipelex.core.bundles.pipelex_bundle_blueprint import PipeBlueprintUnion, PipelexBundleBlueprint+from pipelex.pipe_signature.pipe_signature_blueprint import PipeSignatureBlueprintfrom pipelex.tools.misc.package_utils import get_package_version+if TYPE_CHECKING:+ from collections.abc import Callable+# Fields that are injected at load time, never written by users in .mthds files_INTERNAL_FIELDS = {"source"}@@ -29,6 +30,11 @@ _PIPE_INTERNAL_FIELDS = {"pipe_category"}# __name__ matches the Pydantic $defs key._PIPE_DEFINITION_NAMES: frozenset[str] = frozenset(member.__name__ for member in get_args(get_args(PipeBlueprintUnion)[0]))+# The signature arm is the one typeless arm: `_normalize_type_on_pipe_definitions` REMOVES `type` from+# it entirely, so a contract-only table with no `type` matches it and an explicit `type = "PipeSignature"`+# is rejected (extra property under the arm's `additionalProperties: false`).+_SIGNATURE_DEFINITION_NAME = PipeSignatureBlueprint.__name__+def generate_mthds_schema() -> dict[str, Any]:"""Generate a Taplo-compatible JSON Schema for .mthds files.@@ -47,7 +53,7 @@ def generate_mthds_schema() -> dict[str, Any]:schema = _remove_internal_fields(schema)schema = _promote_schema_required_fields(schema)- schema = _require_type_on_pipe_definitions(schema)+ schema = _normalize_type_on_pipe_definitions(schema)schema = _convert_to_draft4(schema)schema = _patch_construct_schema(schema)@@ -122,17 +128,23 @@ def _promote_schema_required_fields(schema: dict[str, Any]) -> dict[str, Any]:return schema-def _require_type_on_pipe_definitions(schema: dict[str, Any]) -> dict[str, Any]:- """Force `type` into the `required` array of every pipe blueprint definition.+def _normalize_type_on_pipe_definitions(schema: dict[str, Any]) -> dict[str, Any]:+ """Normalize the `type` discriminator across pipe blueprint definitions for Draft-4 `oneOf`.++ The runtime union disambiguates with `Field(discriminator="type")`, but `_convert_to_draft4`+ strips `discriminator` (Draft 4 has none), so the arms must self-disambiguate. Two shapes:- Each pipe blueprint declares `type` as a Literal with a default- (e.g. `type: Literal["PipeLLM"] = "PipeLLM"`), so Pydantic omits it from- `required`. The runtime union disambiguates with `Field(discriminator="type")`,- but `_convert_to_draft4` strips `discriminator` (Draft 4 has none). Without a- required `type`, a type-less table like `{description, output}` matches several- `oneOf` arms at once and `oneOf` rejects the multi-match with an ambiguous error.- Requiring `type` per variant makes a typed table match exactly one arm and a- type-less table fail with a clear "missing type".+ - **Concrete arms** declare `type` as a Literal with a default (e.g.+ `type: Literal["PipeLLM"] = "PipeLLM"`), so Pydantic omits it from `required`. We force `type`+ into `required` so a typed table matches exactly one arm and a table lacking `type` fails these+ arms cleanly instead of ambiguously multi-matching.+ - **The signature arm** is the one typeless arm: we REMOVE `type` from it entirely (property and+ `required`). Every pipe def has `additionalProperties: false`, so the signature arm becomes+ `{description, output, inputs?, signature_for?}` with no `type`. A typeless contract table+ therefore matches only this arm (concrete arms require `type`); a table with a *concrete* `type`+ fails this arm (extra `type` property) and matches only its own arm; a typeless table with a+ stray field matches no arm; and an explicit `type = "PipeSignature"` is rejected here too (extra+ `type` property) — the language surface no longer accepts the retired tag."""schema = copy.deepcopy(schema)defs_key = "$defs" if "$defs" in schema else "definitions"@@ -140,7 +152,15 @@ def _require_type_on_pipe_definitions(schema: dict[str, Any]) -> dict[str, Any]:for def_name in _PIPE_DEFINITION_NAMES:def_schema = definitions.get(def_name)- if def_schema is None or "type" not in def_schema.get("properties", {}):+ if def_schema is None:+ continue+ properties = def_schema.get("properties", {})+ if def_name == _SIGNATURE_DEFINITION_NAME:+ # Typeless arm: no `type` at all, so an explicit tag is rejected as an extra property.+ properties.pop("type", None)+ _remove_from_required(def_schema, field_names={"type"})+ continue+ if "type" not in properties:continuerequired = def_schema.setdefault("required", [])if "type" not in required:diff --git a/pipelex/pipe_signature/pipe_signature_blueprint.py b/pipelex/pipe_signature/pipe_signature_blueprint.pyindex e3a5c3531..05aed6698 100644--- a/pipelex/pipe_signature/pipe_signature_blueprint.py+++ b/pipelex/pipe_signature/pipe_signature_blueprint.py@@ -14,7 +14,12 @@ class PipeSignatureBlueprint(PipeBlueprint):before all its pipes are implemented."""- type: Literal["PipeSignature"] = "PipeSignature"+ # `exclude=True`: the tag is an internal union discriminator, not a language-surface field. A+ # signature has no `type` in `.mthds` (the author omits it — omitting the type IS the signature),+ # so it must not serialize one. This also keeps internal dump→revalidate round-trips typeless: the+ # dumped section carries no `type`, so the bundle before-validator re-injects it via+ # `normalize_typeless_signature_section` instead of tripping the explicit-tag migration error.+ type: Literal["PipeSignature"] = Field(default="PipeSignature", exclude=True)# 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)diff --git a/tests/e2e/fixtures/signature_bundles/mixed_with_signature_step.mthds b/tests/e2e/fixtures/signature_bundles/mixed_with_signature_step.mthdsindex 77b0230d1..4ad9e9b63 100644--- a/tests/e2e/fixtures/signature_bundles/mixed_with_signature_step.mthds+++ b/tests/e2e/fixtures/signature_bundles/mixed_with_signature_step.mthds@@ -13,7 +13,6 @@ output = "Text"prompt = "Extract text from $doc."[pipe.summarize_extracted]-type = "PipeSignature"description = "Summarize extracted text (contract only)."inputs = { extracted = "Text" }output = "MixSummary"diff --git a/tests/e2e/fixtures/signature_bundles/multi_input_multiplicity.mthds b/tests/e2e/fixtures/signature_bundles/multi_input_multiplicity.mthdsindex 113b7b63c..e7c515231 100644--- a/tests/e2e/fixtures/signature_bundles/multi_input_multiplicity.mthds+++ b/tests/e2e/fixtures/signature_bundles/multi_input_multiplicity.mthds@@ -7,7 +7,6 @@ FuseImage = "An image used in the multiplicity signature test."FuseReport = "A report produced from documents and images."[pipe.fuse_docs_and_images]-type = "PipeSignature"description = "Combine docs and exactly 3 images (contract only)."inputs = { docs = "FuseDoc[]", images = "FuseImage[3]" }output = "FuseReport"diff --git a/tests/e2e/fixtures/signature_bundles/signature_only.mthds b/tests/e2e/fixtures/signature_bundles/signature_only.mthdsindex 82e37f4b4..9bc8e0f53 100644--- a/tests/e2e/fixtures/signature_bundles/signature_only.mthds+++ b/tests/e2e/fixtures/signature_bundles/signature_only.mthds@@ -5,7 +5,6 @@ main_pipe = "summarize_doc"SigDocument = "A document concept used for testing signatures."[pipe.summarize_doc]-type = "PipeSignature"description = "Produces a summary of a document (contract only)."inputs = { doc = "SigDocument" }output = "Text"diff --git a/tests/e2e/fixtures/signature_bundles/signature_with_structured_output.mthds b/tests/e2e/fixtures/signature_bundles/signature_with_structured_output.mthdsindex 9514547e3..52c4c6c94 100644--- a/tests/e2e/fixtures/signature_bundles/signature_with_structured_output.mthds+++ b/tests/e2e/fixtures/signature_bundles/signature_with_structured_output.mthds@@ -13,7 +13,6 @@ body = { type = "text", description = "Summary body", required = true }word_count = { type = "integer", description = "Number of words in the summary", required = true }[pipe.summarize_structured]-type = "PipeSignature"description = "Summarize a document into a structured summary (contract only)."inputs = { doc = "SigStructDoc" }output = "SigStructuredSummary"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.mthdsindex 327f39989..06812b09a 100644--- 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@@ -3,7 +3,6 @@ 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/recursive_refinement/bundle.mthds b/tests/e2e/pipelex/pipes/additive_multi_file_library/recursive_refinement/bundle.mthdsindex 69ad4ea01..3d2ae1f41 100644--- 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@@ -16,7 +16,6 @@ key_findings = { type = "list", item_type = "text", description = "Bullet list o# `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"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.mthdsindex 263b35da1..df689c862 100644--- 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@@ -19,14 +19,12 @@ steps = [# 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"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.mthdsindex dd92122b7..752ebe334 100644--- 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@@ -3,7 +3,6 @@ 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"diff --git a/tests/integration/pipelex/cli/test_agent_validate_defaults_strict.py b/tests/integration/pipelex/cli/test_agent_validate_defaults_strict.pyindex e25775204..6628d5b7c 100644--- a/tests/integration/pipelex/cli/test_agent_validate_defaults_strict.py+++ b/tests/integration/pipelex/cli/test_agent_validate_defaults_strict.py@@ -27,7 +27,6 @@ output = "AgentSummary"steps = [ { pipe = "agent_sig", result = "summary" } ][pipe.agent_sig]-type = "PipeSignature"description = "Signature placeholder."inputs = { doc = "AgentDoc" }output = "AgentSummary"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.pyindex dd3576f07..9a6d43c1d 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@@ -32,7 +32,6 @@ output = "Text"prompt = "Extract text from $doc."[pipe.draft_pipe]-type = "PipeSignature"description = "Unrelated draft signature, reached by nothing."inputs = { note = "SliceNote" }output = "SliceNote"@@ -82,7 +81,6 @@ output = "CallerSummary"steps = [ { pipe = "summary_sig", result = "summary" } ][pipe.summary_sig]-type = "PipeSignature"description = "Signature placeholder for the summary step."inputs = { doc = "CallerDoc" }output = "CallerSummary"diff --git a/tests/integration/pipelex/cli/test_validate_signatures_cli.py b/tests/integration/pipelex/cli/test_validate_signatures_cli.pyindex bffe11544..f0b3cafff 100644--- a/tests/integration/pipelex/cli/test_validate_signatures_cli.py+++ b/tests/integration/pipelex/cli/test_validate_signatures_cli.py@@ -31,7 +31,6 @@ output = "CliSummary"steps = [ { pipe = "summary_sig", result = "summary" } ][pipe.summary_sig]-type = "PipeSignature"description = "Signature placeholder for the summary step."inputs = { doc = "CliDoc" }output = "CliSummary"@@ -45,7 +44,6 @@ CliDoc = "A document used in CLI signature tests."CliSummary = "A summary used in CLI signature tests."[pipe.orphan_sig]-type = "PipeSignature"description = "Orphan signature with no caller."inputs = { doc = "CliDoc" }output = "CliSummary"diff --git a/tests/integration/pipelex/cli/test_validate_signatures_summary.py b/tests/integration/pipelex/cli/test_validate_signatures_summary.pyindex 386e30ec6..cd181fd7f 100644--- a/tests/integration/pipelex/cli/test_validate_signatures_summary.py+++ b/tests/integration/pipelex/cli/test_validate_signatures_summary.py@@ -30,7 +30,6 @@ output = "SummaryOut"steps = [ { pipe = "summary_sig", result = "summary" } ][pipe.summary_sig]-type = "PipeSignature"description = "Signature placeholder for the summary step."inputs = { doc = "SummaryDoc" }output = "SummaryOut"diff --git a/tests/integration/pipelex/pipe_signature/test_pipe_signature_in_blueprint_union.py b/tests/integration/pipelex/pipe_signature/test_pipe_signature_in_blueprint_union.pyindex 895d10c8a..6f5238f8b 100644--- a/tests/integration/pipelex/pipe_signature/test_pipe_signature_in_blueprint_union.py+++ b/tests/integration/pipelex/pipe_signature/test_pipe_signature_in_blueprint_union.py@@ -39,3 +39,136 @@ class TestPipeSignatureBlueprintUnion:},})++ def test_typeless_contract_section_normalizes_to_signature(self) -> None:+ """A `[pipe.x]` with no `type` and only contract keys IS a signature (the tag is injected)."""+ bundle = PipelexBundleBlueprint.model_validate(+ {+ "domain": "sig_union_demo",+ "pipe": {+ "summarize_doc": {+ "description": "Summarize a document (contract only).",+ "inputs": {"doc": "SigUnionDoc"},+ "output": "SigUnionSummary",+ },+ },+ }+ )+ assert bundle.pipe is not None+ loaded = bundle.pipe["summarize_doc"]+ assert isinstance(loaded, PipeSignatureBlueprint)+ assert loaded.is_signature is True+ assert loaded.pipe_category is None++ def test_typeless_contract_without_inputs_is_valid(self) -> None:+ """`inputs` is optional on a signature: `{description, output}` alone is a valid contract."""+ bundle = PipelexBundleBlueprint.model_validate(+ {+ "domain": "sig_union_demo",+ "pipe": {+ "emit_summary": {+ "description": "Produce a summary from nothing (contract only).",+ "output": "SigUnionSummary",+ },+ },+ }+ )+ assert bundle.pipe is not None+ loaded = bundle.pipe["emit_summary"]+ assert isinstance(loaded, PipeSignatureBlueprint)+ assert loaded.inputs is None++ def test_explicit_signature_tag_rejected(self) -> None:+ """`PipeSignature` is no longer a pipe type: writing it explicitly is a migration error that+ names the pipe and points the author at the typeless form.+ """+ with pytest.raises(ValidationError) as exc_info:+ PipelexBundleBlueprint.model_validate(+ {+ "domain": "sig_union_demo",+ "pipe": {+ "summarize_doc": {+ "type": "PipeSignature",+ "description": "Summarize a document (contract only).",+ "inputs": {"doc": "SigUnionDoc"},+ "output": "SigUnionSummary",+ },+ },+ }+ )+ message = str(exc_info.value)+ assert "summarize_doc" in message+ assert "is no longer a pipe type" in message+ assert "Delete the `type` line" in message++ def test_typeless_section_with_impl_field_raises_teaching_error(self) -> None:+ """A typeless section carrying an implementation field is a hard error naming the field and+ giving both fixes — never silently treated as a signature, never a bare pydantic dump.+ """+ with pytest.raises(ValidationError) as exc_info:+ PipelexBundleBlueprint.model_validate(+ {+ "domain": "sig_union_demo",+ "pipe": {+ "summarize_doc": {+ "description": "Looks like an implementation but names no type.",+ "inputs": {"doc": "SigUnionDoc"},+ "output": "SigUnionSummary",+ "prompt": "Summarize $doc.",+ },+ },+ }+ )+ message = str(exc_info.value)+ # Names the offending pipe and field.+ assert "summarize_doc" in message+ assert "`prompt`" in message+ # States the rule and both escape routes (add a type / remove the field), without guessing a type.+ assert "may declare only" in message+ assert "add the appropriate `type`" in message+ assert "remove `prompt`" in message++ def test_teaching_error_advertises_signature_for(self) -> None:+ """The stray-key teaching message names `signature_for` as an allowed contract key, and does not+ leak the internal `source` key the allowlist also admits.+ """+ with pytest.raises(ValidationError) as exc_info:+ PipelexBundleBlueprint.model_validate(+ {+ "domain": "sig_union_demo",+ "pipe": {+ "summarize_doc": {+ "description": "Contract with a hint plus a stray implementation field.",+ "inputs": {"doc": "SigUnionDoc"},+ "output": "SigUnionSummary",+ "signature_for": "PipeLLM",+ "model": "gpt",+ },+ },+ }+ )+ message = str(exc_info.value)+ assert "has no `type` but declares `model`" in message+ assert "`signature_for`" in message+ assert "`source`" not in message++ def test_typeless_section_missing_required_contract_field_still_errors(self) -> None:+ """A typeless section whose keys are all contract-legal but that omits a REQUIRED contract+ field (here `output`) is normalized to a signature and then fails the signature's own+ required-field validation. The safety invariant holds: it is never silently accepted as a+ mock, and the missing field is named. (Categorizing this bare pydantic residual into a+ structured item is a deferred, pre-existing general gap — see wip/pipe-signature-not-a-type.md.)+ """+ with pytest.raises(ValidationError) as exc_info:+ PipelexBundleBlueprint.model_validate(+ {+ "domain": "sig_union_demo",+ "pipe": {+ "summarize_doc": {+ "description": "A contract-only section that forgot to declare its output.",+ "signature_for": "PipeLLM",+ },+ },+ }+ )+ assert "output" in str(exc_info.value)diff --git a/tests/integration/pipelex/pipeline/test_acquire_and_validate.py b/tests/integration/pipelex/pipeline/test_acquire_and_validate.pyindex 84191d062..431870d1f 100644--- a/tests/integration/pipelex/pipeline/test_acquire_and_validate.py+++ b/tests/integration/pipelex/pipeline/test_acquire_and_validate.py@@ -37,7 +37,6 @@ output = "Text"prompt = "Summarize $doc"[pipe.standalone_sig]-type = "PipeSignature"description = "A standalone signature reached by nothing"inputs = {{ doc = "Doc" }}output = "Text"diff --git a/tests/integration/pipelex/pipeline/test_public_validation_api.py b/tests/integration/pipelex/pipeline/test_public_validation_api.pyindex 6434e472c..f7a1cccdf 100644--- a/tests/integration/pipelex/pipeline/test_public_validation_api.py+++ b/tests/integration/pipelex/pipeline/test_public_validation_api.py@@ -38,7 +38,6 @@ output = "Text"prompt = "Summarize $doc"[pipe.standalone_sig]-type = "PipeSignature"description = "A standalone signature reached by nothing"inputs = {{ doc = "Doc" }}output = "Text"diff --git a/tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.py b/tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.pyindex 64479dec0..640f11a45 100644--- a/tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.py+++ b/tests/integration/pipelex/pipeline/test_validate_bundle_structured_errors.py@@ -74,6 +74,28 @@ output = "Text"prompt = "Do something magical with $text""""+_TYPELESS_IMPL_FIELD_MTHDS = """+domain = "structured_typeless_impl"+main_pipe = "summarize_doc"++[pipe.summarize_doc]+description = "Looks like an implementation but names no type."+inputs = { doc = "Text" }+output = "Text"+prompt = "Summarize $doc."+"""++_EXPLICIT_SIGNATURE_TAG_MTHDS = """+domain = "structured_explicit_sig_tag"+main_pipe = "summarize_doc"++[pipe.summarize_doc]+type = "PipeSignature"+description = "Still writes the retired tag."+inputs = { doc = "Text" }+output = "Text"+"""+_PROMPT_INPUT_MISMATCH_MTHDS = """domain = "structured_prompt_mismatch"main_pipe = "greet_person"@@ -174,6 +196,43 @@ class TestValidateBundleStructuredErrors:assert item.pipe_code == "mystery"assert item.domain_code == "structured_bad_pipe_type"+ async def test_typeless_pipe_with_impl_field_is_a_categorized_blueprint_item(+ self,+ load_empty_library: Callable[[], str],+ ) -> None:+ """A typeless pipe that declares an implementation field (`prompt`) surfaces as a categorized+ blueprint item with the MISSING_PIPE_TYPE error_type and the pipe locator — not a bare residual.+ """+ load_empty_library()+ items = await _validation_errors_for(_TYPELESS_IMPL_FIELD_MTHDS)+ type_items = [item for item in items if item.error_type == PipeValidationErrorType.MISSING_PIPE_TYPE]+ assert type_items, f"Expected a missing_pipe_type item, got {[(i.category, i.error_type) for i in items]}"+ item = type_items[0]+ assert item.category == ValidationErrorCategory.BLUEPRINT_VALIDATION+ assert item.pipe_code == "summarize_doc"+ assert item.domain_code == "structured_typeless_impl"+ assert "prompt" in item.message++ async def test_explicit_signature_tag_is_a_categorized_blueprint_item(+ self,+ load_empty_library: Callable[[], str],+ ) -> None:+ """A section that writes the retired `type = "PipeSignature"` tag DECLARED a type — it is just+ no longer a valid one — so it surfaces as UNKNOWN_PIPE_TYPE (a declared-but-invalid type), not+ MISSING_PIPE_TYPE, with the pipe locator and the migration guidance in the message.+ """+ load_empty_library()+ items = await _validation_errors_for(_EXPLICIT_SIGNATURE_TAG_MTHDS)+ type_items = [item for item in items if item.error_type == PipeValidationErrorType.UNKNOWN_PIPE_TYPE]+ assert type_items, f"Expected an unknown_pipe_type item, got {[(i.category, i.error_type) for i in items]}"+ item = type_items[0]+ assert item.category == ValidationErrorCategory.BLUEPRINT_VALIDATION+ assert item.pipe_code == "summarize_doc"+ assert item.domain_code == "structured_explicit_sig_tag"+ assert "is no longer a pipe type" in item.message+ # It is NOT miscategorized as "missing" — the pipe declared a type.+ assert not [item for item in items if item.error_type == PipeValidationErrorType.MISSING_PIPE_TYPE]+async def test_missing_input_variable_now_carries_the_pipe_code_locator(self,load_empty_library: Callable[[], str],diff --git a/tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py b/tests/unit/pipelex/builder/operations/test_parse_pipe_spec.pyindex 6796c08b7..07ca67abc 100644--- a/tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py+++ b/tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py@@ -19,6 +19,8 @@ from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpecfrom pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpecfrom pipelex.builder.pipe.pipe_search_spec import PipeSearchSpecfrom pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec+from pipelex.builder.pipe.pipe_signature_spec import PipeSignatureSpec+from pipelex.core.pipes.pipe_blueprint import PipeTypefrom tests.unit.pipelex.builder.operations.test_data import PipeOpsTestData_BASE_LLM = PipeOpsTestData.BASE_LLM_SPEC@@ -37,6 +39,76 @@ class TestParsePipeSpec:with pytest.raises(ValueError, match="PipeLLM"):parse_pipe_spec({"pipe_code": "x", "description": "x"}, pipe_type="PipeBogus")+ # -- typeless signature (no type) -------------------------------------++ def test_typeless_spec_becomes_signature(self) -> None:+ """A typeless contract-only spec (pipe_type=None) routes to PipeSignatureSpec — omitting the+ type IS the signature.+ """+ result = parse_pipe_spec(+ {"pipe_code": "summarize_doc", "description": "Summarize a doc.", "inputs": {"doc": "Document"}, "output": "Text"},+ pipe_type=None,+ )+ assert isinstance(result, PipeSignatureSpec)+ assert result.to_blueprint().is_signature is True++ def test_typeless_spec_preserves_signature_for_hint(self) -> None:+ result = parse_pipe_spec(+ {"pipe_code": "x", "description": "d", "inputs": {"doc": "Text"}, "output": "Text", "signature_for": "PipeLLM"},+ pipe_type=None,+ )+ assert isinstance(result, PipeSignatureSpec)+ assert result.signature_for is PipeType.PIPE_LLM++ def test_explicit_signature_tag_rejected_with_migration_error(self) -> None:+ """`PipeSignature` is no longer a selectable type: passing it is a migration error (never a+ generic 'Invalid pipe type', and never routed through the spec-class map).+ """+ with pytest.raises(ValueError, match="is no longer a pipe type") as exc_info:+ parse_pipe_spec(+ {"pipe_code": "x", "description": "d", "inputs": {"doc": "Text"}, "output": "Text"},+ pipe_type="PipeSignature",+ )+ assert "Invalid pipe type" not in str(exc_info.value)++ def test_typeless_spec_with_stray_field_raises_teaching_error(self) -> None:+ with pytest.raises(ValueError, match="has no `type` but declares `prompt`"):+ parse_pipe_spec(+ {"pipe_code": "x", "description": "d", "inputs": {"doc": "Text"}, "output": "Text", "prompt": "do it"},+ pipe_type=None,+ )++ @pytest.mark.parametrize("alias", ["output_concept", "output_type"])+ def test_typeless_spec_accepts_output_alias(self, alias: str) -> None:+ """Output aliases are canonicalized before the typeless-signature contract check, so a signature+ authored with `output_concept` / `output_type` is accepted — parity with typed pipes.+ """+ result = parse_pipe_spec(+ {"pipe_code": "x", "description": "d", "inputs": {"doc": "Document"}, alias: "Article"},+ pipe_type=None,+ )+ assert isinstance(result, PipeSignatureSpec)+ assert result.output == "Article"++ def test_typeless_spec_accepts_dict_output(self) -> None:+ """A dict-shaped output (`{"type": ...}`) is flattened before the contract check for a signature."""+ result = parse_pipe_spec(+ {"pipe_code": "x", "description": "d", "inputs": {"doc": "Document"}, "output": {"type": "Article"}},+ pipe_type=None,+ )+ assert isinstance(result, PipeSignatureSpec)+ assert result.output == "Article"++ def test_typeless_spec_stray_impl_field_still_rejected_after_output_normalization(self) -> None:+ """Output normalization must not weaken the teaching error: a genuine implementation field on a+ typeless spec still raises, naming the field.+ """+ with pytest.raises(ValueError, match="has no `type` but declares `model`"):+ parse_pipe_spec(+ {"pipe_code": "x", "description": "d", "inputs": {"doc": "Document"}, "output": "Article", "model": "gpt"},+ pipe_type=None,+ )+# -- pipe_code aliases ------------------------------------------------def test_canonical_pipe_code(self) -> None:diff --git a/tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py b/tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.pyindex 66fbc3d3b..0dae6513e 100644--- a/tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py+++ b/tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py@@ -11,6 +11,35 @@ _BASE_LLM = PipeOpsTestData.BASE_LLM_SPECclass TestPipeSpecToToml:"""Comprehensive tests for pipe_spec_to_toml covering all pipe types."""+ # -- PipeSignature (typeless) -----------------------------------------++ def test_signature_toml_has_no_type_line(self) -> None:+ """A signature renders as a typeless `[pipe.x]` section — no `type` line, since omitting the+ type IS the signature — so it re-parses as a signature (an explicit `type = "PipeSignature"`+ would now be rejected).+ """+ spec = parse_pipe_spec(+ {"pipe_code": "summarize_doc", "description": "Summarize a doc.", "inputs": {"doc": "Document"}, "output": "Text"},+ pipe_type=None,+ )+ toml = pipe_spec_to_toml(spec)+ assert "[pipe.summarize_doc]" in toml+ assert "type =" not in toml+ assert 'description = "Summarize a doc."' in toml+ assert 'output = "Text"' in toml++ def test_signature_toml_preserves_signature_for_hint(self) -> None:+ """The optional `signature_for` hint round-trips (guards against renderer drift with the+ agent-CLI `_pipe_spec_to_toml`, which also emits it).+ """+ spec = parse_pipe_spec(+ {"pipe_code": "x", "description": "d", "inputs": {"doc": "Text"}, "output": "Text", "signature_for": "PipeLLM"},+ pipe_type=None,+ )+ toml = pipe_spec_to_toml(spec)+ assert "type =" not in toml+ assert 'signature_for = "PipeLLM"' in toml+# -- PipeLLM ----------------------------------------------------------def test_llm_basic_structure(self) -> None:diff --git a/tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py b/tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.pynew file mode 100644index 000000000..8683fb3d8--- /dev/null+++ b/tests/unit/pipelex/builder/test_bundle_spec_typeless_signature.py@@ -0,0 +1,215 @@+"""Unit tests for typeless-signature normalization in the spec (authoring) layer.++Mirrors the blueprint-layer behavior: a `[pipe.x]` spec section with no `type` whose keys are exactly+the signature contract is normalized to a `PipeSignatureSpec`; a typeless section with any stray field+raises the teaching error; and an explicit `type = "PipeSignature"` is rejected with the migration+error (a signature has no type).+"""++from typing import Any++import pytest+from pydantic import ValidationError++from pipelex.builder.bundle_spec import PipelexBundleSpec+from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec+from pipelex.builder.pipe.pipe_signature_spec import PipeSignatureSpec+from pipelex.core.pipes.pipe_blueprint import PipeType+from pipelex.pipe_signature.pipe_signature_blueprint import PipeSignatureBlueprint+++def _bundle_with_pipe(pipe_section: dict[str, Any], *, pipe_code: str = "summarize_doc") -> PipelexBundleSpec:+ return PipelexBundleSpec.model_validate(+ {+ "domain": "test_domain",+ "main_pipe": pipe_code,+ "pipe": {pipe_code: pipe_section},+ }+ )+++class TestPipelexBundleSpecTypelessSignature:+ def test_typeless_contract_section_becomes_signature_spec(self) -> None:+ """A typeless contract-only section routes to PipeSignatureSpec and round-trips to a signature blueprint."""+ bundle_spec = _bundle_with_pipe(+ {+ "pipe_code": "summarize_doc",+ "description": "Produces a summary of a document.",+ "inputs": {"doc": "Document"},+ "output": "Summary",+ }+ )+ assert bundle_spec.pipe is not None+ sig_spec = bundle_spec.pipe["summarize_doc"]+ assert isinstance(sig_spec, PipeSignatureSpec)++ blueprint = sig_spec.to_blueprint()+ assert isinstance(blueprint, PipeSignatureBlueprint)+ assert blueprint.is_signature is True+ assert blueprint.description == "Produces a summary of a document."+ assert blueprint.inputs == {"doc": "Document"}+ assert blueprint.output == "Summary"++ def test_typeless_with_signature_for_hint_becomes_signature(self) -> None:+ """`signature_for` is a contract-legal optional key, so the section is still a signature."""+ bundle_spec = _bundle_with_pipe(+ {+ "pipe_code": "summarize_doc",+ "description": "Produces a summary of a document.",+ "inputs": {"doc": "Document"},+ "output": "Summary",+ "signature_for": "PipeLLM",+ }+ )+ assert bundle_spec.pipe is not None+ sig_spec = bundle_spec.pipe["summarize_doc"]+ assert isinstance(sig_spec, PipeSignatureSpec)+ assert sig_spec.signature_for is PipeType.PIPE_LLM++ def test_typeless_with_stray_field_raises_teaching_error(self) -> None:+ """A typeless section carrying an implementation field is a hard error that names the field and both fixes."""+ with pytest.raises(ValidationError) as exc_info:+ _bundle_with_pipe(+ {+ "pipe_code": "summarize_doc",+ "description": "Produces a summary of a document.",+ "inputs": {"doc": "Document"},+ "output": "Summary",+ "prompt": "Summarize $doc",+ }+ )+ message = str(exc_info.value)+ assert "has no `type` but declares `prompt`" in message+ assert "To keep it a contract, remove `prompt`" in message++ def test_typeless_with_blueprint_only_source_field_raises_teaching_error(self) -> None:+ """`source` is a blueprint-only field absent from the spec surface, so a typeless section+ carrying it is a stray key (teaching error) — not injected then rejected with a raw pydantic+ `extra_forbidden` message.+ """+ with pytest.raises(ValidationError) as exc_info:+ _bundle_with_pipe(+ {+ "pipe_code": "summarize_doc",+ "description": "Produces a summary of a document.",+ "inputs": {"doc": "Document"},+ "output": "Summary",+ "source": "somewhere.mthds",+ }+ )+ message = str(exc_info.value)+ assert "has no `type` but declares `source`" in message+ assert "Extra inputs are not permitted" not in message++ def test_stray_key_message_advertises_signature_for(self) -> None:+ """The teaching message names `signature_for` as a valid contract key (it is allowed), and does+ not leak the internal `source` / `pipe_code` keys the allowlists also admit.+ """+ with pytest.raises(ValidationError) as exc_info:+ _bundle_with_pipe(+ {+ "pipe_code": "summarize_doc",+ "description": "Produces a summary of a document.",+ "output": "Summary",+ "signature_for": "PipeLLM",+ "model": "gpt",+ }+ )+ message = str(exc_info.value)+ assert "has no `type` but declares `model`" in message+ assert "`signature_for`" in message+ assert "`source`" not in message+ assert "`pipe_code`" not in message++ def test_signature_spec_survives_model_dump_revalidate_round_trip(self) -> None:+ """A bundle spec with a typeless signature must survive `model_dump()` → re-validate. The+ internal `type` / `pipe_category` discriminators must not serialize, else re-validation trips+ the explicit-tag migration error (`type`) or the stray-key teaching error (`pipe_category`).+ """+ bundle_spec = _bundle_with_pipe(+ {+ "pipe_code": "summarize_doc",+ "description": "Produces a summary of a document.",+ "inputs": {"doc": "Document"},+ "output": "Summary",+ }+ )+ dumped = bundle_spec.model_dump()+ sig_section = dumped["pipe"]["summarize_doc"]+ assert "type" not in sig_section+ assert "pipe_category" not in sig_section++ reloaded = PipelexBundleSpec.model_validate(dumped)+ assert reloaded.pipe is not None+ assert isinstance(reloaded.pipe["summarize_doc"], PipeSignatureSpec)++ def test_invalid_pipe_dict_key_rejected_at_spec_level(self) -> None:+ """A non-snake_case pipe dict key is rejected cleanly by the before-validator (mirrors the+ blueprint), instead of slipping through to fail later during `to_blueprint()`.+ """+ with pytest.raises(ValidationError, match="Pipe code 'BadKeyPipe' is not a valid pipe code"):+ PipelexBundleSpec.model_validate(+ {+ "domain": "test_domain",+ "main_pipe": "BadKeyPipe",+ "pipe": {+ "BadKeyPipe": {+ "type": "PipeLLM",+ "pipe_code": "good_pipe",+ "description": "Writes some text.",+ "inputs": {"topic": "Text"},+ "output": "Text",+ "prompt": "Write about $topic",+ }+ },+ }+ )++ def test_explicit_signature_tag_rejected(self) -> None:+ """`PipeSignature` is no longer a pipe type: writing it explicitly in a spec section is a+ migration error naming the pipe and pointing at the typeless form.+ """+ with pytest.raises(ValidationError) as exc_info:+ _bundle_with_pipe(+ {+ "type": "PipeSignature",+ "pipe_code": "summarize_doc",+ "description": "Produces a summary of a document.",+ "inputs": {"doc": "Document"},+ "output": "Summary",+ }+ )+ message = str(exc_info.value)+ assert "summarize_doc" in message+ assert "is no longer a pipe type" in message+ assert "Delete the `type` line" in message++ def test_typed_section_left_untouched(self) -> None:+ """A section that names its own `type` is not normalized — it routes to its concrete spec."""+ bundle_spec = _bundle_with_pipe(+ {+ "type": "PipeLLM",+ "pipe_code": "write_text",+ "description": "Writes some text.",+ "inputs": {"topic": "Text"},+ "output": "Text",+ "prompt": "Write about $topic",+ },+ pipe_code="write_text",+ )+ assert bundle_spec.pipe is not None+ assert isinstance(bundle_spec.pipe["write_text"], PipeLLMSpec)++ def test_already_built_spec_instance_passes_through(self) -> None:+ """A pre-built spec instance (not a raw dict) is left untouched by the before-validator."""+ llm_spec = PipeLLMSpec(+ pipe_code="write_text",+ description="Writes some text.",+ inputs={"topic": "Text"},+ output="Text",+ prompt="Write about $topic",+ model="$writing-creative",+ )+ bundle_spec = PipelexBundleSpec(domain="test_domain", main_pipe="write_text", pipe={"write_text": llm_spec})+ assert bundle_spec.pipe is not None+ assert bundle_spec.pipe["write_text"] is llm_specdiff --git a/tests/unit/pipelex/cli/test_pipe_cmd.py b/tests/unit/pipelex/cli/test_pipe_cmd.pyindex 2712c050f..7806dc66f 100644--- a/tests/unit/pipelex/cli/test_pipe_cmd.py+++ b/tests/unit/pipelex/cli/test_pipe_cmd.py@@ -9,11 +9,16 @@ and integration of parse_pipe_spec with the CLI output path.from __future__ import annotations+import jsonfrom typing import Any, ClassVar+import pytest+import typer+from pipelex.builder.operations.pipe_ops import parse_pipe_specfrom pipelex.cli.agent_cli.commands.pipe_cmd import (_pipe_spec_to_toml, # noqa: PLC2701 # pyright: ignore[reportPrivateUsage]+ pipe_cmd,)@@ -46,6 +51,29 @@ class TestCliPipeCmd:result = parse_pipe_spec(spec, pipe_type=pipe_type)assert result.pipe_code == "test"+ def test_typeless_spec_renders_signature_without_type_line(self) -> None:+ """No type resolved (typeless) → a signature; the CLI TOML omits the `type` line entirely."""+ spec = parse_pipe_spec(+ {"pipe_code": "summarize_doc", "description": "Summarize a doc.", "inputs": {"doc": "Document"}, "output": "Text"},+ pipe_type=None,+ )+ toml = _pipe_spec_to_toml(spec)+ assert "[pipe.summarize_doc]" in toml+ assert "type =" not in toml++ def test_explicit_null_type_rejected(self, capsys: pytest.CaptureFixture[str]) -> None:+ """An explicit `"type": null` in the JSON spec is rejected — a signature is authored by omitting+ the `type` key, not by nulling it (teaching-consistent with the explicit-tag rejection). Present+ null must not silently collapse to a typeless signature.+ """+ spec = json.dumps({"pipe_code": "summarize_doc", "description": "d", "inputs": {"doc": "Document"}, "output": "Text", "type": None})+ with pytest.raises(typer.Exit):+ pipe_cmd(spec=spec)+ captured = capsys.readouterr()+ combined = captured.err + captured.out+ assert "ArgumentError" in combined+ assert "type" in combined+# -- CLI TOML serialization (uses format_toml_string) -----------------def test_llm_model_appears_in_toml(self) -> None:diff --git a/tests/unit/pipelex/language/test_mthds_schema.py b/tests/unit/pipelex/language/test_mthds_schema.pyindex 4b8488eb1..0c7ae2023 100644--- a/tests/unit/pipelex/language/test_mthds_schema.py+++ b/tests/unit/pipelex/language/test_mthds_schema.py@@ -9,6 +9,7 @@ import pytestfrom pipelex.core.pipes.pipe_blueprint import PipeTypefrom pipelex.language.mthds_schema_generator import generate_mthds_schema+from pipelex.pipe_signature.pipe_signature_blueprint import PipeSignatureBlueprintif TYPE_CHECKING:from collections.abc import Iterator@@ -28,7 +29,8 @@ _PIPE_KIND_EXTRA_FIELDS: dict[str, dict[str, Any]] = {"PipeCondition": {"default_outcome": "fallback_pipe", "outcomes": {"yes": "yes_pipe"}},"PipeParallel": {"branches": [{"pipe": "sub_pipe"}]},"PipeSequence": {"steps": [{"pipe": "sub_pipe"}]},- "PipeSignature": {},+ # `PipeSignature` is deliberately absent: a signature is typeless, so there is no typed table for+ # it — an explicit `type = "PipeSignature"` table matches no arm (see test_explicit_signature_tag_is_rejected).}@@ -189,34 +191,74 @@ class TestMthdsSchemaGeneration:assert has_template, "Should have a 'template' variant"assert has_nested, "Should have a 'nested construct' variant"- def test_type_required_on_every_pipe_oneof_arm(self, schema: dict[str, Any]) -> None:- """Every pipe blueprint variant in the pipe `oneOf` must require `type`.+ def test_type_required_on_every_concrete_pipe_arm(self, schema: dict[str, Any]) -> None:+ """Every *concrete* pipe arm requires `type`; the signature arm is the one typeless arm.- Reads the arm names straight from the generated `oneOf`, so a newly added- pipe type is covered automatically — this doubles as the drift guard.+ Reads the arm names straight from the generated `oneOf`, so a newly added pipe type is+ covered automatically — this doubles as the drift guard. The signature arm is the one typeless+ arm: it has NO `type` property at all (an explicit `type = "PipeSignature"` is rejected as an+ extra property under `additionalProperties: false`), so it lists `type` in neither `properties`+ nor `required`."""definitions = schema["definitions"]arms = schema["properties"]["pipe"]["anyOf"][0]["additionalProperties"]["oneOf"]arm_def_names = [arm["$ref"].rsplit("/", 1)[-1] for arm in arms]assert arm_def_names, "The pipe union oneOf should have at least one arm"+ signature_def_name = PipeSignatureBlueprint.__name__+ assert signature_def_name in arm_def_names, "The signature arm must be present in the pipe union"for def_name in arm_def_names:required = definitions[def_name].get("required", [])- assert "type" in required, f"{def_name} must list 'type' in its required array (got {required})"+ properties = definitions[def_name].get("properties", {})+ if def_name == signature_def_name:+ assert "type" not in properties, f"the signature arm must have NO 'type' property (got {sorted(properties)})"+ assert "type" not in required, f"the signature arm must NOT require 'type' (got {required})"+ else:+ assert "type" in required, f"{def_name} must list 'type' in its required array (got {required})"@pytest.mark.parametrize("table",[- pytest.param({"description": "no type at all", "output": "Text"}, id="bare-minimal"),- # A table whose fields uniquely identify PipeFunc but omits `type`. Before the- # fix this matched exactly one arm and validated; requiring `type` rejects it.- pytest.param({"description": "looks like PipeFunc", "output": "Text", "function_name": "do_it"}, id="unique-fields"),+ pytest.param({"description": "bare contract", "output": "Text"}, id="bare-contract"),+ pytest.param({"description": "with inputs", "output": "Text", "inputs": {"doc": "Text"}}, id="with-inputs"),+ pytest.param({"description": "with hint", "output": "Text", "signature_for": "PipeLLM"}, id="with-signature-for"),],)- def test_typeless_pipe_table_is_rejected(self, schema: dict[str, Any], table: dict[str, Any]) -> None:- """A pipe table without `type` must fail validation (no ambiguous multi-match)."""+ def test_typeless_contract_table_matches_signature_arm(self, schema: dict[str, Any], table: dict[str, Any]) -> None:+ """A typeless section carrying only the contract validates — it is a signature."""validator = _pipe_union_oneof_validator(schema)- assert not validator.is_valid(table), f"A type-less pipe table must be rejected: {table}"+ errors = sorted(validator.iter_errors(table), key=str)+ assert not errors, f"A typeless contract table must validate, got errors: {[e.message for e in errors]}"++ @pytest.mark.parametrize(+ "table",+ [+ # A typeless table that adds an implementation field beyond the contract. `prompt` is+ # shared by PipeLLM/PipeImgGen and `function_name` uniquely looks like PipeFunc, but with+ # no `type` neither matches any arm.+ pytest.param({"description": "looks like an impl", "output": "Text", "prompt": "do it"}, id="stray-prompt"),+ pytest.param({"description": "looks like PipeFunc", "output": "Text", "function_name": "do_it"}, id="stray-function-name"),+ ],+ )+ def test_typeless_table_with_stray_field_is_rejected(self, schema: dict[str, Any], table: dict[str, Any]) -> None:+ """A typeless section that declares more than the contract matches no arm."""+ validator = _pipe_union_oneof_validator(schema)+ assert not validator.is_valid(table), f"A typeless non-contract table must be rejected: {table}"++ def test_typoed_type_is_rejected(self, schema: dict[str, Any]) -> None:+ """A misspelled `type` matches no arm (not a concrete kind; the signature arm pins the tag)."""+ validator = _pipe_union_oneof_validator(schema)+ table = {"type": "PipeLLMM", "description": "typo", "output": "Text"}+ assert not validator.is_valid(table)++ def test_explicit_signature_tag_is_rejected(self, schema: dict[str, Any]) -> None:+ """An explicit `type = "PipeSignature"` table matches no arm: the signature arm has no `type`+ property (extra property under `additionalProperties: false`) and every concrete arm pins its+ own `type` enum. `PipeSignature` is no longer a selectable type.+ """+ validator = _pipe_union_oneof_validator(schema)+ table = {"type": "PipeSignature", "description": "explicit tag", "output": "Text"}+ assert not validator.is_valid(table)@pytest.mark.parametrize("pipe_type", sorted(_PIPE_KIND_EXTRA_FIELDS))def test_typed_pipe_table_matches_exactly_one_arm(self, schema: dict[str, Any], pipe_type: str) -> None:@@ -247,14 +289,20 @@ class TestMthdsSchemaGeneration:assert validator.is_valid(table) is should_validate, f"size={size_value!r} should {'' if should_validate else 'not '}validate"def test_minimal_table_coverage_matches_schema_pipe_kinds(self, schema: dict[str, Any]) -> None:- """Guard: the test's per-kind table map covers exactly the pipe kinds in the schema.+ """Guard: the test's per-kind table map covers exactly the *concrete* pipe kinds in the schema.If a new pipe type is added, this fails until a minimal table is provided —- keeping `test_typed_pipe_table_matches_exactly_one_arm` exhaustive.+ keeping `test_typed_pipe_table_matches_exactly_one_arm` exhaustive. The signature arm is+ excluded: it is typeless (no `type` enum) and is not a selectable type."""definitions = schema["definitions"]arms = schema["properties"]["pipe"]["anyOf"][0]["additionalProperties"]["oneOf"]- schema_types = {definitions[arm["$ref"].rsplit("/", 1)[-1]]["properties"]["type"]["enum"][0] for arm in arms}+ signature_def_name = PipeSignatureBlueprint.__name__+ schema_types = {+ definitions[def_name]["properties"]["type"]["enum"][0]+ for arm in arms+ if (def_name := arm["$ref"].rsplit("/", 1)[-1]) != signature_def_name+ }assert set(_PIPE_KIND_EXTRA_FIELDS) == schema_typesdiff --git a/tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py b/tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.pyindex 4881e671d..4a6d1eab9 100644--- a/tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py+++ b/tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py@@ -25,7 +25,6 @@ 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"@@ -44,6 +43,19 @@ output = "Text"prompt = "Summarize $doc.""""+# Typeless header: the same forward-declaration of `summarize`, written WITHOUT the `type` tag.+# The before-validator normalizes it to a PipeSignature, so the new surface must reconcile+# identically to the explicit-tag header above.+DEP_TYPELESS_HEADER_MTHDS = """\+domain = "summary_dep"+description = "Dependency header declaring a summarize signature without a type tag"++[pipe.summarize]+description = "Summarize a document (contract only)."+inputs = { doc = "Text" }+output = "Text"+"""+# A second concrete `summarize` (genuine duplicate) for the negative case.DEP_CONCRETE_DUP_MTHDS = """\domain = "summary_dep"@@ -110,6 +122,34 @@ class TestDependencyMultiFileReconciliation: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_typeless_header_and_concrete_sibling_reconcile_to_concrete(+ self,+ mocker: MockerFixture,+ tmp_path: Path,+ ) -> None:+ """A TYPELESS header (no `type`) + concrete sibling collapse to a single concrete pipe.++ Confirms the new typeless-signature surface reconciles exactly like the explicit-tag header:+ the before-validator normalizes the typeless section to a PipeSignature, and the concrete wins.+ """+ 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_TYPELESS_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, "Typeless signature and concrete must reconcile to exactly one pipe"+ assert not summarize_pipes[0].is_signature, "The concrete definition must win over the typeless forward signature"+def test_two_concrete_definitions_raise(self,mocker: MockerFixture,diff --git a/wip/pipe-signature-not-a-type.md b/wip/pipe-signature-not-a-type.mdnew file mode 100644index 000000000..f018aed6a--- /dev/null+++ b/wip/pipe-signature-not-a-type.md@@ -0,0 +1,132 @@+# PipeSignature is not a type — drop `type = "PipeSignature"` from the language++Branch: `feature/PipeSignature-not-a-type` (currently even with `main`; the signature *machinery* already landed, this branch is the language-surface cleanup).++## The insight++A `PipeSignature` is a **contract declaration** — "this pipe exists, here is its purpose, here is what it takes and what it produces" — with the implementation deferred to somewhere else (a sibling file, a later refinement, a dependency package). The library loader already accepts signatures and reconciles them against the concrete implementation when it shows up.++Today we write a signature like this:++```toml+[pipe.summarize_doc]+type = "PipeSignature"+description = "Produces a summary of a document (contract only)."+inputs = { doc = "SigDocument" }+output = "Text"+```++That `type = "PipeSignature"` line is a lie about the model. `PipeSignature` is **not** a pipe type — the codebase already knows this: it was deliberately evicted from the `PipeType` and `PipeCategory` enums (`pipelex/core/pipes/pipe_blueprint.py:16`, `44-87`), carries `pipe_category = None`, and is identified by class identity (`is_signature`), not by any enum value. A pipe *type* is an implementation kind (PipeLLM, PipeSequence, …). A signature is the **absence** of one.++So the language should stop pretending. The tag adds ceremony, teaches a wrong mental model, and is the kind of bullsh*t our language claims not to have.++## The rule++**A `[pipe.x]` section with no `type` and no implementation is a signature.**++That's it. The whole feature.++Concretely, a pipe declaration needs only:++- `description` — required (what the pipe is for)+- `output` — required (what concept it produces, multiplicity included)+- `inputs` — optional (defaults to none)++If that's *all* a section has, it's a contract — a `PipeSignature`. The moment you add a `type` (and the implementation fields that type needs — `prompt`, `steps`, `branches`, …), it becomes a concrete, runnable pipe.++```toml+# A signature — no type, no implementation. This IS the contract.+[pipe.summarize_doc]+description = "Produces a summary of a document."+inputs = { doc = "SigDocument" }+output = "Text"++# Its implementation — same contract, now with a type and a body.+[pipe.summarize_doc]+type = "PipeLLM"+description = "Produces a summary of a document."+inputs = { doc = "SigDocument" }+output = "Text"+prompt = "Summarize $doc."+```++This reads exactly like a forward declaration vs. a definition in a real language — which is what it is. No new concept to learn; the shape of the file teaches it.++### Scope guardrail (decided)++This change makes **the type tag optional only for the signature case**. Concrete pipes still declare their `type` explicitly — we are **not** inferring the type from fields. And we *can't*, even in principle: fields are not unique to a type. `prompt` does not mean PipeLLM — PipeImgGen uses `prompt` too. There is no field that reliably implies a single concrete type. So inference is off the table, and the rule stays unambiguous: **no `type` ⟺ signature**, and the *only* legal typeless shape is exactly a contract.++## What "no implementation" has to mean (the guard)++The brief says "no type specified **and** no implementation present." Both clauses are load-bearing. A typeless section is a signature **only if it declares nothing but the contract** — `description`, `inputs`, `output` (+ the optional `signature_for` hint, + the internal `source`). The presence of *any* other field means the author is describing an implementation, and an implementation must name its type.++**Decided behavior (no leniency):** a typeless section carrying any non-contract field is a **hard error**. It is never silently treated as a signature (that would hide a real authoring bug behind a mock output), and never a cryptic pydantic dump.++Crucially, the error does **not** guess a type from the fields — because it can't. A `prompt` field is shared by PipeLLM *and* PipeImgGen; no field reliably maps to one type. So the message points at the general fix, not a specific type:++> Pipe `summarize_doc` has no `type` but declares `prompt`. A pipe without a `type` may declare only `description`, `inputs`, and `output` — that is a signature (contract only). To implement it, add the appropriate `type` (`PipeLLM`, `PipeImgGen`, …). To keep it a contract, remove `prompt`.++The error names the offending field(s), states the rule, and gives both escape routes — reinforcing the mental model every time it fires.++## How it works under the hood++The internal machinery does **not** need to lose its discriminator — only the *language surface* drops the tag. This mirrors the workspace rule "structured fields are the contract; the surface is presentation." The blueprint model keeps `type = "PipeSignature"` as an internal runtime discriminator; the `.mthds` author never writes it.++The dispatch is a Pydantic discriminated union on `type` (`pipelex/core/bundles/pipelex_bundle_blueprint.py:29-43`). A discriminated union *requires* the tag, so a missing `type` currently errors with `union_tag_not_found` ("missing required discriminator field 'type'"). We intercept before the union runs.++There is already a `field_validator("pipe", mode="before")` on `PipelexBundleBlueprint` (`validate_pipe_keys`, `:125`). That's the single choke point. It gains a per-section normalization step:++1. **`type` is a real `PipeType`** → leave untouched. Concrete pipe, dispatched as today.+2. **`type` absent, only signature-allowed fields present** → inject `type = "PipeSignature"` so the union routes to `PipeSignatureBlueprint`. The user never saw the tag; the model still discriminates cleanly.+3. **`type` absent, any non-contract field present** → raise the teaching error above (no type inference, no leniency). Legal typeless keys are exactly `{description, inputs, output, signature_for, source}`; anything else fails here.+4. **`type = "PipeSignature"` written explicitly** → raise a migration error (see Migration). It's now an internal-only value.++Everything downstream is unchanged:++- `PipeSignatureBlueprint` still carries the internal tag, `pipe_category = None`, `is_signature = True`.+- Blueprint → runtime factory dispatch keys off `blueprint.is_signature` (`pipe_factory.py:110-117`) — untouched.+- Library reconciliation keys off `is_signature` class identity (`library_crate_factory.py:170-201`) — untouched. Concrete still beats signature; contracts must still match.+- Validation semantics — strict mode refusing bundles that contain signatures, `--allow-signatures` dry-running them as mocks — all key off `is_signature` / the pending-signatures set (`validate_bundle.py`, `_validate_core.py`) — untouched.++## Surfaces to change (implementation checklist)++- **Blueprint parse** — `pipelex/core/bundles/pipelex_bundle_blueprint.py`: extend the `pipe` before-validator with the 4-way normalization + the two teaching errors. This is the heart of the change.+- **Spec parse (authoring layer)** — `pipelex/builder/pipe/pipe_spec_union.py` + a matching before-validator wherever spec dicts are validated into `PipeSpecUnion`. Same 4-way logic so AI-authored specs get the identical clean surface. `PipeSignatureSpec` keeps its internal tag (`pipe_signature_spec.py`).+- **Allowlist / messaging** — `pipelex/core/pipes/pipe_blueprint.py`: `PIPE_SIGNATURE_TYPE_TAG` stays valid *internally* (the injected value must pass `validate_pipe_type`), but the user-facing rejection of an explicitly-written `PipeSignature` lives in the before-validator with a tailored message. Confirm no user path still requires the tag.+- **MTHDS JSON Schema** — `pipelex/language/mthds_schema_generator.py`: today `_require_type_on_pipe_definitions` (`:125`) forces `type` required on *every* pipe arm so a typeless table fails. New behavior: the signature arm must **omit** `type` and become the "no-type" branch (`{description, output, inputs?}`, `additionalProperties: false`). Disambiguation still holds in Draft-4 (no discriminator): a typed table fails the signature arm (extra `type` property under `additionalProperties: false`) and matches its own arm; a typeless table matches only the signature arm. Regenerate `derived/mthds_schema.json` via `pipelex-dev generate-mthds-schema`. **This is the subtlest piece — verify the Taplo/editor lint accepts a typeless section and still rejects a typo'd type.**+- **Pretty rendering** — `pipe_signature_spec.py` `rendered_pretty` prints `Type: PipeSignature (...)`. Reword to present it as a signature without a type line (e.g. "Signature (contract only)").+- **Fixtures** — 8 bundle files under `tests/e2e/` write `type = "PipeSignature"`; delete the line from each. They double as the regression corpus for "typeless ⟹ signature."+- **Tests** — add: typeless section parses to `PipeSignatureBlueprint`; typeless-with-`prompt` raises the teaching error; explicit `type = "PipeSignature"` raises the migration error; reconciliation of a typeless header against a typed definition still collapses. Existing signature tests (`tests/unit|integration|e2e/.../pipe_signature/`) update to the new surface.+- **Docs** — `docs/building-methods/pipes/signature-pipes.md`, `docs/building-methods/pipes/index.md`, `docs/tools/cli/validate.md`, `docs/tools/cli/agent-cli.md`, error pages, and `pipelex/cli/agent_cli/CLAUDE.md`: teach "omit the type" instead of "set `type = PipeSignature`."++## Migration++Per the workspace "no backward compatibility" rule, we do **not** keep `type = "PipeSignature"` as a silent alias. We reject it — but with a friendly, one-line migration error so anyone with an old bundle knows exactly what to do:++> `PipeSignature` is no longer a pipe type. Delete the `type` line — a pipe with no type and no implementation is a signature.++Same for the spec layer. All in-repo fixtures are migrated in this change, so nothing internal breaks.++## Cross-repo ripple (gated, not in this change)++The MTHDS JSON Schema is copied into downstream repos (`mthds`, `vscode-pipelex`, `mthds-ui`) — see the `mthds-schema-sync` skill. The schema shape changes here (signature arm no longer requires `type`), so those copies drift. That propagation is **gated on a released pipelex version** and handled by the schema-sync skill, not folded into this branch. Flag it in the changelog as a schema change.++## Decisions (settled)++**D1 — Scope: signatures only.** `type` is optional *only* for the signature case. Concrete pipes keep explicit `type`. No inference from fields — it isn't even possible reliably (`prompt` ⟹ PipeLLM *or* PipeImgGen).++**D2 — Typeless + non-contract field = hard error, no leniency.** The only legal typeless shape is exactly a contract (`description`, `inputs`, `output`, `signature_for`). Any other field is a hard error with a teaching message that does **not** guess a type.++**D3 — Explicit `type = "PipeSignature"` is rejected** with a one-line migration error (per the no-backcompat rule). No transitional alias.++**D4 — Keep `signature_for`.** The optional hint stays — harmless, orthogonal, useful to agents.++## Remaining risk to watch during implementation++The JSON-Schema arm (Draft-4, no discriminator) is the one place the disambiguation is non-trivial: the signature arm must omit `type`, forbid extra properties, and still not collide with a typed arm. Verify the editor/Taplo lint (a) accepts a bare `{description, output}` section, (b) rejects a typeless section with a stray field, and (c) rejects a typo'd `type`. Everything else keys off `is_signature` and is mechanical.++## Deferred follow-ups (from the Checkpoint-1 cold review)++**Categorization completeness for a typeless section missing a required contract field.** A typeless `[pipe.x]` whose keys are all contract-legal but that omits a *required* contract field (`description` or `output`) — e.g. a section with only `signature_for`, or an empty stanza — is normalized to a `PipeSignature` and then fails deep in the union with a bare pydantic `type=missing` "Field required" residual at loc `('pipe', <code>, 'PipeSignature', 'output')`. That residual is not matched by any categorizer branch, so it is dropped from the structured `validation_errors[]` (only the raw message survives). The safety invariant still holds — it errors, it is never silently accepted as a mock, and the missing field is named in the raw message (pinned by `test_typeless_section_missing_required_contract_field_still_errors`). This is a **pre-existing, general** gap, not introduced here: a concrete `PipeLLM` missing `output` produces the identical uncategorized residual today. Fixing it properly means a general categorizer branch for pydantic `type=missing` / `extra_forbidden` errors under a `('pipe', <code>, …)` loc (recover `pipe_code` from `loc[1]`, the field from `loc[-1]`), which also changes categorization for concrete pipes — a broader change that deserves its own scoped commit and tests, not this signature-feature change.++**Spec-layer `inputs` is required, unlike the optional blueprint `inputs` (Phase-3 finding).** A no-inputs signature (`{description, output}` only) is valid at the blueprint/language layer (`PipeBlueprint.inputs` defaults to `None`), but the spec/authoring layer requires `inputs` (`PipeSpec.inputs: dict[str, str]` has no default), so a no-inputs signature fails at the spec layer with a raw pydantic `inputs Field required`. This asymmetry **predates this feature** — `PipeSpec.inputs` has always been required — and is orthogonal to the type-tag removal; the single-pipe `pipelex-agent pipe` command and bundle-spec authoring both inherit it (a no-inputs signature can only be authored at the blueprint level, e.g. hand-written `.mthds`). Fixing it means making `PipeSpec`/`PipeSignatureSpec` `inputs` optional to match the blueprint, a small change touching every spec — deferred, out of scope for the type-tag removal.