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.
feat: TOML pipeline inputs + `--format toml` template generation (#1022)
Louis Choquel81e28d6665d9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b23d2d840..f75e88e8f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,11 @@## [Unreleased]+### Added++- **TOML pipeline inputs:** The `--inputs` file passed to `pipelex run` and `pipelex-agent run` (pipe/bundle/method) can now be TOML in addition to JSON, discriminated by file extension — a `.toml` suffix is parsed as TOML, every other value stays JSON. Both formats produce the same input dictionary; TOML's multi-line strings make text-heavy inputs much easier to author. `run bundle <dir>` auto-detects `inputs.toml` alongside `inputs.json` when `--inputs` is omitted, erroring if both exist. Inline JSON (`{...}`) and agent-CLI stdin inputs stay JSON-only. A bare TOML datetime/date/time literal is rejected with an explicit error (quote it as a string) — native datetime concept support is a separate track.+- **`--format toml` for inputs-template generation:** `pipelex build inputs` and `pipelex-agent inputs` (pipe/bundle/method) accept `--format json|toml` (default `json`) to emit the generated inputs template as TOML. On the main CLI, `toml` defaults the output filename to `inputs.toml`; on the agent CLI, `toml` prints the raw TOML template to stdout (the no-inputs case prints a TOML comment line that loads back as an empty dict).+### 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.diff --git a/TODOS.md b/TODOS.mdindex 05f768b90..3438ef2fc 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,173 +1,72 @@-# Implementation plan — PipeSignature is not a type+# TOML pipeline inputs — feature/Inputs-**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+Status: **CHECKPOINT 3 CLEARED (2026-07-06)** — all four phases done and committed. Phases 1+2 (`9041c6986`), Phase 3 (`1fdfd26d0`), Phase 4 docs + changelog (`5ebd9bef2`), with full `make agent-check` + `make agent-test` green. Feature is ready for PR to dev — nothing pushed. This tracker replaces the retired hello-plugin tracker (that track completed and merged to dev via PR #1015).-## Goal in one line+## Goal-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.+Accept pipeline inputs as TOML in addition to JSON, discriminated by file extension, on both CLI surfaces (`pipelex run pipe|bundle|method` and `pipelex-agent run ...`). Also let the input-template generators (`pipelex build inputs ...`, `pipelex-agent inputs ...`) emit TOML via `--format toml`. TOML's multi-line strings make text-heavy inputs much more pleasant to author than JSON.-## Settled decisions (from the design doc)+## Current state (verified against this tree)-- **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.+- Both surfaces take `--inputs` and discriminate by content prefix, not extension: `startswith("{")` → inline JSON, else → JSON file via `load_json_dict_from_path` + `resolve_inputs_paths`. Main CLI: `pipelex/cli/commands/run/_run_core.py:140-164`. Agent CLI: `pipelex/cli/agent_cli/commands/run/stdin_resolver.py` (`parse_cli_inputs` → `_parse_inputs_arg`).+- The agent CLI additionally reads JSON from stdin (flat dict or `working_memory` envelope) — `stdin_resolver.py:_read_stdin_inputs`.+- `run bundle <dir>` auto-detects `inputs.json` (`DEFAULT_INPUTS_FILE_NAME` in `pipelex/builder/conventions.py`) — main `cli/commands/run/bundle_cmd.py:149`, agent `cli/agent_cli/commands/run/bundle_cmd.py:118`.+- TOML loading machinery already exists and is unused on this path: `pipelex/tools/misc/toml_utils.py` (`load_toml_from_path` via `tomli`, raising `TomlError`; `tomlkit` for writing).+- Template generation: main CLI `build inputs` uses `render_inputs` (`pipelex/core/pipes/inputs/input_renderer.py`) → `InputStuffSpecs.render_inputs` (`input_stuff_specs.py:153`) which builds a dict then `json.dumps` — the dict is trivially extractable for a TOML serializer. Agent CLI `inputs` uses `build_inputs_for_pipe` (`pipelex/builder/operations/inputs_ops.py`) which already returns the dict.+- The API runner receives the already-parsed dict, so this feature is purely client-side parsing — no wire or server change.-## Phasing rationale (why this order)+## Decisions (settled with Louis, 2026-07-06)-`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**:+- **D1 — extension discrimination.** `.toml` suffix → TOML loader; every other value (including `.json` and extensionless) keeps today's JSON behavior. No content sniffing.+- **D2 — inline and stdin stay JSON-only.** The `{`-prefix inline path is untouched; inline TOML is ambiguous with file paths. Agent-CLI stdin (flat dict + `working_memory` envelope) stays JSON-only.+- **D3 — auto-detect both, error on ambiguity.** `run bundle <dir>` auto-detects `inputs.toml` alongside `inputs.json`; if both exist, hard error telling the user to pass `--inputs` explicitly.+- **D4 — TOML datetimes rejected for now.** `tomli` parses TOML datetime/date/time into Python objects with no JSON equivalent. Adding `DATETIME` to `NativeConceptCode` is deferred to its own track; until then the loader rejects any datetime-typed value with an explicit not-implemented error.+- **D5 — template generation gets `--format json|toml`** (default `json`) on both surfaces; when `toml` is selected and no explicit output path is given, the default filename becomes `inputs.toml`.+- **D6 — everything lands in pipelex first.** No `docs/specs/` or `conformance/` edits ride this branch: conformance pins the released pipelex, so its tests can't go green until this ships in a release. Spec + conformance + skills + mthds-js sweep is an explicitly deferred follow-up wave (see "Deferred" below).-- **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.+## Phases-One commit per phase (repo convention). Nothing pushed until the user says so.+### Phase 1 — Shared inputs-file loader — DONE----+- [x] New module `pipelex/cli/commands/run/_inputs_file_loader.py`: `load_inputs_dict_from_path(path: Path) -> dict[str, Any]`. Suffix match: `.toml` → `load_toml_from_path`; else → `load_json_dict_from_path`. Also hosts the shared auto-detect probe `find_default_inputs_file(directory)` (D3).+- [x] Datetime guard: recursive walk rejecting `datetime.datetime` / `date` / `time` instances, run on both formats. New `pipelex/cli/commands/run/exceptions.py` with `InputsDatetimeNotSupportedError` and `AmbiguousInputsFilesError` — both carry class-level `error_domain = INPUT` + `user_action` (CHANGE_INPUT), so the agent envelope self-describes and they must NOT get `AGENT_ERROR_HINTS`/`AGENT_ERROR_DOMAINS` entries (enforced by `test_agent_output_drift.py`). Messages include the offending key path (e.g. `record.entries[0].when`) and the quote-as-string workaround.+- [x] `pipelex-dev generate-error-pages` run — new pages `docs/errors/inputs-datetime-not-supported-error.md`, `docs/errors/ambiguous-inputs-files-error.md` (+ index update).+- [x] Unit tests: `tests/unit/pipelex/cli/commands/run/test_inputs_file_loader.py` (loads, extension rule, TomlError, datetime top-level/nested/all four TOML datetime flavors, JsonTypeError, multi-line string) and `test_inputs_file_probe.py` (json-only / toml-only / neither / both-ambiguous).-## Fan-out convention for `/code-review` (used at every checkpoint)+### Phase 2 — Wire into both run surfaces — DONE-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:+- [x] Main CLI `_run_core.py`: swapped to the shared loader; new except branches for `TomlError` and `InputsDatetimeNotSupportedError`; also fixed a pre-existing gap — invalid JSON in an inputs *file* (`json.JSONDecodeError`) previously escaped to the generic traceback handler, now gets a friendly message on both surfaces. The `JsonTypeError` wording stays JSON-specific (it can only fire on the JSON branch).+- [x] Agent CLI `stdin_resolver.py::_parse_inputs_arg`: same swap; `agent_error` branches for `TomlError` / `InputsDatetimeNotSupportedError` / `json.JSONDecodeError`. `AGENT_ERROR_HINTS` + `AGENT_ERROR_DOMAINS` got `TomlError` entries (it has no class-level metadata — kept generic since TomlError also fires outside inputs loading); the two new errors self-describe (see Phase 1).+- [x] Auto-detect + ambiguity (D3): `DEFAULT_INPUTS_TOML_FILE_NAME` in `conventions.py`; both `bundle_cmd.py` sites probe via the shared `find_default_inputs_file`. The probe is skipped entirely when `--inputs` is passed, so the ambiguity rule only bites on auto-detect (both surfaces).+- [x] Verified `run method --inputs relative/path.toml` comes free: main-CLI `method_cmd.py` joins `method_dir / inputs_path` preserving the suffix. Also fixed a pre-existing asymmetry (Louis's call): the *agent* CLI `run method` used to treat `--inputs` as cwd-relative; both surfaces now resolve relative `--inputs` file paths against the method dir via the shared `resolve_inputs_arg_against_dir` helper in `_inputs_file_loader.py` (inline JSON and absolute paths pass through).+- [x] Tests: e2e subprocess dry run with `inputs.toml` + relative `url` resolution (`tests/e2e/pipelex/cli/test_toml_inputs_run.py`, staged csv_demo fixture); main-CLI auto-detect/ambiguity/explicit-bypass (`tests/unit/pipelex/cli/commands/run/test_bundle_cmd_auto_inputs.py`); agent-CLI auto-detect + ambiguity envelope + bypass (`tests/unit/pipelex/cli/agent_cli/test_run_bundle_auto_inputs.py`); `.toml` branch + error envelopes in `test_stdin_resolver.py`; TOML load/resolve + error exits in `test_run_core_execution.py`; method-dir `--inputs` resolution helper (`test_inputs_arg_resolution.py`) + agent `run method` relative-path resolution (`test_run_method_inputs_resolution.py`).-> 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.+**CHECKPOINT 1 — CLEARED 2026-07-06.** TOML inputs load end-to-end on both surfaces; `make agent-check` fully green (pyright/mypy/ruff/keyword-only); the full CLI unit, integration, and e2e test paths pass, including the new subprocess TOML dry run against the real binary. Work is uncommitted — commit before starting Phase 3.-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.+### Phase 3 — Template generation `--format toml` — DONE----+- [x] `InputStuffSpecs.build_inputs_template() -> dict` exposed; `render_inputs` (both the method and the module-level function in `input_renderer.py`) is now the JSON serializer over it.+- [x] TOML serializer `serialize_inputs_template_to_toml` in `pipelex/core/pipes/inputs/input_renderer.py` (tomlkit), plus `render_inputs_toml(pipe)` and the `InputsTemplateFormat` StrEnum (`json|toml`). Verified the generator never emits `None` placeholders (Optionals are unwrapped to their inner type), but the pinned defensive policy is: None → `""` recursively, so keys stay visible in the template (`test_inputs_template_toml.py`).+- [x] Main CLI `pipelex build inputs pipe|bundle|method`: `--format json|toml` (param `template_format`, default `json`); `toml` defaults the output filename to `inputs.toml` (next to bundle / `results/` / method `results/` — all three default-path sites).+- [x] Agent CLI `pipelex-agent inputs pipe|bundle|method`: same `--format json|toml`; `toml` prints the raw TOML template to stdout via shared `emit_inputs_result`/`emit_no_inputs_result` helpers in agent `_inputs_core.py` (no-inputs case prints a TOML comment line — valid TOML, loads as `{}`). Deviation documented in `pipelex/cli/agent_cli/CLAUDE.md` (output-format section + commands table); `test_inputs_format_unaffected.py` reworked to pin the new contract (InputsTemplateFormat, still no `--error-format`).+- [x] Round-trip tests: unit (`test_inputs_template_roundtrip.py` — TOML template loads through the Phase-1 loader identically to its JSON twin) and e2e (`test_toml_inputs_build.py` — real binary generates `inputs.toml` from the csv_demo fixture, then a dry run consumes it).-## Phase 0 — Baseline (quick)+**CHECKPOINT 2 — CLEARED 2026-07-06.** Template generation done on both surfaces; `make agent-check` fully green; targeted CLI + core + builder unit/integration/e2e suites pass (incl. the generate→dry-run e2e chain and a manual raw-TOML smoke of the agent CLI). Committed at this boundary.-- [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 4 — Docs, changelog, final gates — DONE----+- [x] `docs/tools/cli/run.md`: reworked "Input JSON Format" → "Input File Formats" section (extension rule, JSON + TOML examples with multi-line strings, datetime-limitation warning, auto-detect/ambiguity note); all three `--inputs` option lines and the `run bundle` intro updated to mention JSON-or-TOML + inputs-file auto-detect.+- [x] `docs/building-methods/pipes/provide-inputs.md`: new "Input Files: JSON or TOML" section (extension rule, equivalent JSON/TOML example, datetime-limitation warning, pointer to run CLI reference); `build inputs` tip mentions `--format toml`.+- [x] `docs/tools/cli/build/inputs.md`: `--format json|toml` on all three subcommands, `--output` default-filename behavior (`inputs.json`/`inputs.toml`), `--format toml` example, TOML output + multiplicity examples; frontmatter/intro reworded.+- [x] `docs/tools/cli/agent-cli.md`: `run --inputs` JSON-or-TOML + stdin-stays-JSON/auto-detect note; `inputs --format json|toml` deviation note; Output Contract updated for inputs' dual output. (`pipelex/cli/agent_cli/CLAUDE.md` was already updated in Phase 3.)+- [x] `CHANGELOG.md` under `[Unreleased]`: Added — TOML inputs (extension-discriminated) + `--format toml` template generation; TOML-datetime limitation noted.+- [x] Full `make agent-check` (pyright/mypy/ruff/plxt/keyword-only all green) + `make agent-test` (full suite green).-## Phase 1 — Additive typeless-signature support (blueprint + language schema)+**CHECKPOINT 3 (final) — CLEARED 2026-07-06.** All phases done; gates fully green; docs + changelog landed. Phase 4 changes uncommitted at this boundary — commit, then open the PR to dev. Nothing pushed.-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).+## Deferred — follow-up wave AFTER this ships in a pipelex release (NOT this branch)-- [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 1 — STOP--- [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.-------## Phase 2 — Spec (authoring) layer--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()`.--- [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-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).--### ⛔ CHECKPOINT 2 — STOP--- [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.**+- **Spec + conformance sync (D6).** Grep `docs/specs/` (workspace root) for the `--inputs` surface (command-surface-map, protocol spec); add the extension rule + `--format toml` to the spec prose and matching conformance tests with the bidirectional `> Verified by:` ↔ `pytest.mark.spec` links. Gated on the conformance venv's pipelex pin reaching the release that carries this feature (same de-gate pattern as the Optionals track).+- **Skills sweep.** `mthds-plugins` skills (`mthds-run`, `mthds-inputs`) document `inputs.json`; update after release (published plugin, separate repo).+- **mthds-js check.** Verify `mthds-agent` passes `--inputs` through opaquely (no client-side `.json` assumption) — expected no-op.+- **DATETIME native concept.** Add `DATETIME` to `NativeConceptCode`, then replace the Phase-1 datetime guard with real support. Own track.diff --git a/docs/building-methods/pipes/provide-inputs.md b/docs/building-methods/pipes/provide-inputs.mdindex db19acde0..dc8c9e372 100644--- a/docs/building-methods/pipes/provide-inputs.md+++ b/docs/building-methods/pipes/provide-inputs.md@@ -23,7 +23,44 @@ pipelex run bundle path/to/my_pipe.mthds --inputs results/inputs.jsonSee more about the options of the CLI [here](../../tools/cli/index.md).!!! tip "Starting Point for Input Structure"- Use `pipelex build inputs` to quickly understand what inputs your pipeline expects and generate a template to fill in.+ Use `pipelex build inputs` to quickly understand what inputs your pipeline expects and generate a template to fill in. Add `--format toml` to get a TOML template instead of JSON.++## Input Files: JSON or TOML++When you pass an inputs file to `--inputs` (or drop a default inputs file next to a bundle), Pipelex accepts **both JSON and TOML**, discriminated by the file extension — a `.toml` suffix is parsed as TOML, everything else as JSON. Both formats produce the same input dictionary, so every PipelineInputs shape below applies to either. TOML's multi-line strings make text-heavy inputs much easier to author.++The JSON and TOML examples below are equivalent:++**JSON:**+```json+{+ "instructions": "Focus on payment terms.",+ "invoice": {+ "concept": "accounting.Invoice",+ "content": {+ "invoice_number": "INV-001",+ "amount": 1250.00+ }+ }+}+```++**TOML:**+```toml+instructions = "Focus on payment terms."++[invoice]+concept = "accounting.Invoice"++[invoice.content]+invoice_number = "INV-001"+amount = 1250.00+```++!!! warning "TOML datetimes are not supported yet"+ A bare TOML datetime/date/time literal (e.g. `date = 2025-10-20`) is rejected with an explicit error — quote it as a string (`date = "2025-10-20"`) in the meantime.++The rest of this guide shows inputs in JSON (and Python) form; translate any of them to TOML with the same structure. See the [run CLI reference](../../tools/cli/run.md#input-file-formats) for the extension rule and auto-detection behavior.## Understanding PipelineInputs Format@@ -67,9 +104,7 @@ The simplest case - just provide a string directly:**JSON Format:**```json{- "inputs": {- "my_text": "my text"- }+ "my_text": "my text"}```@@ -89,9 +124,7 @@ Provide multiple text items as a list:**JSON Format:**```json{- "inputs": {- "my_texts": ["my text1", "my text2", "my text3"]- }+ "my_texts": ["my text1", "my text2", "my text3"]}```@@ -204,11 +237,9 @@ Use the explicit format `{"concept": "...", "content": "..."}` when you need pre**JSON Format:**```json{- "inputs": {- "text": {- "concept": "Text",- "content": "my text"- }+ "text": {+ "concept": "Text",+ "content": "my text"}}```@@ -233,11 +264,9 @@ inputs = {**JSON Format:**```json{- "inputs": {- "documents": {- "concept": "Text",- "content": ["text1", "text2", "text3"]- }+ "documents": {+ "concept": "Text",+ "content": ["text1", "text2", "text3"]}}```@@ -249,14 +278,12 @@ inputs = {**JSON Format:**```json{- "inputs": {- "invoice_data": {- "concept": "Invoice",- "content": {- "invoice_number": "INV-001",- "amount": 1250.00,- "date": "2025-10-20"- }+ "invoice_data": {+ "concept": "Invoice",+ "content": {+ "invoice_number": "INV-001",+ "amount": 1250.00,+ "date": "2025-10-20"}}}@@ -299,20 +326,18 @@ This explicitly tells Pipelex to use the `Invoice` concept from the `accounting`**JSON Format:**```json{- "inputs": {- "invoices": {- "concept": "Invoice",- "content": [- {- "invoice_number": "INV-001",- "amount": 1250.00- },- {- "invoice_number": "INV-002",- "amount": 890.00- }- ]- }+ "invoices": {+ "concept": "Invoice",+ "content": [+ {+ "invoice_number": "INV-001",+ "amount": 1250.00+ },+ {+ "invoice_number": "INV-002",+ "amount": 890.00+ }+ ]}}```@@ -326,15 +351,13 @@ Provide structured data as a dictionary:**JSON Format:**```json{- "inputs": {- "person": {- "concept": "PersonInfo",- "content": {- "arg1": "something",- "arg2": 1,- "arg3": {- "arg4": "something else"- }+ "person": {+ "concept": "PersonInfo",+ "content": {+ "arg1": "something",+ "arg2": 1,+ "arg3": {+ "arg4": "something else"}}}@@ -352,22 +375,20 @@ The system will:**JSON Format:**```json{- "inputs": {- "people": {- "concept": "PersonInfo",- "content": [- {- "arg1": "something",- "arg2": 1,- "arg3": {"arg4": "something else"}- },- {- "arg1": "something else",- "arg2": 2,- "arg3": {"arg4": "something else else"}- }- ]- }+ "people": {+ "concept": "PersonInfo",+ "content": [+ {+ "arg1": "something",+ "arg2": 1,+ "arg3": {"arg4": "something else"}+ },+ {+ "arg1": "something else",+ "arg2": 2,+ "arg3": {"arg4": "something else else"}+ }+ ]}}```@@ -533,22 +554,20 @@ inputs = {```json{- "inputs": {- "text": "Analyze this contract for risks.",- "category": {- "concept": "Category",- "content": {- "name": "legal",- "priority": "high"- }- },- "options": ["option1", "option2", "option3"],- "invoice": {- "concept": "accounting.Invoice",- "content": {- "invoice_number": "INV-001",- "amount": 1250.00- }+ "text": "Analyze this contract for risks.",+ "category": {+ "concept": "Category",+ "content": {+ "name": "legal",+ "priority": "high"+ }+ },+ "options": ["option1", "option2", "option3"],+ "invoice": {+ "concept": "accounting.Invoice",+ "content": {+ "invoice_number": "INV-001",+ "amount": 1250.00}}}diff --git a/docs/errors/ambiguous-inputs-files-error.md b/docs/errors/ambiguous-inputs-files-error.mdnew file mode 100644index 000000000..bd1a8e221--- /dev/null+++ b/docs/errors/ambiguous-inputs-files-error.md@@ -0,0 +1,22 @@+---+title: "Ambiguous inputs files"+description: "Reference for the `AmbiguousInputsFilesError` Pipelex error class."+---++<!-- pipelex:generated -->++# Ambiguous inputs files++Raised when a bundle directory holds both default inputs files on auto-detect.++| Field | Value |+|---|---|+| `error_type` | `AmbiguousInputsFilesError` |+| `title` | Ambiguous inputs files |+| `type_uri` | `https://docs.pipelex.com/latest/errors/ambiguous-inputs-files-error/` |+| `error_domain` | `input` |+| Defined in | `pipelex.cli.commands.run.exceptions` |+| Parent class | [`PipelexError`](pipelex-error.md) |+| `user_action` | `change_input` — Pass --inputs explicitly to choose which inputs file to use |++[Back to Error Reference](index.md)diff --git a/docs/errors/inputs-datetime-not-supported-error.md b/docs/errors/inputs-datetime-not-supported-error.mdnew file mode 100644index 000000000..6b51fe450--- /dev/null+++ b/docs/errors/inputs-datetime-not-supported-error.md@@ -0,0 +1,22 @@+---+title: "Inputs datetime not supported"+description: "Reference for the `InputsDatetimeNotSupportedError` Pipelex error class."+---++<!-- pipelex:generated -->++# Inputs datetime not supported++Raised when a loaded inputs file carries a TOML datetime/date/time value.++| Field | Value |+|---|---|+| `error_type` | `InputsDatetimeNotSupportedError` |+| `title` | Inputs datetime not supported |+| `type_uri` | `https://docs.pipelex.com/latest/errors/inputs-datetime-not-supported-error/` |+| `error_domain` | `input` |+| Defined in | `pipelex.cli.commands.run.exceptions` |+| Parent class | [`PipelexError`](pipelex-error.md) |+| `user_action` | `change_input` — Quote the datetime as a string in the inputs file (e.g. "2026-07-06"); native TOML datetime inputs are not supported yet |++[Back to Error Reference](index.md)diff --git a/docs/errors/platform-and-tooling.md b/docs/errors/platform-and-tooling.mdindex 1d11f8ff8..d09722b64 100644--- a/docs/errors/platform-and-tooling.md+++ b/docs/errors/platform-and-tooling.md@@ -87,6 +87,8 @@ own page. Classes are grouped by subsystem.## CLI+- [`AmbiguousInputsFilesError`](ambiguous-inputs-files-error.md) — Ambiguous inputs files+- [`InputsDatetimeNotSupportedError`](inputs-datetime-not-supported-error.md) — Inputs datetime not supported- [`PipelexCLIError`](pipelex-cli-error.md) — Pipelex CLI- [`ReadinessCheckError`](readiness-check-error.md) — Readiness checkdiff --git a/docs/tools/cli/agent-cli.md b/docs/tools/cli/agent-cli.mdindex c3b6cd5b6..eefbcbf6c 100644--- a/docs/tools/cli/agent-cli.md+++ b/docs/tools/cli/agent-cli.md@@ -32,7 +32,7 @@ pipelex-agent run method <NAME> [OPTIONS]**Common options:**-- `--inputs`, `-i` - Path to JSON input file+- `--inputs`, `-i` - Path to a JSON or TOML inputs file (discriminated by file extension: `.toml` → TOML, everything else → JSON). Inline JSON (a value starting with `{`) stays JSON-only.- `--dry-run` - Dry-run without calling AI providers- `--mock-inputs` - Use mock inputs- `--graph` / `--no-graph` - Enable/disable execution graph (enabled by default)@@ -43,6 +43,9 @@ pipelex-agent run method <NAME> [OPTIONS]For `bundle` and `method`, use `--pipe` to target a specific pipe.+!!! note "Stdin inputs stay JSON"+ The agent CLI can also read inputs from stdin (a flat dict or a `working_memory` envelope). Stdin inputs are **JSON-only** — the extension-based TOML discrimination applies to `--inputs` file paths only. Like the main CLI, `run bundle <dir>` auto-detects `inputs.json` / `inputs.toml` when `--inputs` is omitted, erroring if both exist.+### ValidateValidate pipes, bundles, or methods. Success output is markdown by default, or JSON with `--format json`. Errors follow `--error-format` (defaults to `--format`'s value).@@ -75,7 +78,7 @@ For `bundle`, additional options are available:### Inputs-Generate example input JSON for a pipe, bundle, or method.+Generate an example inputs template for a pipe, bundle, or method.```bashpipelex-agent inputs pipe <PIPE_CODE> [OPTIONS]@@ -86,9 +89,13 @@ pipelex-agent inputs method <NAME> [OPTIONS]**Common options:**- `--library-dir`, `-L` - Additional library directory+- `--format` - Template serialization: `json` (default) or `toml`For `bundle` and `method`, use `--pipe` to target a specific pipe.+!!! note "`inputs --format` is `json|toml`, not `markdown|json`"+ Unlike `run`/`validate`, the `inputs` command's `--format` selects the **template serialization**, not a presentation style. `json` (the default) emits the structured JSON success envelope; `toml` prints the raw TOML template straight to stdout (a pipe with no inputs prints a TOML comment line, which loads back as an empty dict). This mirrors the raw-TOML output of the `concept` and `pipe` commands. `inputs` has no `--error-format` — its errors stay JSON.+### Flat CommandsThese commands do not have subcommands:@@ -107,7 +114,7 @@ These commands do not have subcommands:Commands use different stdout formats depending on their purpose:- **Markdown or JSON**: `run`, `validate`, `init`, `models`, `check-model`, `doctor` — markdown by default, JSON with `--format json`. Error format follows `--error-format` (defaults to `--format`'s value, so `--format json` flips both).-- **JSON**: `inputs` — structured JSON via `agent_success()`+- **JSON or raw TOML**: `inputs` — structured JSON via `agent_success()` by default (`--format json`), or the raw TOML template printed directly to stdout with `--format toml`- **Raw TOML**: `concept`, `pipe` — TOML text printed directly to stdout- **Passthrough**: `fmt`, `lint` — raw `plxt` outputdiff --git a/docs/tools/cli/build/inputs.md b/docs/tools/cli/build/inputs.mdindex 3c81149ee..4443c2640 100644--- a/docs/tools/cli/build/inputs.md+++ b/docs/tools/cli/build/inputs.md@@ -1,10 +1,10 @@----description: "Generate example input JSON for any pipe — see the expected input structure based on the pipe's declared input types in .mthds files."+description: "Generate an example inputs template (JSON or TOML) for any pipe — see the expected input structure based on the pipe's declared input types in .mthds files."---# Build Inputs-Generate example input JSON for a pipe, showing the expected input structure based on the pipe's input types.+Generate an example inputs template for a pipe, showing the expected input structure based on the pipe's input types. The template is emitted as JSON by default, or as TOML with `--format toml`.## Usage@@ -21,7 +21,8 @@ pipelex build inputs pipe <PIPE_CODE> [OPTIONS]**Options:**- `--library-dir`, `-L` - Directory to search for pipe definitions. Can be specified multiple times.-- `--output`, `-o` - Path to save the generated JSON file (defaults to `results/`)+- `--output`, `-o` - Path to save the generated inputs file (defaults to `results/`, filename `inputs.json` or `inputs.toml` depending on `--format`)+- `--format` - Template format: `json` (default) or `toml`### From a bundle@@ -37,7 +38,8 @@ pipelex build inputs bundle <PATH> [OPTIONS]- `--pipe` - Pipe code to use (can be omitted if the bundle declares a `main_pipe`)- `--library-dir`, `-L` - Directory to search for pipe definitions. Can be specified multiple times.-- `--output`, `-o` - Path to save the generated JSON file (defaults to bundle's directory)+- `--output`, `-o` - Path to save the generated inputs file (defaults to the bundle's directory, filename `inputs.json` or `inputs.toml` depending on `--format`)+- `--format` - Template format: `json` (default) or `toml`### From an installed method@@ -53,7 +55,8 @@ pipelex build inputs method <NAME> [OPTIONS]- `--pipe` - Pipe code (overrides method's `main_pipe`)- `--library-dir`, `-L` - Directory to search for pipe definitions. Can be specified multiple times.-- `--output`, `-o` - Path to save the generated JSON file+- `--output`, `-o` - Path to save the generated inputs file (filename `inputs.json` or `inputs.toml` depending on `--format`)+- `--format` - Template format: `json` (default) or `toml`## Examples@@ -93,9 +96,19 @@ pipelex build inputs pipe my_domain.my_pipe -L ./my_library/pipelex build inputs bundle my_bundle.mthds --output custom_inputs.json```+**Generate a TOML template instead of JSON:**++```bash+pipelex build inputs bundle my_bundle.mthds --format toml+```++When `--format toml` is selected and no explicit `--output` is given, the default filename becomes `inputs.toml` (instead of `inputs.json`).+## Output Format-The generated JSON file contains all inputs required by the pipe, with example values based on each input's concept type:+The generated file contains all inputs required by the pipe, with example values based on each input's concept type. Both formats carry the same structure — [`pipelex run`](../run.md#input-file-formats) accepts either.++**JSON (`--format json`, default):**```json{@@ -114,6 +127,22 @@ The generated JSON file contains all inputs required by the pipe, with example v}```+**TOML (`--format toml`):**++```toml+[text_input]+concept = "native.Text"++[text_input.content]+text = "text_value"++[document_input]+concept = "native.Document"++[document_input.content]+url = "url_value"+```+### Multiplicity SupportWhen an input has multiplicity (accepts multiple items), the content is wrapped in a list:@@ -131,6 +160,16 @@ When an input has multiplicity (accepts multiple items), the content is wrapped}```+In TOML, the same list of items uses the array-of-tables syntax:++```toml+[documents]+concept = "native.Document"++[[documents.content]]+url = "url_value"+```+## Use Cases- **Understanding pipe requirements** - Quickly see what inputs a pipe expectsdiff --git a/docs/tools/cli/run.md b/docs/tools/cli/run.mdindex 32e126eb6..8358cf4da 100644--- a/docs/tools/cli/run.md+++ b/docs/tools/cli/run.md@@ -28,7 +28,7 @@ Runs a pipe by code from your project's pipe library.**Options:**-- `--inputs`, `-i` - Path to JSON file containing inputs+- `--inputs`, `-i` - Path to a JSON or TOML file containing inputs (discriminated by file extension — see [Input File Formats](#input-file-formats))- `--output-dir`, `-o` - Directory to save outputs (defaults to `results/`)- `--save-main-stuff` / `--no-save-main-stuff` - Whether to save the main output to a file- `--save-working-memory` / `--no-save-working-memory` - Whether to save the full working memory@@ -72,7 +72,7 @@ pipelex run pipe my_pipe -L ./pipelines -L ./shared_pipespipelex run bundle <PATH> [OPTIONS]```-Runs a pipeline from a bundle file (`.mthds`) or a pipeline directory. When a directory is given, the bundle file is auto-detected inside it.+Runs a pipeline from a bundle file (`.mthds`) or a pipeline directory. When a directory is given, the bundle file is auto-detected inside it — and so is an inputs file (`inputs.json` or `inputs.toml`) when `--inputs` is not passed (see [Input File Formats](#input-file-formats)).**Arguments:**@@ -81,7 +81,7 @@ Runs a pipeline from a bundle file (`.mthds`) or a pipeline directory. When a di**Options:**- `--pipe PIPE_CODE` - Run a specific pipe from the bundle (defaults to the bundle's main pipe)-- `--inputs`, `-i` - Path to JSON file containing inputs+- `--inputs`, `-i` - Path to a JSON or TOML file containing inputs (discriminated by file extension — see [Input File Formats](#input-file-formats))- `--output-dir`, `-o` - Directory to save outputs- `--save-main-stuff` / `--no-save-main-stuff` - Whether to save the main output- `--save-working-memory` / `--no-save-working-memory` - Whether to save the full working memory@@ -128,7 +128,7 @@ Runs a pipeline from an installed method package.**Options:**- `--pipe PIPE_CODE` - Run a specific pipe within the method (defaults to the method's main pipe)-- `--inputs`, `-i` - Path to JSON file containing inputs+- `--inputs`, `-i` - Path to a JSON or TOML file containing inputs (discriminated by file extension — see [Input File Formats](#input-file-formats))- `--output-dir`, `-o` - Directory to save outputs- `--save-main-stuff` / `--no-save-main-stuff` - Whether to save the main output- `--save-working-memory` / `--no-save-working-memory` - Whether to save the full working memory@@ -154,9 +154,18 @@ pipelex run method invoice_extractor --pipe extract_amountspipelex run method invoice_extractor --inputs invoice_data.json```-## Input JSON Format+## Input File Formats-The input JSON file should contain a dictionary where keys are input variable names:+An inputs file is a dictionary whose keys are input variable names. Pipelex accepts **both JSON and TOML**, discriminated by the file extension:++- A `.toml` suffix is parsed as TOML.+- Every other value — `.json`, no extension, anything else — is parsed as JSON.++There is no content sniffing: the extension alone decides. Inline JSON passed to `--inputs` (a value starting with `{`) stays JSON-only.++Both formats produce the same input dictionary for the value types they share, so the [PipelineInputs shapes](../../building-methods/pipes/provide-inputs.md) apply to both — with one structural exception: JSON `null` has no TOML equivalent (TOML has no null type).++### JSON```json{@@ -168,6 +177,32 @@ The input JSON file should contain a dictionary where keys are input variable na}```+### TOML++The same inputs in TOML. TOML's multi-line strings (`"""..."""`) make text-heavy inputs far more pleasant to author than escaped JSON:++```toml+input_variable = "simple string value"++instructions = """+Focus on payment terms.+Flag anything that looks unusual.+"""++[another_input]+concept = "domain_code.ConceptName"++[another_input.content]+field = "value"+```++!!! warning "TOML datetimes are not supported yet"+ TOML parses bare datetime/date/time literals (e.g. `when = 2026-07-06`) into typed objects that have no JSON equivalent and no native concept yet, so the loader rejects them with an explicit error. Quote such values as strings (`when = "2026-07-06"`) in the meantime.++### Auto-detection and ambiguity++`run bundle <dir>` auto-detects a default inputs file inside the directory when `--inputs` is omitted: it looks for `inputs.json`, then `inputs.toml`. If **both** exist, the run fails with an ambiguity error asking you to pass `--inputs` explicitly — passing `--inputs` always bypasses auto-detection.+## Output FormatThe output JSON contains the complete working memory after pipeline execution, including all intermediate results and the final output.diff --git a/pipelex/builder/conventions.py b/pipelex/builder/conventions.pyindex 01ad111fd..e61b46194 100644--- a/pipelex/builder/conventions.py+++ b/pipelex/builder/conventions.py@@ -8,3 +8,4 @@ from pipelex.core.interpreter.helpers import MTHDS_EXTENSIONDEFAULT_BUNDLE_FILE_NAME = f"bundle{MTHDS_EXTENSION}"DEFAULT_INPUTS_FILE_NAME = "inputs.json"+DEFAULT_INPUTS_TOML_FILE_NAME = "inputs.toml"diff --git a/pipelex/cli/agent_cli/CLAUDE.md b/pipelex/cli/agent_cli/CLAUDE.mdindex 9a349288c..8fcfc826c 100644--- a/pipelex/cli/agent_cli/CLAUDE.md+++ b/pipelex/cli/agent_cli/CLAUDE.md@@ -11,7 +11,9 @@ Two independent options control the two output streams:Only the error format is backed by a module-level `ContextVar` in `agent_output.py` (`_agent_cli_error_format`). The reason: `agent_error()` is called from sites that don't see the Typer option — factory init failures (`agent_cli_factory.py`), the unknown-command handler in `PipelexAgentCLI.get_command`, log-level/runner validation in the app callback, and any future site in shared library/runtime code. The ContextVar lets all of them honor `--error-format` (or `--format`'s inherited value) for free. JSON is the default so errors raised before any command opts in stay machine-parseable.-`inputs`, `concept`, `pipe`, `fmt`, `lint`, `accept-gateway-terms` are **always JSON / raw passthrough** — they have neither `--format` nor `--error-format`. Their errors keep flowing through the ContextVar's JSON default.+`concept`, `pipe`, `fmt`, `lint`, `accept-gateway-terms` are **always JSON / raw passthrough** — they have neither `--format` nor `--error-format`. Their errors keep flowing through the ContextVar's JSON default.++`inputs` is a deliberate deviation: its `--format` takes `json|toml` (an `InputsTemplateFormat`, NOT the `markdown|json` `CliOutputFormat` pair) because it selects the **template serialization**, not a presentation style. `json` (default) keeps the structured success envelope; `toml` prints the raw TOML template to stdout, in the same spirit as the `concept`/`pipe` raw-TOML passthrough. A pipe with no inputs prints a TOML comment line in `toml` mode (valid TOML, loads back as an empty dict). `inputs` still has no `--error-format` — its errors keep flowing through the ContextVar's JSON default.Markdown structure per command:@@ -80,7 +82,7 @@ commands/| `validate` | Dry-runs pipes/bundles/methods (pipe\|bundle\|method subcommands), returns validation status per pipe. Bundle subcommand supports `--graph` for graph visualization (with `--graph-format` for the graph renderer). `--format markdown\|json` (success, default: markdown) + `--error-format markdown\|json` (errors, defaults to `--format`'s value). || `fmt` | Formats a .mthds/.toml/.plx file in-place (delegates to plxt) || `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) |+| `inputs` | Generates an example inputs template for a pipe/bundle/method (pipe\|bundle\|method subcommands). `--format json\|toml` (template serialization, default: json — NOT the markdown\|json pair); `toml` prints raw TOML to stdout || `concept` | Converts a JSON concept spec into raw TOML (stdout) || `pipe` | Converts a JSON pipe spec into raw TOML (stdout). A spec with a `type` (via `--type` or a `type` key) is that concrete pipe; a **typeless** spec (no `type`) is a signature and renders a `[pipe.x]` section with no type line. An explicit `type = "PipeSignature"` is rejected with a migration error — `PipeSignature` is not a type. || `models` | Lists available model presets, aliases, and waterfalls. `--format markdown\|json` (success, default: markdown) + `--error-format markdown\|json` (errors, defaults to `--format`'s value) |diff --git a/pipelex/cli/agent_cli/commands/agent_output.py b/pipelex/cli/agent_cli/commands/agent_output.pyindex 7f5554126..bca12cef7 100644--- a/pipelex/cli/agent_cli/commands/agent_output.py+++ b/pipelex/cli/agent_cli/commands/agent_output.py@@ -138,6 +138,7 @@ AGENT_ERROR_HINTS: dict[str, str] = {"GraphSpecParseError": "Validate graphspec.json structure; ensure it matches the expected GraphSpec schema",# Input/type errors"JsonTypeError": "Input file must be a JSON object {...}, not an array or scalar value",+ "TomlError": "Fix the TOML syntax error (the message includes the line and column)","BundleError": "Bundle must declare a 'main_pipe' or use the --pipe flag to specify which pipe to run","ValidationError": "Check that spec fields match the expected schema for the given type","ValueError": "Check that the provided value is valid for the parameter (e.g., --type must be a valid pipe type)",@@ -160,6 +161,7 @@ AGENT_ERROR_DOMAINS: dict[str, str] = {"FileNotFoundError": "input","JSONDecodeError": "input","JsonTypeError": "input",+ "TomlError": "input","ArgumentError": "input","ValidationError": "input","ValueError": "input",diff --git a/pipelex/cli/agent_cli/commands/inputs/_inputs_core.py b/pipelex/cli/agent_cli/commands/inputs/_inputs_core.pyindex b64c4ace7..b6d43b202 100644--- a/pipelex/cli/agent_cli/commands/inputs/_inputs_core.py+++ b/pipelex/cli/agent_cli/commands/inputs/_inputs_core.py@@ -1,10 +1,12 @@-"""Core logic for generating input JSON in the agent CLI."""+"""Core logic for generating inputs templates in the agent CLI."""from __future__ import annotationsfrom typing import TYPE_CHECKING, Anyfrom pipelex.builder.operations.inputs_ops import build_inputs_for_pipe+from pipelex.cli.agent_cli.commands.agent_output import agent_success+from pipelex.core.pipes.inputs.input_renderer import InputsTemplateFormat, serialize_inputs_template_to_tomlif TYPE_CHECKING:from pathlib import Path@@ -35,3 +37,47 @@ async def inputs_core(bundle_path=bundle_path,library_dirs=library_dirs,)+++def emit_inputs_result(result: dict[str, Any], *, template_format: InputsTemplateFormat) -> None:+ """Emit an inputs-generation result in the requested template format.++ JSON keeps the structured success envelope; TOML prints the raw template to+ stdout, in the same spirit as the ``concept``/``pipe`` raw-TOML passthrough+ commands.++ Args:+ result: The inputs-generation result (``success``/``pipe_code``/``inputs``).+ template_format: The requested inputs template format.+ """+ match template_format:+ case InputsTemplateFormat.JSON:+ agent_success(result)+ case InputsTemplateFormat.TOML:+ toml_content = serialize_inputs_template_to_toml(result["inputs"])+ print(toml_content, end="" if toml_content.endswith("\n") else "\n")+++def emit_no_inputs_result(pipe_code: str | None, *, message: str, template_format: InputsTemplateFormat) -> None:+ """Emit the not-an-error result for a pipe that requires no inputs.++ JSON keeps the structured envelope with an empty ``inputs`` dict; TOML+ prints a comment line — valid TOML that loads back as an empty dict.++ Args:+ pipe_code: The pipe code the inputs were requested for, if known.+ message: The human-readable no-inputs-required message.+ template_format: The requested inputs template format.+ """+ match template_format:+ case InputsTemplateFormat.JSON:+ agent_success(+ {+ "success": True,+ "pipe_code": pipe_code,+ "inputs": {},+ "message": message,+ }+ )+ case InputsTemplateFormat.TOML:+ print(f"# {message}")diff --git a/pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py b/pipelex/cli/agent_cli/commands/inputs/bundle_cmd.pyindex 4f4ff5583..dabad130d 100644--- a/pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py+++ b/pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py@@ -10,11 +10,12 @@ import typerfrom pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_cli-from pipelex.cli.agent_cli.commands.agent_output import agent_error, agent_success, extract_validation_errors-from pipelex.cli.agent_cli.commands.inputs._inputs_core import inputs_core+from pipelex.cli.agent_cli.commands.agent_output import agent_error, extract_validation_errors+from pipelex.cli.agent_cli.commands.inputs._inputs_core import emit_inputs_result, emit_no_inputs_result, inputs_corefrom pipelex.core.interpreter.helpers import MTHDS_EXTENSION, is_pipelex_filefrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.core.pipes.inputs.exceptions import NoInputsRequiredError+from pipelex.core.pipes.inputs.input_renderer import InputsTemplateFormatfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import Pipelexfrom pipelex.pipeline.exceptions import ValidateBundleError@@ -33,16 +34,22 @@ def inputs_bundle_cmd(list[str] | None,typer.Option("--library-dir", "-L", help="Directory to search for pipe definitions (.mthds files)"),] = None,+ template_format: Annotated[+ InputsTemplateFormat,+ typer.Option("--format", help="Inputs template format: 'json' for the JSON result envelope (default), 'toml' for raw TOML on stdout"),+ ] = InputsTemplateFormat.JSON,) -> None:- """Generate example input JSON from a bundle file (.mthds) or pipeline directory.+ """Generate an example inputs template from a bundle file (.mthds) or pipeline directory.- Outputs JSON to stdout on success, JSON to stderr on error with exit code 1.+ Outputs the JSON envelope (or raw TOML with --format toml) to stdout on+ success, JSON to stderr on error with exit code 1.Examples:pipelex-agent inputs bundle my_bundle.mthdspipelex-agent inputs bundle my_bundle.mthds --pipe my_pipepipelex-agent inputs bundle pipeline_01/pipelex-agent inputs bundle pipeline_01/ --pipe my_pipe+ pipelex-agent inputs bundle pipeline_01/ --format toml"""bundle_path: str | None = Nonetarget_path = Path(path)@@ -87,7 +94,7 @@ def inputs_bundle_cmd(try:result = asyncio.run(inputs_core(pipe_code=pipe_code, bundle_path=Path(bundle_path), library_dirs=library_dirs)) # type: ignore[arg-type]- agent_success(result)+ emit_inputs_result(result, template_format=template_format)except FileNotFoundError as exc:agent_error(f"Bundle file not found: {bundle_path}", error_type="FileNotFoundError", cause=exc)@@ -100,14 +107,7 @@ def inputs_bundle_cmd(agent_error(exc.message, error_type="ValidateBundleError", cause=exc, **extra)except NoInputsRequiredError as exc:- agent_success(- {- "success": True,- "pipe_code": pipe_code,- "inputs": {},- "message": str(exc),- }- )+ emit_no_inputs_result(pipe_code, message=str(exc), template_format=template_format)except PipeOperatorModelChoiceError as exc:agent_error(diff --git a/pipelex/cli/agent_cli/commands/inputs/method_cmd.py b/pipelex/cli/agent_cli/commands/inputs/method_cmd.pyindex 223f50c3e..6ac0baffb 100644--- a/pipelex/cli/agent_cli/commands/inputs/method_cmd.py+++ b/pipelex/cli/agent_cli/commands/inputs/method_cmd.py@@ -9,11 +9,12 @@ from typing import Annotated, Anyimport typerfrom pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_cli-from pipelex.cli.agent_cli.commands.agent_output import agent_error, agent_success, extract_validation_errors-from pipelex.cli.agent_cli.commands.inputs._inputs_core import inputs_core+from pipelex.cli.agent_cli.commands.agent_output import agent_error, extract_validation_errors+from pipelex.cli.agent_cli.commands.inputs._inputs_core import emit_inputs_result, emit_no_inputs_result, inputs_corefrom pipelex.cli.method_resolver import resolve_method_targetfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.core.pipes.inputs.exceptions import NoInputsRequiredError+from pipelex.core.pipes.inputs.input_renderer import InputsTemplateFormatfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import Pipelexfrom pipelex.pipeline.exceptions import ValidateBundleError@@ -32,14 +33,21 @@ def inputs_method_cmd(list[str] | None,typer.Option("--library-dir", "-L", help="Directory to search for pipe definitions (.mthds files)"),] = None,+ template_format: Annotated[+ InputsTemplateFormat,+ typer.Option("--format", help="Inputs template format: 'json' for the JSON result envelope (default), 'toml' for raw TOML on stdout"),+ ] = InputsTemplateFormat.JSON,) -> None:- """Generate example input JSON for an installed method and output JSON results.+ """Generate an example inputs template for an installed method.Resolves the method by name, finds its .mthds bundle, and generates inputs.+ Outputs the JSON envelope (or raw TOML with --format toml) to stdout on+ success, JSON to stderr on error with exit code 1.Examples:pipelex-agent inputs method my-methodpipelex-agent inputs method my-method --pipe custom_pipe+ pipelex-agent inputs method my-method --format toml"""pipe_code, method_library_dirs, method = resolve_method_target(method_name=name,@@ -59,7 +67,7 @@ def inputs_method_cmd(try:result = asyncio.run(inputs_core(pipe_code=pipe_code, bundle_path=bundle_path, library_dirs=library_dirs_paths))- agent_success(result)+ emit_inputs_result(result, template_format=template_format)except FileNotFoundError as exc:agent_error(f"Bundle file not found: {bundle_path}", error_type="FileNotFoundError", cause=exc)@@ -72,14 +80,7 @@ def inputs_method_cmd(agent_error(exc.message, error_type="ValidateBundleError", cause=exc, **extra)except NoInputsRequiredError as exc:- agent_success(- {- "success": True,- "pipe_code": pipe_code,- "inputs": {},- "message": str(exc),- }- )+ emit_no_inputs_result(pipe_code, message=str(exc), template_format=template_format)except PipeOperatorModelChoiceError as exc:agent_error(diff --git a/pipelex/cli/agent_cli/commands/inputs/pipe_cmd.py b/pipelex/cli/agent_cli/commands/inputs/pipe_cmd.pyindex a37b251dc..fa9e5d9e1 100644--- a/pipelex/cli/agent_cli/commands/inputs/pipe_cmd.py+++ b/pipelex/cli/agent_cli/commands/inputs/pipe_cmd.py@@ -9,12 +9,13 @@ from typing import Annotated, Anyimport typerfrom pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_cli-from pipelex.cli.agent_cli.commands.agent_output import agent_error, agent_success, extract_validation_errors-from pipelex.cli.agent_cli.commands.inputs._inputs_core import inputs_core+from pipelex.cli.agent_cli.commands.agent_output import agent_error, extract_validation_errors+from pipelex.cli.agent_cli.commands.inputs._inputs_core import emit_inputs_result, emit_no_inputs_result, inputs_corefrom pipelex.cli.method_resolver import resolve_pipe_from_exportsfrom pipelex.core.interpreter.helpers import MTHDS_EXTENSION, is_pipelex_filefrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.core.pipes.inputs.exceptions import NoInputsRequiredError+from pipelex.core.pipes.inputs.input_renderer import InputsTemplateFormatfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import Pipelexfrom pipelex.pipeline.exceptions import ValidateBundleError@@ -29,14 +30,20 @@ def inputs_pipe_cmd(list[str] | None,typer.Option("--library-dir", "-L", help="Directory to search for pipe definitions (.mthds files)"),] = None,+ template_format: Annotated[+ InputsTemplateFormat,+ typer.Option("--format", help="Inputs template format: 'json' for the JSON result envelope (default), 'toml' for raw TOML on stdout"),+ ] = InputsTemplateFormat.JSON,) -> None:- """Generate example input JSON for a pipe by code and output JSON results.+ """Generate an example inputs template for a pipe by code.- Outputs JSON to stdout on success, JSON to stderr on error with exit code 1.+ Outputs the JSON envelope (or raw TOML with --format toml) to stdout on+ success, JSON to stderr on error with exit code 1.Examples:pipelex-agent inputs pipe my_pipepipelex-agent inputs pipe my_pipe -L ./my_pipes+ pipelex-agent inputs pipe my_pipe --format toml"""# Helpful error if the user passes a path instead of a pipe codetarget_path = Path(pipe_code)@@ -67,7 +74,7 @@ def inputs_pipe_cmd(try:result = asyncio.run(inputs_core(pipe_code=pipe_code, bundle_path=None, library_dirs=library_dirs))- agent_success(result)+ emit_inputs_result(result, template_format=template_format)except FileNotFoundError as exc:agent_error(f"File not found: {exc}", error_type="FileNotFoundError", cause=exc)@@ -81,14 +88,7 @@ def inputs_pipe_cmd(except NoInputsRequiredError as exc:# Not really an error - just a pipe with no inputs- agent_success(- {- "success": True,- "pipe_code": pipe_code,- "inputs": {},- "message": str(exc),- }- )+ emit_no_inputs_result(pipe_code, message=str(exc), template_format=template_format)except PipeOperatorModelChoiceError as exc:agent_error(diff --git a/pipelex/cli/agent_cli/commands/run/bundle_cmd.py b/pipelex/cli/agent_cli/commands/run/bundle_cmd.pyindex 3624891d5..2a618defd 100644--- a/pipelex/cli/agent_cli/commands/run/bundle_cmd.py+++ b/pipelex/cli/agent_cli/commands/run/bundle_cmd.py@@ -10,7 +10,7 @@ from typing import Annotated, Anyimport typerfrom mthds.runners.types import RunnerType-from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAME, DEFAULT_INPUTS_FILE_NAME+from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.cli.agent_cli.commands.agent_cli_factory import make_pipelex_for_agent_clifrom pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, agent_error, agent_success_formatted, set_agent_cli_error_formatfrom pipelex.cli.agent_cli.commands.run._output_helpers import format_run_markdown@@ -93,7 +93,7 @@ def run_bundle_cmd(pipe_code: str | None = pipebundle_path: str | None = None- auto_inputs_path: str | None = None+ auto_inputs_dir: Path | None = Nonetarget_path = Path(path)if target_path.is_dir():@@ -114,9 +114,10 @@ def run_bundle_cmd()bundle_path = str(mthds_files[0])- # Auto-detect inputs file (used as low-priority fallback)- inputs_file = target_path / DEFAULT_INPUTS_FILE_NAME- auto_inputs_path = str(inputs_file) if inputs_file.is_file() else None+ # Hand the directory to parse_cli_inputs as the lowest-priority inputs source: it probes+ # for inputs.json / inputs.toml (and applies the ambiguity rule) only after --inputs and+ # stdin are ruled out, so an ambiguous dir can't pre-empt an explicit flag or piped stdin.+ auto_inputs_dir = target_path# Add directory as library dir (prepend to user-supplied list)target_dir_str = str(target_path)@@ -155,7 +156,7 @@ def run_bundle_cmd(agent_error(f"Failed to parse bundle '{bundle_path}': {exc}", error_type=type(exc).__name__, cause=exc)# Load inputs: --inputs flag takes priority, then stdin fallback, then auto-detected- pipeline_inputs: dict[str, Any] | None = parse_cli_inputs(inputs_arg=inputs, stdin_fallback=True, auto_inputs_path=auto_inputs_path)+ pipeline_inputs: dict[str, Any] | None = parse_cli_inputs(inputs_arg=inputs, stdin_fallback=True, auto_inputs_dir=auto_inputs_dir)runner_type: RunnerType = ctx.obj["runner"]diff --git a/pipelex/cli/agent_cli/commands/run/method_cmd.py b/pipelex/cli/agent_cli/commands/run/method_cmd.pyindex a96033ba8..12f04f0b5 100644--- a/pipelex/cli/agent_cli/commands/run/method_cmd.py+++ b/pipelex/cli/agent_cli/commands/run/method_cmd.py@@ -16,6 +16,7 @@ from pipelex.cli.agent_cli.commands.run._output_helpers import format_run_markdofrom pipelex.cli.agent_cli.commands.run._run_core import run_pipeline_corefrom pipelex.cli.agent_cli.commands.run._run_core_api import run_pipeline_core_apifrom pipelex.cli.agent_cli.commands.run.stdin_resolver import parse_cli_inputs+from pipelex.cli.commands.run._inputs_file_loader import resolve_inputs_arg_against_dirfrom pipelex.cli.method_resolver import resolve_method_targetfrom pipelex.core.interpreter.helpers import MTHDS_EXTENSIONfrom pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError@@ -111,8 +112,11 @@ def run_method_cmd(if library_dir:all_library_dirs.extend(library_dir)+ # Resolve a relative --inputs file path against the method's directory (same rule as the main CLI)+ effective_inputs = resolve_inputs_arg_against_dir(inputs, base_dir=Path(method_library_dirs[0]))+# Load inputs: --inputs flag takes priority, then stdin fallback- pipeline_inputs: dict[str, Any] | None = parse_cli_inputs(inputs_arg=inputs, stdin_fallback=True)+ pipeline_inputs: dict[str, Any] | None = parse_cli_inputs(inputs_arg=effective_inputs, stdin_fallback=True)runner_type: RunnerType = ctx.obj["runner"]diff --git a/pipelex/cli/agent_cli/commands/run/stdin_resolver.py b/pipelex/cli/agent_cli/commands/run/stdin_resolver.pyindex d702d6c09..780655a33 100644--- a/pipelex/cli/agent_cli/commands/run/stdin_resolver.py+++ b/pipelex/cli/agent_cli/commands/run/stdin_resolver.py@@ -8,9 +8,10 @@ from pathlib import Pathfrom typing import Any, castfrom pipelex.cli.agent_cli.commands.agent_output import agent_error+from pipelex.cli.commands.run._inputs_file_loader import find_default_inputs_file, load_inputs_dict_from_pathfrom pipelex.cli.commands.run._inputs_path_resolver import resolve_inputs_paths-from pipelex.tools.misc.exceptions import JsonTypeError-from pipelex.tools.misc.json_utils import load_json_dict_from_path+from pipelex.cli.commands.run.exceptions import AmbiguousInputsFilesError, InputsDatetimeNotSupportedError+from pipelex.tools.misc.exceptions import JsonTypeError, TomlErrorWORKING_MEMORY_KEY = "working_memory"MAIN_STUFF_KEY = "main_stuff"@@ -117,23 +118,30 @@ def parse_cli_inputs(inputs_arg: str | None,*,stdin_fallback: bool = True,- auto_inputs_path: str | None = None,+ auto_inputs_dir: Path | None = None,) -> dict[str, Any] | None:- """Parse pipeline inputs from CLI --inputs argument, stdin, or auto-detected path.+ """Parse pipeline inputs from CLI --inputs argument, stdin, or an auto-detected directory.Resolution order:1. If ``inputs_arg`` is provided: parse as inline JSON (starts with ``{``) or file path.2. If ``inputs_arg`` is None and ``stdin_fallback`` is True and stdin is not a TTY:read JSON from stdin and resolve envelope format if present.- 3. If ``auto_inputs_path`` is provided: parse it as a file path (lowest priority fallback).+ 3. If ``auto_inputs_dir`` is provided: probe it for a default inputs file+ (``inputs.json`` / ``inputs.toml``) and parse it (lowest-priority fallback).4. Otherwise return None (no inputs).+ The auto-detect probe — including its ``inputs.json``/``inputs.toml`` ambiguity+ rule — runs only here, in step 3, so it can never pre-empt higher-priority+ ``--inputs`` or piped stdin: the ambiguity error is surfaced only when the+ auto-detected file is the source actually being used.+Args:inputs_arg: The ``--inputs`` CLI argument value, or None.stdin_fallback: Whether to attempt reading from stdin when ``inputs_arg`` is None.- auto_inputs_path: Auto-detected inputs file path (e.g. from a directory target).- Only used as a last-resort fallback when both ``inputs_arg`` and stdin are absent.+ auto_inputs_dir: Directory to probe for a default inputs file (e.g. a+ directory target). Only consulted as a last-resort fallback when both+ ``inputs_arg`` and stdin are absent.Returns:Parsed inputs dict, or None if no inputs are available.@@ -146,8 +154,13 @@ def parse_cli_inputs(if stdin_inputs is not None:return stdin_inputs- if auto_inputs_path is not None:- return _parse_inputs_arg(auto_inputs_path)+ if auto_inputs_dir is not None:+ try:+ auto_inputs_file = find_default_inputs_file(auto_inputs_dir)+ except AmbiguousInputsFilesError as ambiguity_exc:+ agent_error(ambiguity_exc.message, error_type="AmbiguousInputsFilesError", cause=ambiguity_exc)+ if auto_inputs_file is not None:+ return _parse_inputs_arg(str(auto_inputs_file))return None@@ -169,14 +182,20 @@ def _parse_inputs_arg(inputs_arg: str) -> dict[str, Any] | None:agent_error(f"Failed to parse inline JSON inputs: {exc}", error_type="JSONDecodeError", cause=exc)else:try:- loaded = load_json_dict_from_path(Path(inputs_arg))+ loaded = load_inputs_dict_from_path(Path(inputs_arg))# Resolve relative url paths against the inputs file's parent directorybase_dir = Path(inputs_arg).parent.resolve()return resolve_inputs_paths(loaded, base_dir=base_dir)except FileNotFoundError as exc:agent_error(f"Input file not found: {inputs_arg}", error_type="FileNotFoundError", cause=exc)+ except json.JSONDecodeError as exc:+ agent_error(f"Input file contains invalid JSON: {inputs_arg}: {exc}", error_type="JSONDecodeError", cause=exc)except JsonTypeError as exc:agent_error(f"Input file must be a valid JSON dictionary: {inputs_arg}", error_type="JsonTypeError", cause=exc)+ except TomlError as exc:+ agent_error(exc.message, error_type="TomlError", cause=exc)+ except InputsDatetimeNotSupportedError as exc:+ agent_error(exc.message, error_type="InputsDatetimeNotSupportedError", cause=exc)return Nonediff --git a/pipelex/cli/commands/build/inputs/_inputs_core.py b/pipelex/cli/commands/build/inputs/_inputs_core.pyindex 3f1e18c72..b76f0acce 100644--- a/pipelex/cli/commands/build/inputs/_inputs_core.py+++ b/pipelex/cli/commands/build/inputs/_inputs_core.py@@ -6,7 +6,7 @@ from pathlib import Pathimport typerfrom posthog import tag-from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAME+from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTS_TOML_FILE_NAMEfrom pipelex.cli.cli_factory import make_pipelex_for_clifrom pipelex.cli.error_handlers import (ErrorContext,@@ -15,7 +15,7 @@ from pipelex.cli.error_handlers import ()from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceErrorfrom pipelex.core.pipes.inputs.exceptions import PipeInputError-from pipelex.core.pipes.inputs.input_renderer import NoInputsRequiredError, render_inputs+from pipelex.core.pipes.inputs.input_renderer import InputsTemplateFormat, NoInputsRequiredError, render_inputs, render_inputs_tomlfrom pipelex.hub import get_library_manager, get_required_pipe, get_telemetry_manager, resolve_library_dirs, set_current_libraryfrom pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityErrorfrom pipelex.pipelex import PACKAGE_VERSION@@ -38,8 +38,9 @@ async def _generate_inputs_core(bundle_path: Path | None = None,output_path: Path | None = None,library_dir: list[str] | None = None,+ template_format: InputsTemplateFormat = InputsTemplateFormat.JSON,) -> None:- """Core logic for generating input JSON for a pipe."""+ """Core logic for generating an inputs template file for a pipe."""# Set up library so pipes can be foundlibrary_manager = get_library_manager()library_id, _ = library_manager.open_library()@@ -85,28 +86,36 @@ async def _generate_inputs_core(typer.secho(f"Error: Could not find pipe '{pipe_code}': {exc}", fg=typer.colors.RED)raise typer.Exit(1) from exc+ inputs_template_str: str+ default_file_name: strtry:- inputs_json_str = render_inputs(the_pipe, indent=2)+ match template_format:+ case InputsTemplateFormat.JSON:+ inputs_template_str = render_inputs(the_pipe, indent=2)+ default_file_name = DEFAULT_INPUTS_FILE_NAME+ case InputsTemplateFormat.TOML:+ inputs_template_str = render_inputs_toml(the_pipe)+ default_file_name = DEFAULT_INPUTS_TOML_FILE_NAMEexcept NoInputsRequiredError as exc:typer.secho(str(exc), fg=typer.colors.YELLOW)raise typer.Exit(0) from excexcept Exception as exc:- # CLI command boundary: any failure generating the input JSON is reported to the user and exits via typer.Exit.- typer.secho(f"Error generating input JSON: {exc}", fg=typer.colors.RED)+ # CLI command boundary: any failure generating the inputs template is reported to the user and exits via typer.Exit.+ typer.secho(f"Error generating inputs template: {exc}", fg=typer.colors.RED)raise typer.Exit(1) from excif output_path:final_output_path = output_pathelif bundle_path:bundle_dir = bundle_path.parent- final_output_path = bundle_dir / DEFAULT_INPUTS_FILE_NAME+ final_output_path = bundle_dir / default_file_nameelse:- final_output_path = Path("results") / DEFAULT_INPUTS_FILE_NAME+ final_output_path = Path("results") / default_file_nametry:ensure_directory_for_file_path(file_path=final_output_path)- save_text_to_path(text=inputs_json_str, path=final_output_path)- typer.secho(f"Generated input JSON file: {final_output_path}", fg=typer.colors.GREEN)+ save_text_to_path(text=inputs_template_str, path=final_output_path)+ typer.secho(f"Generated inputs file: {final_output_path}", fg=typer.colors.GREEN)except Exception as exc:# CLI command boundary: any failure writing the file is reported to the user and exits via typer.Exit.typer.secho(f"Error saving file: {exc}", fg=typer.colors.RED)@@ -119,6 +128,7 @@ def execute_generate_inputs(bundle_path: Path | None,output_path: Path | None,library_dir: list[str] | None = None,+ template_format: InputsTemplateFormat = InputsTemplateFormat.JSON,telemetry_command_label: str = f"{COMMAND} {SUB_COMMAND_INPUTS}",) -> None:"""Synchronous entry point wrapping the async inputs generation with Pipelex setup/teardown."""@@ -132,7 +142,15 @@ def execute_generate_inputs(tag(name=EventProperty.PIPELEX_VERSION, value=PACKAGE_VERSION)tag(name=EventProperty.CLI_COMMAND, value=telemetry_command_label)- asyncio.run(_generate_inputs_core(pipe_code=pipe_code, bundle_path=bundle_path, output_path=output_path, library_dir=library_dir))+ asyncio.run(+ _generate_inputs_core(+ pipe_code=pipe_code,+ bundle_path=bundle_path,+ output_path=output_path,+ library_dir=library_dir,+ template_format=template_format,+ )+ )except PipeOperatorModelChoiceError as exc:handle_model_choice_error(exc, context=ErrorContext.BUILD)diff --git a/pipelex/cli/commands/build/inputs/bundle_cmd.py b/pipelex/cli/commands/build/inputs/bundle_cmd.pyindex 7ebff8dd8..bbf65e4c3 100644--- a/pipelex/cli/commands/build/inputs/bundle_cmd.py+++ b/pipelex/cli/commands/build/inputs/bundle_cmd.py@@ -8,6 +8,7 @@ import typerfrom pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAMEfrom pipelex.cli.commands.build.inputs._inputs_core import execute_generate_inputsfrom pipelex.core.interpreter.helpers import MTHDS_EXTENSION, is_pipelex_file+from pipelex.core.pipes.inputs.input_renderer import InputsTemplateFormatdef build_inputs_bundle_cmd(@@ -29,16 +30,21 @@ def build_inputs_bundle_cmd(] = None,output_path: Annotated[str | None,- typer.Option("--output", "-o", help="Path to save the generated JSON file (defaults to bundle's directory)"),+ typer.Option("--output", "-o", help="Path to save the generated inputs file (defaults to bundle's directory)"),] = None,+ template_format: Annotated[+ InputsTemplateFormat,+ typer.Option("--format", help="Format of the generated inputs template (json or toml)"),+ ] = InputsTemplateFormat.JSON,) -> None:- """Generate example input JSON from a bundle file or pipeline directory.+ """Generate an example inputs template from a bundle file or pipeline directory.Examples:pipelex build inputs bundle my_bundle.mthdspipelex build inputs bundle pipeline_01/pipelex build inputs bundle my_bundle.mthds --pipe my_pipepipelex build inputs bundle pipeline_01/ --output custom_inputs.json+ pipelex build inputs bundle pipeline_01/ --format toml"""target_path = Path(path)bundle_path: Path@@ -95,4 +101,5 @@ def build_inputs_bundle_cmd(bundle_path=bundle_path,output_path=output_path_path,library_dir=library_dir,+ template_format=template_format,)diff --git a/pipelex/cli/commands/build/inputs/method_cmd.py b/pipelex/cli/commands/build/inputs/method_cmd.pyindex 08c48c325..bbbf7ab24 100644--- a/pipelex/cli/commands/build/inputs/method_cmd.py+++ b/pipelex/cli/commands/build/inputs/method_cmd.py@@ -5,9 +5,10 @@ from typing import Annotatedimport typer-from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAME+from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTS_TOML_FILE_NAMEfrom pipelex.cli.commands.build.inputs._inputs_core import execute_generate_inputsfrom pipelex.cli.method_resolver import resolve_method_target+from pipelex.core.pipes.inputs.input_renderer import InputsTemplateFormatdef build_inputs_method_cmd(@@ -29,15 +30,20 @@ def build_inputs_method_cmd(] = None,output_path: Annotated[str | None,- typer.Option("--output", "-o", help="Path to save the generated JSON file"),+ typer.Option("--output", "-o", help="Path to save the generated inputs file"),] = None,+ template_format: Annotated[+ InputsTemplateFormat,+ typer.Option("--format", help="Format of the generated inputs template (json or toml)"),+ ] = InputsTemplateFormat.JSON,) -> None:- """Generate example input JSON for an installed method.+ """Generate an example inputs template for an installed method.Examples:pipelex build inputs method my-methodpipelex build inputs method my-method --pipe custom_pipepipelex build inputs method my-method --output custom_inputs.json+ pipelex build inputs method my-method --format toml"""pipe_code, method_library_dirs, _ = resolve_method_target(method_name=name,@@ -53,11 +59,18 @@ def build_inputs_method_cmd(if output_path:output_path_path = Path(output_path)else:- output_path_path = Path(method_library_dirs[0]) / "results" / DEFAULT_INPUTS_FILE_NAME+ default_file_name: str+ match template_format:+ case InputsTemplateFormat.JSON:+ default_file_name = DEFAULT_INPUTS_FILE_NAME+ case InputsTemplateFormat.TOML:+ default_file_name = DEFAULT_INPUTS_TOML_FILE_NAME+ output_path_path = Path(method_library_dirs[0]) / "results" / default_file_nameexecute_generate_inputs(pipe_code=pipe_code,bundle_path=None,output_path=output_path_path,library_dir=effective_library_dir,+ template_format=template_format,)diff --git a/pipelex/cli/commands/build/inputs/pipe_cmd.py b/pipelex/cli/commands/build/inputs/pipe_cmd.pyindex f2a358478..593fae70e 100644--- a/pipelex/cli/commands/build/inputs/pipe_cmd.py+++ b/pipelex/cli/commands/build/inputs/pipe_cmd.py@@ -6,6 +6,7 @@ from typing import Annotatedimport typerfrom pipelex.cli.commands.build.inputs._inputs_core import execute_generate_inputs+from pipelex.core.pipes.inputs.input_renderer import InputsTemplateFormatdef build_inputs_pipe_cmd(@@ -23,15 +24,20 @@ def build_inputs_pipe_cmd(] = None,output_path: Annotated[str | None,- typer.Option("--output", "-o", help="Path to save the generated JSON file (defaults to 'results/')"),+ typer.Option("--output", "-o", help="Path to save the generated inputs file (defaults to 'results/')"),] = None,+ template_format: Annotated[+ InputsTemplateFormat,+ typer.Option("--format", help="Format of the generated inputs template (json or toml)"),+ ] = InputsTemplateFormat.JSON,) -> None:- """Generate example input JSON for a pipe by code.+ """Generate an example inputs template for a pipe by code.Examples:pipelex build inputs pipe my_domain.my_pipepipelex build inputs pipe my_pipe -L ./my_library/pipelex build inputs pipe my_pipe --output custom_inputs.json+ pipelex build inputs pipe my_pipe --format toml"""output_path_path = Path(output_path) if output_path else None@@ -40,4 +46,5 @@ def build_inputs_pipe_cmd(bundle_path=None,output_path=output_path_path,library_dir=library_dir,+ template_format=template_format,)diff --git a/pipelex/cli/commands/run/_inputs_file_loader.py b/pipelex/cli/commands/run/_inputs_file_loader.pynew file mode 100644index 000000000..cbc8fb5c5--- /dev/null+++ b/pipelex/cli/commands/run/_inputs_file_loader.py@@ -0,0 +1,140 @@+"""Shared pipeline-inputs file loader for the run CLI surfaces.++The inputs format is discriminated by file extension: a ``.toml`` suffix loads+through the TOML parser, every other suffix (``.json``, extensionless, ...)+keeps the JSON behavior. Both the main CLI (``pipelex run``) and the agent CLI+(``pipelex-agent run``) load inputs files through this module so the two+surfaces cannot drift — same deal for the ``inputs.json`` / ``inputs.toml``+auto-detect probe and its ambiguity rule.+"""++from __future__ import annotations++import datetime+from pathlib import Path+from typing import Any, cast++from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTS_TOML_FILE_NAME+from pipelex.cli.commands.run.exceptions import AmbiguousInputsFilesError, InputsDatetimeNotSupportedError+from pipelex.tools.misc.json_utils import load_json_dict_from_path+from pipelex.tools.misc.toml_utils import load_toml_from_path++TOML_SUFFIX = ".toml"+++def load_inputs_dict_from_path(path: Path) -> dict[str, Any]:+ """Load a pipeline-inputs dict from a JSON or TOML file, discriminated by extension.++ Args:+ path: Path to the inputs file. A ``.toml`` suffix selects the TOML+ parser; every other suffix (including none) is parsed as JSON.++ Returns:+ The loaded inputs dictionary.++ Raises:+ FileNotFoundError: If the file does not exist.+ TomlError: If a ``.toml`` file has invalid TOML syntax.+ json.JSONDecodeError: If a JSON file has invalid JSON syntax.+ JsonTypeError: If a JSON file does not hold a dictionary.+ InputsDatetimeNotSupportedError: If a loaded value is a TOML+ datetime/date/time instance (no native concept support yet).+ """+ inputs_dict: dict[str, Any]+ if path.suffix.lower() == TOML_SUFFIX:+ inputs_dict = load_toml_from_path(path)+ else:+ inputs_dict = load_json_dict_from_path(path)+ _assert_no_datetime_values(inputs_dict, source_path=path, key_path="")+ return inputs_dict+++def resolve_inputs_arg_against_dir(inputs_arg: str | None, *, base_dir: Path) -> str | None:+ """Resolve a relative ``--inputs`` file path against ``base_dir``.++ Inline JSON (a ``{`` prefix), URI-scheme strings (containing ``://``, e.g.+ ``https://...``/``s3://...``) and None pass through unchanged. A file path+ has ``~`` expanded first; if it is then absolute it is returned as-is,+ otherwise it is joined onto ``base_dir``. Shared by the ``run method``+ commands of both CLI surfaces so the resolve-against-the-method-dir rule+ cannot drift.++ Args:+ inputs_arg: The raw ``--inputs`` CLI argument value, or None.+ base_dir: The directory relative file paths are resolved against.++ Returns:+ The resolved ``--inputs`` value, same form as the input.+ """+ if not inputs_arg or inputs_arg.startswith("{") or "://" in inputs_arg:+ return inputs_arg+ # expanduser so a quoted/`=`-form `~/inputs.toml` resolves to the home dir, not a literal `~` component+ # (matches the --save-csv handling in _run_core.py). Return the expanded path in both branches, since+ # nothing downstream re-expands it.+ inputs_path = Path(inputs_arg).expanduser()+ if inputs_path.is_absolute():+ return str(inputs_path)+ return str(base_dir / inputs_path)+++def find_default_inputs_file(directory: Path) -> Path | None:+ """Probe a bundle directory for the default inputs file (JSON or TOML).++ Args:+ directory: The bundle/pipeline directory to probe.++ Returns:+ The path to ``inputs.json`` or ``inputs.toml`` when exactly one exists,+ None when neither does.++ Raises:+ AmbiguousInputsFilesError: When both default files exist — the caller+ must pass ``--inputs`` explicitly.+ """+ json_file = directory / DEFAULT_INPUTS_FILE_NAME+ toml_file = directory / DEFAULT_INPUTS_TOML_FILE_NAME+ json_exists = json_file.is_file()+ toml_exists = toml_file.is_file()+ if json_exists and toml_exists:+ msg = (+ f"Directory '{directory}' holds both '{DEFAULT_INPUTS_FILE_NAME}' and '{DEFAULT_INPUTS_TOML_FILE_NAME}', "+ "so inputs auto-detection is ambiguous. Pass --inputs explicitly to choose one."+ )+ raise AmbiguousInputsFilesError(msg)+ if json_exists:+ return json_file+ if toml_exists:+ return toml_file+ return None+++def _assert_no_datetime_values(value: Any, *, source_path: Path, key_path: str) -> None:+ """Recursively reject datetime/date/time instances in a loaded inputs value.++ Only TOML can produce such values (JSON has no datetime type), but the walk+ is format-agnostic and harmless to run on both.++ Args:+ value: The loaded value to inspect (dict, list, scalar, ...).+ source_path: The inputs file the value was loaded from, for the error message.+ key_path: Dotted/indexed path to ``value`` inside the inputs dict, empty at the root.++ Raises:+ InputsDatetimeNotSupportedError: On the first datetime-typed value found.+ """+ if isinstance(value, (datetime.datetime, datetime.date, datetime.time)):+ located = f" at '{key_path}'" if key_path else ""+ msg = (+ f"Inputs file '{source_path}' holds a TOML datetime value{located} ({value!r}). "+ "TOML datetime inputs are not supported yet: quote the value as a string in the meantime."+ )+ raise InputsDatetimeNotSupportedError(msg)+ if isinstance(value, dict):+ value_dict = cast("dict[str, Any]", value)+ for key, sub_value in value_dict.items():+ sub_key_path = f"{key_path}.{key}" if key_path else str(key)+ _assert_no_datetime_values(sub_value, source_path=source_path, key_path=sub_key_path)+ elif isinstance(value, list):+ value_list = cast("list[Any]", value)+ for index_item, sub_value in enumerate(value_list):+ _assert_no_datetime_values(sub_value, source_path=source_path, key_path=f"{key_path}[{index_item}]")diff --git a/pipelex/cli/commands/run/_run_core.py b/pipelex/cli/commands/run/_run_core.pyindex 0862a43da..4c88df03d 100644--- a/pipelex/cli/commands/run/_run_core.py+++ b/pipelex/cli/commands/run/_run_core.py@@ -11,7 +11,9 @@ from posthog import tagfrom pipelex import logfrom pipelex.base_exceptions import PipelexErrorfrom pipelex.cli.cli_factory import make_pipelex_for_cli+from pipelex.cli.commands.run._inputs_file_loader import load_inputs_dict_from_pathfrom pipelex.cli.commands.run._inputs_path_resolver import resolve_inputs_paths+from pipelex.cli.commands.run.exceptions import InputsDatetimeNotSupportedErrorfrom pipelex.cli.error_handlers import (ErrorContext,handle_model_availability_error,@@ -35,9 +37,9 @@ from pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.reporting.cost_report_renderer import render_cost_report_for_outputfrom pipelex.system.runtime import IntegrationModefrom pipelex.system.telemetry.events import EventProperty-from pipelex.tools.misc.exceptions import JsonTypeError+from pipelex.tools.misc.exceptions import JsonTypeError, TomlErrorfrom pipelex.tools.misc.file_utils import get_incremental_directory_path-from pipelex.tools.misc.json_utils import load_json_dict_from_path, save_as_json_to_path+from pipelex.tools.misc.json_utils import save_as_json_to_pathfrom pipelex.tools.misc.package_utils import get_package_versionfrom pipelex.tools.tabular.csv_codec import assert_supported_table_suffix, csv_from_list_content, flat_field_namesfrom pipelex.tools.tabular.exceptions import CsvError@@ -149,7 +151,7 @@ async def _execute_run(raise typer.Exit(1) from json_decode_excelse:try:- pipeline_inputs = load_json_dict_from_path(Path(inputs))+ pipeline_inputs = load_inputs_dict_from_path(Path(inputs))# Resolve relative url paths against the inputs file's parent directorybase_dir = Path(inputs).parent.resolve()pipeline_inputs = resolve_inputs_paths(pipeline_inputs, base_dir=base_dir)@@ -158,10 +160,22 @@ async def _execute_run(print_traceback_if_requested(get_console())typer.secho(f"Failed to load input file '{inputs}': file not found", fg=typer.colors.RED, err=True)raise typer.Exit(1) from file_not_found_exc+ except json.JSONDecodeError as json_decode_exc:+ print_traceback_if_requested(get_console())+ typer.secho(f"Failed to parse input file '{inputs}': invalid JSON: {json_decode_exc}", fg=typer.colors.RED, err=True)+ raise typer.Exit(1) from json_decode_excexcept JsonTypeError as json_type_error_exc:print_traceback_if_requested(get_console())typer.secho(f"Failed to parse input file '{inputs}': must be a valid JSON dictionary", fg=typer.colors.RED, err=True)raise typer.Exit(1) from json_type_error_exc+ except TomlError as toml_error_exc:+ print_traceback_if_requested(get_console())+ typer.secho(f"Failed to parse input file: {toml_error_exc.message}", fg=typer.colors.RED, err=True)+ raise typer.Exit(1) from toml_error_exc+ except InputsDatetimeNotSupportedError as datetime_exc:+ print_traceback_if_requested(get_console())+ typer.secho(f"Failed to load input file: {datetime_exc.message}", fg=typer.colors.RED, err=True)+ raise typer.Exit(1) from datetime_exc# Determine pipe run modepipe_run_mode = PipeRunMode.DRY if dry_run else Nonediff --git a/pipelex/cli/commands/run/bundle_cmd.py b/pipelex/cli/commands/run/bundle_cmd.pyindex 792e4a291..c72346487 100644--- a/pipelex/cli/commands/run/bundle_cmd.py+++ b/pipelex/cli/commands/run/bundle_cmd.py@@ -5,8 +5,10 @@ from typing import Annotatedimport typer-from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAME, DEFAULT_INPUTS_FILE_NAME+from pipelex.builder.conventions import DEFAULT_BUNDLE_FILE_NAME+from pipelex.cli.commands.run._inputs_file_loader import find_default_inputs_filefrom pipelex.cli.commands.run._run_core import COMMAND, execute_run, validate_run_flag_combination+from pipelex.cli.commands.run.exceptions import AmbiguousInputsFilesErrorfrom pipelex.core.interpreter.helpers import MTHDS_EXTENSION, is_pipelex_file@@ -145,11 +147,16 @@ def run_bundle_cmd(raise typer.Exit(1)bundle_path = str(mthds_files[0])- # Auto-detect inputs if --inputs not explicitly provided- inputs_file = target_path / DEFAULT_INPUTS_FILE_NAME- if not inputs and inputs_file.is_file():- inputs = str(inputs_file)- typer.echo(f"Auto-detected inputs: {inputs}")+ # Auto-detect inputs (inputs.json or inputs.toml) if --inputs not explicitly provided+ if not inputs:+ try:+ inputs_file = find_default_inputs_file(target_path)+ except AmbiguousInputsFilesError as ambiguity_exc:+ typer.secho(f"Failed to run: {ambiguity_exc.message}", fg=typer.colors.RED, err=True)+ raise typer.Exit(1) from ambiguity_exc+ if inputs_file is not None:+ inputs = str(inputs_file)+ typer.echo(f"Auto-detected inputs: {inputs}")# Add directory as library dirtarget_dir_str = str(target_path)diff --git a/pipelex/cli/commands/run/exceptions.py b/pipelex/cli/commands/run/exceptions.pynew file mode 100644index 000000000..16d5966fb--- /dev/null+++ b/pipelex/cli/commands/run/exceptions.py@@ -0,0 +1,37 @@+"""Errors raised while loading pipeline-inputs files for the run CLI surfaces."""++from pipelex.base_exceptions import ErrorDomain, PipelexError+from pipelex.cogt.inference.error_classification import UserAction, UserActionKind+++class InputsDatetimeNotSupportedError(PipelexError):+ """Raised when a loaded inputs file carries a TOML datetime/date/time value.++ TOML parses datetimes into Python objects that have no JSON equivalent and no+ native concept yet, so the inputs loader rejects them until DATETIME concept+ support lands.+ """++ error_domain = ErrorDomain.INPUT+ user_action = UserAction(+ kind=UserActionKind.CHANGE_INPUT,+ detail='Quote the datetime as a string in the inputs file (e.g. "2026-07-06"); native TOML datetime inputs are not supported yet',+ )+ # The message describes a fault in the caller's own inputs file — caller-facing copy.+ _authors_caller_facing_message = True+++class AmbiguousInputsFilesError(PipelexError):+ """Raised when a bundle directory holds both default inputs files on auto-detect.++ Auto-detection probes for both ``inputs.json`` and ``inputs.toml``; when both+ exist there is no safe pick, so the caller must choose explicitly.+ """++ error_domain = ErrorDomain.INPUT+ user_action = UserAction(+ kind=UserActionKind.CHANGE_INPUT,+ detail="Pass --inputs explicitly to choose which inputs file to use",+ )+ # The message describes a fault in the caller's own bundle directory — caller-facing copy.+ _authors_caller_facing_message = Truediff --git a/pipelex/cli/commands/run/method_cmd.py b/pipelex/cli/commands/run/method_cmd.pyindex e0ad5e35f..828bd9b9c 100644--- a/pipelex/cli/commands/run/method_cmd.py+++ b/pipelex/cli/commands/run/method_cmd.py@@ -5,6 +5,7 @@ from typing import Annotatedimport typer+from pipelex.cli.commands.run._inputs_file_loader import resolve_inputs_arg_against_dirfrom pipelex.cli.commands.run._run_core import COMMAND, execute_run, validate_run_flag_combinationfrom pipelex.cli.method_resolver import resolve_method_target@@ -130,11 +131,7 @@ def run_method_cmd(effective_output_dir = output_dir or str(method_dir / "results")# Resolve --inputs relative to the method's directory- effective_inputs: str | None = inputs- if inputs and not inputs.startswith("{"):- inputs_path = Path(inputs)- if not inputs_path.is_absolute():- effective_inputs = str(method_dir / inputs_path)+ effective_inputs = resolve_inputs_arg_against_dir(inputs, base_dir=method_dir)# Merge method library dirs with user-supplied -L dirsif library_dir:diff --git a/pipelex/core/pipes/inputs/input_renderer.py b/pipelex/core/pipes/inputs/input_renderer.pyindex 82c73dcec..33416a8a5 100644--- a/pipelex/core/pipes/inputs/input_renderer.py+++ b/pipelex/core/pipes/inputs/input_renderer.py@@ -1,5 +1,37 @@+import json+from typing import Any++import tomlkit+from pipelex.core.pipes.inputs.exceptions import NoInputsRequiredErrorfrom pipelex.core.pipes.pipe_abstract import PipeAbstract+from pipelex.types import StrEnum+++class InputsTemplateFormat(StrEnum):+ """Serialization format for a generated inputs template."""++ JSON = "json"+ TOML = "toml"+++def build_inputs_template(the_pipe: PipeAbstract) -> dict[str, Any]:+ """Build the inputs template dict for a pipe.++ Args:+ the_pipe: The pipe to build the inputs template for++ Returns:+ Dictionary mapping each input variable to its generated example value++ Raises:+ NoInputsRequiredError: If the pipe has no inputs+ """+ if not the_pipe.inputs.root:+ msg = f"No inputs required for pipe '{the_pipe.code}'."+ raise NoInputsRequiredError(msg)++ return the_pipe.inputs.build_inputs_template()def render_inputs(the_pipe: PipeAbstract, *, indent: int = 2) -> str:@@ -15,8 +47,47 @@ def render_inputs(the_pipe: PipeAbstract, *, indent: int = 2) -> str:Raises:NoInputsRequiredError: If the pipe has no inputs"""- if not the_pipe.inputs.root:- msg = f"No inputs required for pipe '{the_pipe.code}'."- raise NoInputsRequiredError(msg)+ return json.dumps(build_inputs_template(the_pipe), indent=indent, ensure_ascii=False)+++def render_inputs_toml(the_pipe: PipeAbstract) -> str:+ """Render a TOML representation of the pipe's inputs.++ Args:+ the_pipe: The pipe to render inputs for++ Returns:+ TOML string with the inputs representation++ Raises:+ NoInputsRequiredError: If the pipe has no inputs+ """+ return serialize_inputs_template_to_toml(build_inputs_template(the_pipe))+++def serialize_inputs_template_to_toml(template: dict[str, Any]) -> str:+ """Serialize an inputs template dict to a TOML string.++ TOML has no null: a None placeholder is substituted with an empty string+ so the key stays visible in the template (omitting it would hide the field+ from the user filling the template in).++ Args:+ template: The inputs template dict (variable name -> example value)++ Returns:+ TOML string of the template+ """+ sanitized = _substitute_none_values(template)+ return tomlkit.dumps(sanitized) # pyright: ignore[reportUnknownMemberType]+- return the_pipe.inputs.render_inputs(indent=indent)+def _substitute_none_values(value: Any) -> Any:+ """Recursively replace None with an empty string in a template value."""+ if value is None:+ return ""+ if isinstance(value, dict):+ return {key: _substitute_none_values(sub_value) for key, sub_value in value.items()} # pyright: ignore[reportUnknownArgumentType, reportUnknownVariableType]+ if isinstance(value, list):+ return [_substitute_none_values(sub_value) for sub_value in value] # pyright: ignore[reportUnknownArgumentType, reportUnknownVariableType]+ return valuediff --git a/pipelex/core/pipes/inputs/input_stuff_specs.py b/pipelex/core/pipes/inputs/input_stuff_specs.pyindex cf01b8bbf..ef08d77af 100644--- a/pipelex/core/pipes/inputs/input_stuff_specs.py+++ b/pipelex/core/pipes/inputs/input_stuff_specs.py@@ -150,6 +150,17 @@ class InputStuffSpecs(RootModel[PipeInputsRoot]):lines = [f"{prefix}- {var_name}: {stuff_spec.to_bundle_representation()}" for var_name, stuff_spec in self.root.items()]return "\n" + "\n".join(lines)+ def build_inputs_template(self) -> dict[str, Any]:+ """Build the inputs template dict: variable name -> example stuff representation.++ Returns:+ Dictionary mapping each input variable to its generated example value+ """+ template: dict[str, Any] = {}+ for var_name, stuff_spec in self.root.items():+ template[var_name] = stuff_spec.render_stuff_spec(ConceptRepresentationFormat.JSON)+ return template+def render_inputs(self, indent: int = 2) -> str:"""Render a JSON representation for all stuff specs as a formatted string.@@ -159,8 +170,4 @@ class InputStuffSpecs(RootModel[PipeInputsRoot]):Returns:Formatted JSON string with all inputs"""- json_inputs: dict[str, Any] = {}- for var_name, stuff_spec in self.root.items():- json_inputs[var_name] = stuff_spec.render_stuff_spec(ConceptRepresentationFormat.JSON)-- return json.dumps(json_inputs, indent=indent, ensure_ascii=False)+ return json.dumps(self.build_inputs_template(), indent=indent, ensure_ascii=False)diff --git a/tests/e2e/pipelex/cli/test_toml_inputs_build.py b/tests/e2e/pipelex/cli/test_toml_inputs_build.pynew file mode 100644index 000000000..4006bf5d1--- /dev/null+++ b/tests/e2e/pipelex/cli/test_toml_inputs_build.py@@ -0,0 +1,94 @@+"""E2E test for TOML inputs-template generation via the ``pipelex build inputs`` CLI.++One ``gha_disabled`` subprocess check exercises the real binary end to end: ``build+inputs bundle --format toml`` must write an ``inputs.toml`` next to the bundle (the+TOML default filename), and that generated template must feed a ``run --dry-run``+straight back — the full generate→load round trip across both CLI surfaces. The+staged bundle is the same ``csv_demo`` fixture used by the CSV e2e tests; its+``inputs.json`` is removed from the staged copy so the follow-up run cannot fall back+to the JSON twin.++The subprocess calls inherit the ambient environment (they need a working+``.pipelex`` config to boot) and run with ``cwd`` set to a tmp dir so on-disk side+effects stay out of the source tree.+"""++from __future__ import annotations++import os+import shutil+import subprocess # noqa: S404 — invokes the real pipelex binary for E2E coverage+from pathlib import Path+from typing import Any, cast++import pytest+import tomli++REPO_ROOT = Path(__file__).resolve().parents[4]+PIPELEX_BIN = REPO_ROOT / ".venv" / "bin" / "pipelex"+BUNDLE_SRC = REPO_ROOT / "tests" / "integration" / "pipelex" / "csv" / "csv_demo"+++class TestTomlInputsBuild:+ @pytest.mark.gha_disabled+ def test_build_inputs_toml_then_dry_run(self, tmp_path: Path) -> None:+ staged = tmp_path / "csv_demo"+ shutil.copytree(BUNDLE_SRC, staged)+ (staged / "inputs.json").unlink()++ build_result = subprocess.run( # noqa: S603+ [+ str(PIPELEX_BIN),+ "build",+ "inputs",+ "bundle",+ str(staged / "csv_demo.mthds"),+ "--pipe",+ "summarize_people",+ "--format",+ "toml",+ ],+ cwd=str(tmp_path),+ env=os.environ.copy(),+ capture_output=True,+ text=True,+ check=False,+ timeout=180,+ )+ assert build_result.returncode == 0, f"TOML template generation must succeed.\nstdout={build_result.stdout!r}\nstderr={build_result.stderr!r}"++ inputs_toml = staged / "inputs.toml"+ assert inputs_toml.is_file(), "The TOML default filename must be inputs.toml next to the bundle"+ template = tomli.loads(inputs_toml.read_text(encoding="utf-8"))+ assert template["people"]["concept"] == "csv_demo.Person"+ person_items = template["people"]["content"]+ assert isinstance(person_items, list), "Person[] multiplicity must wrap content in a list"+ first_person = cast("dict[str, Any]", person_items[0])+ assert {"name", "job", "country", "birth_year"} <= set(first_person.keys())++ run_result = subprocess.run( # noqa: S603+ [+ str(PIPELEX_BIN),+ "run",+ "pipe",+ "summarize_people",+ "-L",+ str(staged),+ "--inputs",+ str(inputs_toml),+ "--dry-run",+ "--no-save-working-memory",+ "--no-save-main-stuff",+ "--no-graph",+ ],+ cwd=str(tmp_path),+ env=os.environ.copy(),+ capture_output=True,+ text=True,+ check=False,+ timeout=180,+ )+ assert run_result.returncode == 0, (+ f"Dry run fed the generated inputs.toml must succeed.\nstdout={run_result.stdout!r}\nstderr={run_result.stderr!r}"+ )+ assert "inputs.toml" in run_result.stdoutdiff --git a/tests/e2e/pipelex/cli/test_toml_inputs_run.py b/tests/e2e/pipelex/cli/test_toml_inputs_run.pynew file mode 100644index 000000000..76369d052--- /dev/null+++ b/tests/e2e/pipelex/cli/test_toml_inputs_run.py@@ -0,0 +1,67 @@+"""E2E test for TOML pipeline inputs via the ``pipelex run`` CLI.++One ``gha_disabled`` subprocess check exercises the real binary: a dry run fed an+``inputs.toml`` (instead of ``inputs.json``) must load the TOML, resolve the relative+``url`` against the inputs file's directory, and complete. The staged bundle is the+same ``csv_demo`` fixture used by the CSV e2e tests; the test writes the TOML+equivalent of its ``inputs.json`` into the staged copy.++The subprocess test inherits the ambient environment (it needs a working ``.pipelex``+config to boot) and runs with ``cwd`` set to a tmp dir so on-disk side effects stay+out of the source tree.+"""++from __future__ import annotations++import os+import shutil+import subprocess # noqa: S404 — invokes the real pipelex binary for E2E coverage+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[4]+PIPELEX_BIN = REPO_ROOT / ".venv" / "bin" / "pipelex"+BUNDLE_SRC = REPO_ROOT / "tests" / "integration" / "pipelex" / "csv" / "csv_demo"++INPUTS_TOML = """[people]+concept = "csv_demo.Person"++[people.content]+url = "people.csv"+"""+++class TestTomlInputsRun:+ @pytest.mark.gha_disabled+ def test_toml_inputs_dry_run(self, tmp_path: Path) -> None:+ staged = tmp_path / "csv_demo"+ shutil.copytree(BUNDLE_SRC, staged)+ inputs_toml = staged / "inputs.toml"+ inputs_toml.write_text(INPUTS_TOML, encoding="utf-8")++ result = subprocess.run( # noqa: S603+ [+ str(PIPELEX_BIN),+ "run",+ "pipe",+ "summarize_people",+ "-L",+ str(staged),+ "--inputs",+ str(inputs_toml),+ "--dry-run",+ "--no-save-working-memory",+ "--no-save-main-stuff",+ "--no-graph",+ ],+ cwd=str(tmp_path),+ env=os.environ.copy(),+ capture_output=True,+ text=True,+ check=False,+ timeout=180,+ )+ assert result.returncode == 0, f"TOML-inputs dry run must succeed.\nstdout={result.stdout!r}\nstderr={result.stderr!r}"+ assert "Loaded inputs from" in result.stdout+ assert "inputs.toml" in result.stdoutdiff --git a/tests/unit/pipelex/cli/agent_cli/test_inputs_format_unaffected.py b/tests/unit/pipelex/cli/agent_cli/test_inputs_format_unaffected.pyindex 5c7a780f2..e8092a242 100644--- a/tests/unit/pipelex/cli/agent_cli/test_inputs_format_unaffected.py+++ b/tests/unit/pipelex/cli/agent_cli/test_inputs_format_unaffected.py@@ -1,4 +1,4 @@-"""Regression test: the `inputs` command stays JSON-only (no --format / --error-format options)."""+"""Regression test: the `inputs` commands' --format is the template serialization (json|toml), not the markdown|json pair."""from __future__ import annotations@@ -7,14 +7,23 @@ import inspectfrom pipelex.cli.agent_cli.commands.inputs.bundle_cmd import inputs_bundle_cmdfrom pipelex.cli.agent_cli.commands.inputs.method_cmd import inputs_method_cmdfrom pipelex.cli.agent_cli.commands.inputs.pipe_cmd import inputs_pipe_cmd+from pipelex.core.pipes.inputs.input_renderer import InputsTemplateFormatclass TestInputsFormatUnaffected:- """The `inputs` command always emits JSON — it must not gain --format or --error-format options."""+ """The `inputs` commands never gain the markdown|json presentation pair.- def test_inputs_commands_have_no_format_params(self) -> None:- """No inputs subcommand declares an output_format or error_format parameter."""+ Their `--format` is an InputsTemplateFormat (json|toml) selecting the template+ serialization — a deliberate deviation documented in the agent CLI CLAUDE.md.+ Errors stay on the ContextVar's JSON default: no --error-format.+ """++ def test_inputs_commands_have_template_format_not_presentation_format(self) -> None:+ """Each inputs subcommand declares template_format (InputsTemplateFormat) and no output_format/error_format."""for command in (inputs_pipe_cmd, inputs_bundle_cmd, inputs_method_cmd):parameters = inspect.signature(command).parametersassert "output_format" not in parameters, f"{command.__name__} unexpectedly gained an output_format parameter"assert "error_format" not in parameters, f"{command.__name__} unexpectedly gained an error_format parameter"+ template_format_param = parameters.get("template_format")+ assert template_format_param is not None, f"{command.__name__} lost its template_format parameter"+ assert template_format_param.default == InputsTemplateFormat.JSON, f"{command.__name__} must default to the JSON envelope"diff --git a/tests/unit/pipelex/cli/agent_cli/test_inputs_template_format_toml.py b/tests/unit/pipelex/cli/agent_cli/test_inputs_template_format_toml.pynew file mode 100644index 000000000..63eaf11e7--- /dev/null+++ b/tests/unit/pipelex/cli/agent_cli/test_inputs_template_format_toml.py@@ -0,0 +1,78 @@+"""Unit tests for agent CLI `inputs pipe --format toml` (raw TOML template on stdout)."""++from __future__ import annotations++import json+from typing import TYPE_CHECKING, Any++import tomli++from pipelex.cli.agent_cli.commands.inputs.pipe_cmd import inputs_pipe_cmd+from pipelex.core.pipes.inputs.exceptions import NoInputsRequiredError+from pipelex.core.pipes.inputs.input_renderer import InputsTemplateFormat++if TYPE_CHECKING:+ import pytest+ from pytest_mock import MockerFixture++PIPE_CMD_MODULE = "pipelex.cli.agent_cli.commands.inputs.pipe_cmd"++INPUTS_TEMPLATE: dict[str, Any] = {+ "topic": {+ "concept": "demo.Topic",+ "content": {"text": "line one\nline two"},+ },+}+++class TestAgentInputsTemplateFormatToml:+ def _patch_inputs(self, mocker: MockerFixture, *, result: dict[str, Any] | None = None, error: Exception | None = None) -> None:+ """Patch the pipe command's dependencies; inputs_core returns result or raises error."""+ mocker.patch(f"{PIPE_CMD_MODULE}.make_pipelex_for_agent_cli")+ mocker.patch(f"{PIPE_CMD_MODULE}.Pipelex.teardown_if_needed")+ mocker.patch(f"{PIPE_CMD_MODULE}.resolve_pipe_from_exports", return_value=[])+ if error is not None:+ mocker.patch(f"{PIPE_CMD_MODULE}.inputs_core", new=mocker.AsyncMock(side_effect=error))+ else:+ mocker.patch(f"{PIPE_CMD_MODULE}.inputs_core", new=mocker.AsyncMock(return_value=result))++ def test_toml_format_prints_raw_toml(self, mocker: MockerFixture, capsys: pytest.CaptureFixture[str]) -> None:+ """--format toml prints the raw TOML template, not the JSON envelope."""+ self._patch_inputs(mocker, result={"success": True, "pipe_code": "demo.my_pipe", "inputs": INPUTS_TEMPLATE})++ inputs_pipe_cmd("my_pipe", template_format=InputsTemplateFormat.TOML)++ captured = capsys.readouterr()+ assert not captured.out.lstrip().startswith("{")+ assert tomli.loads(captured.out) == INPUTS_TEMPLATE++ def test_json_default_keeps_envelope(self, mocker: MockerFixture, capsys: pytest.CaptureFixture[str]) -> None:+ """The default format keeps the structured JSON success envelope."""+ self._patch_inputs(mocker, result={"success": True, "pipe_code": "demo.my_pipe", "inputs": INPUTS_TEMPLATE})++ inputs_pipe_cmd("my_pipe")++ envelope = json.loads(capsys.readouterr().out)+ assert envelope["success"] is True+ assert envelope["inputs"] == INPUTS_TEMPLATE++ def test_no_inputs_in_toml_mode_prints_comment(self, mocker: MockerFixture, capsys: pytest.CaptureFixture[str]) -> None:+ """A pipe without inputs yields a TOML comment line — valid TOML that loads as an empty dict."""+ self._patch_inputs(mocker, error=NoInputsRequiredError("No inputs required for pipe 'demo.my_pipe'."))++ inputs_pipe_cmd("my_pipe", template_format=InputsTemplateFormat.TOML)++ captured = capsys.readouterr()+ assert captured.out.startswith("# No inputs required")+ assert tomli.loads(captured.out) == {}++ def test_no_inputs_in_json_mode_keeps_envelope(self, mocker: MockerFixture, capsys: pytest.CaptureFixture[str]) -> None:+ """A pipe without inputs keeps the structured envelope in JSON mode."""+ self._patch_inputs(mocker, error=NoInputsRequiredError("No inputs required for pipe 'demo.my_pipe'."))++ inputs_pipe_cmd("my_pipe")++ envelope = json.loads(capsys.readouterr().out)+ assert envelope["success"] is True+ assert envelope["inputs"] == {}+ assert "No inputs required" in envelope["message"]diff --git a/tests/unit/pipelex/cli/agent_cli/test_run_bundle_auto_inputs.py b/tests/unit/pipelex/cli/agent_cli/test_run_bundle_auto_inputs.pynew file mode 100644index 000000000..6563dfab6--- /dev/null+++ b/tests/unit/pipelex/cli/agent_cli/test_run_bundle_auto_inputs.py@@ -0,0 +1,111 @@+"""Unit tests for agent CLI `run bundle <dir>` inputs auto-detection (inputs.json / inputs.toml)."""++from __future__ import annotations++import io+import json+from typing import TYPE_CHECKING, Any++import pytest+import typer+from mthds.runners.types import RunnerType++from pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, set_agent_cli_error_format+from pipelex.cli.agent_cli.commands.run.bundle_cmd import run_bundle_cmd++if TYPE_CHECKING:+ from pathlib import Path++ from pytest_mock import MockerFixture++RUN_BUNDLE_MODULE = "pipelex.cli.agent_cli.commands.run.bundle_cmd"+++class TestAgentRunBundleAutoInputs:+ @pytest.fixture+ def bundle_dir(self, tmp_path: Path) -> Path:+ """A pipeline directory holding a default bundle file (never interpreted: --pipe is passed)."""+ (tmp_path / "bundle.mthds").write_text("# bundle\n", encoding="utf-8")+ return tmp_path++ @pytest.fixture+ def tty_stdin(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Make stdin look like a TTY so parse_cli_inputs skips the stdin fallback."""+ mock_stdin = io.StringIO("")+ mock_stdin.isatty = lambda: True # type: ignore[assignment]+ monkeypatch.setattr("sys.stdin", mock_stdin)++ def _patch_run(self, mocker: MockerFixture, result: dict[str, Any]) -> Any:+ """Patch the run bundle command's runner dependencies; return the run_pipeline_core mock."""+ mocker.patch(f"{RUN_BUNDLE_MODULE}.make_pipelex_for_agent_cli")+ mocker.patch(f"{RUN_BUNDLE_MODULE}.Pipelex.teardown_if_needed")+ return mocker.patch(f"{RUN_BUNDLE_MODULE}.run_pipeline_core", new=mocker.AsyncMock(return_value=result))++ def _make_ctx(self, mocker: MockerFixture) -> Any:+ ctx = mocker.MagicMock()+ ctx.obj = {"runner": RunnerType.PIPELEX}+ return ctx++ @pytest.mark.usefixtures("tty_stdin")+ def test_auto_detects_inputs_toml(self, mocker: MockerFixture, bundle_dir: Path, capsys: pytest.CaptureFixture[str]) -> None:+ """With only inputs.toml in the directory, it is auto-detected and loaded through the TOML parser."""+ run_core_mock = self._patch_run(mocker, {"answer": "42"})+ (bundle_dir / "inputs.toml").write_text('topic = "cats"\n', encoding="utf-8")++ run_bundle_cmd(ctx=self._make_ctx(mocker), path=str(bundle_dir), pipe="my_pipe", output_format=CliOutputFormat.JSON)++ capsys.readouterr()+ assert run_core_mock.call_args.kwargs["inputs"] == {"topic": "cats"}++ @pytest.mark.usefixtures("tty_stdin")+ def test_both_inputs_files_error_envelope(self, mocker: MockerFixture, bundle_dir: Path, capsys: pytest.CaptureFixture[str]) -> None:+ """With both default inputs files present, the command emits the ambiguity envelope and exits."""+ set_agent_cli_error_format(CliOutputFormat.JSON)+ run_core_mock = self._patch_run(mocker, {"answer": "42"})+ (bundle_dir / "inputs.json").write_text('{"topic": "cats"}', encoding="utf-8")+ (bundle_dir / "inputs.toml").write_text('topic = "cats"\n', encoding="utf-8")++ with pytest.raises(typer.Exit) as exc_info:+ run_bundle_cmd(ctx=self._make_ctx(mocker), path=str(bundle_dir), pipe="my_pipe", output_format=CliOutputFormat.JSON)++ assert exc_info.value.exit_code == 1+ envelope = json.loads(capsys.readouterr().err)+ assert envelope["error_type"] == "AmbiguousInputsFilesError"+ assert envelope["error_domain"] == "input"+ assert "--inputs" in envelope["hint"]+ run_core_mock.assert_not_called()++ def test_piped_stdin_preempts_ambiguous_auto_detect(+ self, mocker: MockerFixture, bundle_dir: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+ ) -> None:+ """Piped stdin supplies inputs and outranks auto-detect, so an ambiguous dir does NOT error."""+ set_agent_cli_error_format(CliOutputFormat.JSON)+ run_core_mock = self._patch_run(mocker, {"answer": "42"})+ (bundle_dir / "inputs.json").write_text('{"topic": "fromjson"}', encoding="utf-8")+ (bundle_dir / "inputs.toml").write_text('topic = "fromtoml"\n', encoding="utf-8")+ piped_stdin = io.StringIO('{"topic": "fromstdin"}')+ piped_stdin.isatty = lambda: False # type: ignore[assignment]+ monkeypatch.setattr("sys.stdin", piped_stdin)++ run_bundle_cmd(ctx=self._make_ctx(mocker), path=str(bundle_dir), pipe="my_pipe", output_format=CliOutputFormat.JSON)++ capsys.readouterr()+ assert run_core_mock.call_args.kwargs["inputs"] == {"topic": "fromstdin"}++ @pytest.mark.usefixtures("tty_stdin")+ def test_explicit_inputs_bypasses_ambiguity(self, mocker: MockerFixture, bundle_dir: Path, capsys: pytest.CaptureFixture[str]) -> None:+ """An explicit --inputs skips the probe entirely, even with both default files present."""+ run_core_mock = self._patch_run(mocker, {"answer": "42"})+ (bundle_dir / "inputs.json").write_text('{"topic": "json"}', encoding="utf-8")+ (bundle_dir / "inputs.toml").write_text('topic = "toml"\n', encoding="utf-8")++ run_bundle_cmd(+ ctx=self._make_ctx(mocker),+ path=str(bundle_dir),+ pipe="my_pipe",+ inputs=str(bundle_dir / "inputs.toml"),+ output_format=CliOutputFormat.JSON,+ )++ capsys.readouterr()+ assert run_core_mock.call_args.kwargs["inputs"] == {"topic": "toml"}diff --git a/tests/unit/pipelex/cli/agent_cli/test_run_method_inputs_resolution.py b/tests/unit/pipelex/cli/agent_cli/test_run_method_inputs_resolution.pynew file mode 100644index 000000000..d70867bc3--- /dev/null+++ b/tests/unit/pipelex/cli/agent_cli/test_run_method_inputs_resolution.py@@ -0,0 +1,67 @@+"""Unit tests for agent CLI `run method` resolving a relative --inputs path against the method dir."""++from __future__ import annotations++import io+from typing import TYPE_CHECKING, Any++import pytest+from mthds.runners.types import RunnerType++from pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat+from pipelex.cli.agent_cli.commands.run.method_cmd import run_method_cmd++if TYPE_CHECKING:+ from pathlib import Path++ from pytest_mock import MockerFixture++RUN_METHOD_MODULE = "pipelex.cli.agent_cli.commands.run.method_cmd"+++class TestAgentRunMethodInputsResolution:+ @pytest.fixture+ def tty_stdin(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Make stdin look like a TTY so parse_cli_inputs skips the stdin fallback."""+ mock_stdin = io.StringIO("")+ mock_stdin.isatty = lambda: True # type: ignore[assignment]+ monkeypatch.setattr("sys.stdin", mock_stdin)++ def _patch_method_run(self, mocker: MockerFixture, *, method_dir: Path, result: dict[str, Any]) -> Any:+ """Patch method resolution + runner dependencies; return the run_pipeline_core mock."""+ method_mock = mocker.MagicMock()+ method_mock.mthds_files = []+ method_mock.path = method_dir+ mocker.patch(+ f"{RUN_METHOD_MODULE}.resolve_method_target",+ return_value=("my_pipe", [str(method_dir)], method_mock),+ )+ mocker.patch(f"{RUN_METHOD_MODULE}.make_pipelex_for_agent_cli")+ mocker.patch(f"{RUN_METHOD_MODULE}.Pipelex.teardown_if_needed")+ return mocker.patch(f"{RUN_METHOD_MODULE}.run_pipeline_core", new=mocker.AsyncMock(return_value=result))++ def _make_ctx(self, mocker: MockerFixture) -> Any:+ ctx = mocker.MagicMock()+ ctx.obj = {"runner": RunnerType.PIPELEX}+ return ctx++ @pytest.mark.usefixtures("tty_stdin")+ def test_relative_inputs_resolved_against_method_dir(self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ """A relative --inputs path loads from the method's directory, not the CWD (same rule as the main CLI)."""+ (tmp_path / "inputs.toml").write_text('topic = "cats"\n', encoding="utf-8")+ run_core_mock = self._patch_method_run(mocker, method_dir=tmp_path, result={"answer": "42"})++ run_method_cmd(ctx=self._make_ctx(mocker), name="my-method", inputs="inputs.toml", output_format=CliOutputFormat.JSON)++ capsys.readouterr()+ assert run_core_mock.call_args.kwargs["inputs"] == {"topic": "cats"}++ @pytest.mark.usefixtures("tty_stdin")+ def test_inline_json_untouched_by_resolution(self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ """Inline JSON --inputs is parsed as-is, never treated as a path."""+ run_core_mock = self._patch_method_run(mocker, method_dir=tmp_path, result={"answer": "42"})++ run_method_cmd(ctx=self._make_ctx(mocker), name="my-method", inputs='{"topic": "inline"}', output_format=CliOutputFormat.JSON)++ capsys.readouterr()+ assert run_core_mock.call_args.kwargs["inputs"] == {"topic": "inline"}diff --git a/tests/unit/pipelex/cli/commands/build/test_inputs_core_toml.py b/tests/unit/pipelex/cli/commands/build/test_inputs_core_toml.pynew file mode 100644index 000000000..150cb0eff--- /dev/null+++ b/tests/unit/pipelex/cli/commands/build/test_inputs_core_toml.py@@ -0,0 +1,89 @@+"""Unit tests for the `pipelex build inputs --format toml` path of _generate_inputs_core."""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import TYPE_CHECKING, Any++import pytest++from pipelex.cli.commands.build.inputs._inputs_core import _generate_inputs_core # noqa: PLC2701 # pyright: ignore[reportPrivateUsage]+from pipelex.core.pipes.inputs.input_renderer import InputsTemplateFormat++if TYPE_CHECKING:+ from pathlib import Path++ from pytest_mock import MockerFixture++MODULE = "pipelex.cli.commands.build.inputs._inputs_core"++TOML_TEMPLATE = '[topic]\nconcept = "demo.Topic"\n'+++class TestGenerateInputsCoreToml:+ @pytest.fixture+ def core_mocks(self, mocker: MockerFixture) -> dict[str, Any]:+ """Stub the library plumbing, bundle validation, pipe lookup and both renderers."""+ library_manager = mocker.MagicMock()+ library_manager.open_library.return_value = ("lib_id", mocker.MagicMock())+ mocker.patch(f"{MODULE}.get_library_manager", return_value=library_manager)+ mocker.patch(f"{MODULE}.set_current_library")+ mocker.patch(f"{MODULE}.resolve_library_dirs", return_value=([], "defaults"))+ validate_result = SimpleNamespace(blueprints=[SimpleNamespace(main_pipe="bundle_main")])+ return {+ "validate_bundle": mocker.patch(f"{MODULE}.validate_bundle", new=mocker.AsyncMock(return_value=validate_result)),+ "get_required_pipe": mocker.patch(f"{MODULE}.get_required_pipe", return_value=SimpleNamespace(code="bundle_main")),+ "render_inputs": mocker.patch(f"{MODULE}.render_inputs", return_value='{\n "topic": "your topic"\n}'),+ "render_inputs_toml": mocker.patch(f"{MODULE}.render_inputs_toml", return_value=TOML_TEMPLATE),+ }++ def test_toml_format_writes_inputs_toml_next_to_bundle(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:+ """With --format toml and no --output, the default filename becomes inputs.toml next to the bundle."""+ bundle_path = tmp_path / "demo.mthds"++ asyncio.run(_generate_inputs_core(pipe_code=None, bundle_path=bundle_path, template_format=InputsTemplateFormat.TOML))++ inputs_file = tmp_path / "inputs.toml"+ assert inputs_file.read_text(encoding="utf-8") == TOML_TEMPLATE+ core_mocks["render_inputs_toml"].assert_called_once()+ core_mocks["render_inputs"].assert_not_called()+ assert not (tmp_path / "inputs.json").exists()++ def test_toml_format_defaults_to_results_dir_without_bundle(+ self, core_mocks: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Without a bundle, --format toml lands in results/inputs.toml."""+ monkeypatch.chdir(tmp_path)++ asyncio.run(_generate_inputs_core(pipe_code="my_pipe", bundle_path=None, template_format=InputsTemplateFormat.TOML))++ inputs_file = tmp_path / "results" / "inputs.toml"+ assert inputs_file.read_text(encoding="utf-8") == TOML_TEMPLATE+ core_mocks["render_inputs"].assert_not_called()++ def test_explicit_output_path_wins_over_toml_default_name(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:+ """An explicit --output is used verbatim in TOML mode too."""+ target_path = tmp_path / "custom" / "my_inputs.toml"++ asyncio.run(+ _generate_inputs_core(+ pipe_code="my_pipe",+ bundle_path=tmp_path / "demo.mthds",+ output_path=target_path,+ template_format=InputsTemplateFormat.TOML,+ )+ )++ assert target_path.read_text(encoding="utf-8") == TOML_TEMPLATE+ core_mocks["render_inputs_toml"].assert_called_once()++ def test_json_default_still_writes_inputs_json(self, core_mocks: dict[str, Any], tmp_path: Path) -> None:+ """Leaving template_format at its default keeps the historical inputs.json behavior."""+ bundle_path = tmp_path / "demo.mthds"++ asyncio.run(_generate_inputs_core(pipe_code=None, bundle_path=bundle_path))++ inputs_file = tmp_path / "inputs.json"+ assert inputs_file.read_text(encoding="utf-8") == '{\n "topic": "your topic"\n}'+ core_mocks["render_inputs_toml"].assert_not_called()diff --git a/tests/unit/pipelex/cli/commands/run/test_bundle_cmd_auto_inputs.py b/tests/unit/pipelex/cli/commands/run/test_bundle_cmd_auto_inputs.pynew file mode 100644index 000000000..45d1b6f1f--- /dev/null+++ b/tests/unit/pipelex/cli/commands/run/test_bundle_cmd_auto_inputs.py@@ -0,0 +1,67 @@+"""Unit tests for `pipelex run bundle <dir>` inputs auto-detection (inputs.json / inputs.toml)."""++from __future__ import annotations++from typing import TYPE_CHECKING++import pytest+import typer++from pipelex.cli.commands.run.bundle_cmd import run_bundle_cmd++if TYPE_CHECKING:+ from pathlib import Path++ from pytest_mock import MockerFixture++BUNDLE_CMD_MODULE = "pipelex.cli.commands.run.bundle_cmd"+++class TestBundleCmdAutoInputs:+ @pytest.fixture+ def bundle_dir(self, tmp_path: Path) -> Path:+ """A pipeline directory holding a default bundle file (contents never parsed: execute_run is mocked)."""+ (tmp_path / "bundle.mthds").write_text("# bundle\n", encoding="utf-8")+ return tmp_path++ def test_auto_detects_inputs_toml(self, mocker: MockerFixture, bundle_dir: Path) -> None:+ """With only inputs.toml in the directory, it is auto-detected and forwarded."""+ mock_execute = mocker.patch(f"{BUNDLE_CMD_MODULE}.execute_run")+ (bundle_dir / "inputs.toml").write_text('topic = "cats"\n', encoding="utf-8")++ run_bundle_cmd(path=str(bundle_dir))++ assert mock_execute.call_args.kwargs["inputs"] == str(bundle_dir / "inputs.toml")++ def test_auto_detects_inputs_json(self, mocker: MockerFixture, bundle_dir: Path) -> None:+ """With only inputs.json in the directory, today's auto-detection is unchanged."""+ mock_execute = mocker.patch(f"{BUNDLE_CMD_MODULE}.execute_run")+ (bundle_dir / "inputs.json").write_text('{"topic": "cats"}', encoding="utf-8")++ run_bundle_cmd(path=str(bundle_dir))++ assert mock_execute.call_args.kwargs["inputs"] == str(bundle_dir / "inputs.json")++ def test_both_inputs_files_error(self, mocker: MockerFixture, bundle_dir: Path, capsys: pytest.CaptureFixture[str]) -> None:+ """With both inputs.json and inputs.toml present, the command exits telling the user to pass --inputs."""+ mock_execute = mocker.patch(f"{BUNDLE_CMD_MODULE}.execute_run")+ (bundle_dir / "inputs.json").write_text('{"topic": "cats"}', encoding="utf-8")+ (bundle_dir / "inputs.toml").write_text('topic = "cats"\n', encoding="utf-8")++ with pytest.raises(typer.Exit) as exc_info:+ run_bundle_cmd(path=str(bundle_dir))++ assert exc_info.value.exit_code == 1+ assert "--inputs" in capsys.readouterr().err+ mock_execute.assert_not_called()++ def test_explicit_inputs_bypasses_ambiguity(self, mocker: MockerFixture, bundle_dir: Path) -> None:+ """An explicit --inputs skips the probe entirely, even with both default files present."""+ mock_execute = mocker.patch(f"{BUNDLE_CMD_MODULE}.execute_run")+ (bundle_dir / "inputs.json").write_text('{"topic": "cats"}', encoding="utf-8")+ (bundle_dir / "inputs.toml").write_text('topic = "cats"\n', encoding="utf-8")+ explicit = bundle_dir / "inputs.toml"++ run_bundle_cmd(path=str(bundle_dir), inputs=str(explicit))++ assert mock_execute.call_args.kwargs["inputs"] == str(explicit)diff --git a/tests/unit/pipelex/cli/commands/run/test_inputs_arg_resolution.py b/tests/unit/pipelex/cli/commands/run/test_inputs_arg_resolution.pynew file mode 100644index 000000000..ada5a8915--- /dev/null+++ b/tests/unit/pipelex/cli/commands/run/test_inputs_arg_resolution.py@@ -0,0 +1,39 @@+"""Unit tests for the shared --inputs-argument resolution against a base directory."""++from __future__ import annotations++from pathlib import Path++from pipelex.cli.commands.run._inputs_file_loader import resolve_inputs_arg_against_dir # noqa: PLC2701 # pyright: ignore[reportPrivateUsage]+++class TestResolveInputsArgAgainstDir:+ def test_relative_path_is_joined(self, tmp_path: Path) -> None:+ """A relative file path is resolved against the base directory."""+ assert resolve_inputs_arg_against_dir("inputs.toml", base_dir=tmp_path) == str(tmp_path / "inputs.toml")+ assert resolve_inputs_arg_against_dir("sub/inputs.json", base_dir=tmp_path) == str(tmp_path / "sub" / "inputs.json")++ def test_absolute_path_passes_through(self, tmp_path: Path) -> None:+ """An absolute file path is untouched."""+ absolute = str(tmp_path / "inputs.toml")+ assert resolve_inputs_arg_against_dir(absolute, base_dir=tmp_path / "elsewhere") == absolute++ def test_tilde_is_expanded(self, tmp_path: Path) -> None:+ """A `~`-prefixed path expands to the home dir, not joined under base_dir."""+ result = resolve_inputs_arg_against_dir("~/inputs.toml", base_dir=tmp_path)+ assert result == str(Path("~/inputs.toml").expanduser())+ assert "~" not in (result or "")+ assert not (result or "").startswith(str(tmp_path))++ def test_inline_json_passes_through(self, tmp_path: Path) -> None:+ """Inline JSON (a `{` prefix) is untouched."""+ assert resolve_inputs_arg_against_dir('{"topic": "cats"}', base_dir=tmp_path) == '{"topic": "cats"}'++ def test_uri_passes_through(self, tmp_path: Path) -> None:+ """A URI-scheme string is preserved unchanged, not mangled into a broken local path under base_dir."""+ assert resolve_inputs_arg_against_dir("https://example.com/inputs.json", base_dir=tmp_path) == "https://example.com/inputs.json"+ assert resolve_inputs_arg_against_dir("s3://bucket/inputs.json", base_dir=tmp_path) == "s3://bucket/inputs.json"++ def test_none_passes_through(self, tmp_path: Path) -> None:+ """None (no --inputs given) is untouched."""+ assert resolve_inputs_arg_against_dir(None, base_dir=tmp_path) is Nonediff --git a/tests/unit/pipelex/cli/commands/run/test_inputs_file_loader.py b/tests/unit/pipelex/cli/commands/run/test_inputs_file_loader.pynew file mode 100644index 000000000..259927726--- /dev/null+++ b/tests/unit/pipelex/cli/commands/run/test_inputs_file_loader.py@@ -0,0 +1,123 @@+"""Unit tests for the shared inputs-file loader (extension-discriminated JSON/TOML)."""++from __future__ import annotations++import json+from typing import TYPE_CHECKING++import pytest++from pipelex.cli.commands.run._inputs_file_loader import load_inputs_dict_from_path # noqa: PLC2701 # pyright: ignore[reportPrivateUsage]+from pipelex.cli.commands.run.exceptions import InputsDatetimeNotSupportedError+from pipelex.tools.misc.exceptions import JsonTypeError, TomlError++if TYPE_CHECKING:+ from pathlib import Path+++class TestInputsFileLoader:+ def test_toml_file_loads(self, tmp_path: Path) -> None:+ """A .toml suffix routes through the TOML parser."""+ inputs_file = tmp_path / "inputs.toml"+ inputs_file.write_text('topic = "cats"\ncount = 3\n', encoding="utf-8")++ assert load_inputs_dict_from_path(inputs_file) == {"topic": "cats", "count": 3}++ def test_toml_multiline_string_round_trips(self, tmp_path: Path) -> None:+ """A TOML multi-line string lands verbatim (newlines preserved) in the input value."""+ inputs_file = tmp_path / "inputs.toml"+ inputs_file.write_text(+ '[contract_text]\nconcept = "Text"\ncontent = """\nFirst line.\nSecond line.\n"""\n',+ encoding="utf-8",+ )++ loaded = load_inputs_dict_from_path(inputs_file)++ assert loaded["contract_text"]["content"] == "First line.\nSecond line.\n"++ def test_json_file_loads(self, tmp_path: Path) -> None:+ """A .json suffix keeps today's JSON behavior."""+ inputs_file = tmp_path / "inputs.json"+ inputs_file.write_text(json.dumps({"topic": "dogs"}), encoding="utf-8")++ assert load_inputs_dict_from_path(inputs_file) == {"topic": "dogs"}++ def test_extensionless_file_treated_as_json(self, tmp_path: Path) -> None:+ """Only the .toml suffix selects TOML; an extensionless file is parsed as JSON."""+ inputs_file = tmp_path / "inputs"+ inputs_file.write_text(json.dumps({"key": "value"}), encoding="utf-8")++ assert load_inputs_dict_from_path(inputs_file) == {"key": "value"}++ @pytest.mark.parametrize("file_name", ["inputs.TOML", "inputs.Toml"])+ def test_uppercase_toml_suffix_routes_to_toml(self, tmp_path: Path, file_name: str) -> None:+ """The .toml suffix match is case-insensitive, so an uppercase suffix still parses as TOML."""+ inputs_file = tmp_path / file_name+ inputs_file.write_text('topic = "cats"\ncount = 3\n', encoding="utf-8")++ assert load_inputs_dict_from_path(inputs_file) == {"topic": "cats", "count": 3}++ def test_toml_syntax_error_raises_toml_error(self, tmp_path: Path) -> None:+ """Invalid TOML surfaces a TomlError naming the file."""+ inputs_file = tmp_path / "inputs.toml"+ inputs_file.write_text("topic = \n", encoding="utf-8")++ with pytest.raises(TomlError) as exc_info:+ load_inputs_dict_from_path(inputs_file)+ assert str(inputs_file) in exc_info.value.message++ def test_non_dict_json_raises_json_type_error(self, tmp_path: Path) -> None:+ """A JSON file holding a list (not a dict) still raises JsonTypeError."""+ inputs_file = tmp_path / "inputs.json"+ inputs_file.write_text('["not", "a", "dict"]', encoding="utf-8")++ with pytest.raises(JsonTypeError):+ load_inputs_dict_from_path(inputs_file)++ def test_missing_file_raises_file_not_found(self, tmp_path: Path) -> None:+ """A missing file raises FileNotFoundError for both formats."""+ with pytest.raises(FileNotFoundError):+ load_inputs_dict_from_path(tmp_path / "absent.toml")+ with pytest.raises(FileNotFoundError):+ load_inputs_dict_from_path(tmp_path / "absent.json")++ @pytest.mark.parametrize(+ "toml_value",+ [+ "2026-07-06T12:30:00Z",+ "2026-07-06T12:30:00",+ "2026-07-06",+ "12:30:00",+ ],+ ids=["offset_datetime", "local_datetime", "local_date", "local_time"],+ )+ def test_datetime_rejected_at_top_level(self, tmp_path: Path, toml_value: str) -> None:+ """Every TOML datetime flavor is rejected with the not-supported error."""+ inputs_file = tmp_path / "inputs.toml"+ inputs_file.write_text(f"deadline = {toml_value}\n", encoding="utf-8")++ with pytest.raises(InputsDatetimeNotSupportedError) as exc_info:+ load_inputs_dict_from_path(inputs_file)+ assert "not supported yet" in exc_info.value.message+ assert "deadline" in exc_info.value.message++ def test_datetime_rejected_nested(self, tmp_path: Path) -> None:+ """A datetime nested dict-in-list-in-dict is rejected, with its key path in the message."""+ inputs_file = tmp_path / "inputs.toml"+ inputs_file.write_text(+ '[record]\nconcept = "Event"\n[[record.entries]]\nlabel = "kickoff"\nwhen = 2026-07-06T09:00:00Z\n',+ encoding="utf-8",+ )++ with pytest.raises(InputsDatetimeNotSupportedError) as exc_info:+ load_inputs_dict_from_path(inputs_file)+ assert "record.entries[0].when" in exc_info.value.message++ def test_datetime_message_suggests_quoting(self, tmp_path: Path) -> None:+ """The rejection message tells the user to quote the value as a string meanwhile."""+ inputs_file = tmp_path / "inputs.toml"+ inputs_file.write_text("deadline = 2026-07-06\n", encoding="utf-8")++ with pytest.raises(InputsDatetimeNotSupportedError) as exc_info:+ load_inputs_dict_from_path(inputs_file)+ assert "quote the value as a string" in exc_info.value.messagediff --git a/tests/unit/pipelex/cli/commands/run/test_inputs_file_probe.py b/tests/unit/pipelex/cli/commands/run/test_inputs_file_probe.pynew file mode 100644index 000000000..11f2f63ae--- /dev/null+++ b/tests/unit/pipelex/cli/commands/run/test_inputs_file_probe.py@@ -0,0 +1,44 @@+"""Unit tests for the shared inputs.json / inputs.toml auto-detect probe."""++from __future__ import annotations++from typing import TYPE_CHECKING++import pytest++from pipelex.cli.commands.run._inputs_file_loader import find_default_inputs_file # noqa: PLC2701 # pyright: ignore[reportPrivateUsage]+from pipelex.cli.commands.run.exceptions import AmbiguousInputsFilesError++if TYPE_CHECKING:+ from pathlib import Path+++class TestFindDefaultInputsFile:+ def test_json_only_is_found(self, tmp_path: Path) -> None:+ """With only inputs.json present, the probe returns it."""+ json_file = tmp_path / "inputs.json"+ json_file.write_text("{}", encoding="utf-8")++ assert find_default_inputs_file(tmp_path) == json_file++ def test_toml_only_is_found(self, tmp_path: Path) -> None:+ """With only inputs.toml present, the probe returns it."""+ toml_file = tmp_path / "inputs.toml"+ toml_file.write_text("", encoding="utf-8")++ assert find_default_inputs_file(tmp_path) == toml_file++ def test_neither_returns_none(self, tmp_path: Path) -> None:+ """With neither default file present, the probe returns None."""+ assert find_default_inputs_file(tmp_path) is None++ def test_both_present_raises_ambiguity_error(self, tmp_path: Path) -> None:+ """With both default files present, the probe hard-errors telling the user to pass --inputs."""+ (tmp_path / "inputs.json").write_text("{}", encoding="utf-8")+ (tmp_path / "inputs.toml").write_text("", encoding="utf-8")++ with pytest.raises(AmbiguousInputsFilesError) as exc_info:+ find_default_inputs_file(tmp_path)+ assert "--inputs" in exc_info.value.message+ assert "inputs.json" in exc_info.value.message+ assert "inputs.toml" in exc_info.value.messagediff --git a/tests/unit/pipelex/cli/commands/run/test_inputs_template_roundtrip.py b/tests/unit/pipelex/cli/commands/run/test_inputs_template_roundtrip.pynew file mode 100644index 000000000..f250df057--- /dev/null+++ b/tests/unit/pipelex/cli/commands/run/test_inputs_template_roundtrip.py@@ -0,0 +1,53 @@+"""Round-trip test: a --format toml generated template loads back through the shared inputs-file loader.++The same template dict is serialized both ways (the JSON path `pipelex build inputs`+writes, and the new TOML path), then both files are loaded through+``load_inputs_dict_from_path`` — the loader the ``run`` surfaces use. The two loads+must resolve to the same dict as the original template, so a generated ``inputs.toml``+is guaranteed to feed ``pipelex run --inputs`` exactly like its ``inputs.json`` twin.+"""++from __future__ import annotations++import json+from typing import TYPE_CHECKING++from pipelex.cli.commands.run._inputs_file_loader import load_inputs_dict_from_path # noqa: PLC2701 # pyright: ignore[reportPrivateUsage]+from pipelex.core.pipes.inputs.input_renderer import serialize_inputs_template_to_toml++if TYPE_CHECKING:+ from pathlib import Path+++class TestInputsTemplateRoundTrip:+ def test_toml_template_loads_identically_to_json_template(self, tmp_path: Path) -> None:+ """The TOML serialization of a template loads back equal to the template and to its JSON twin."""+ template = {+ "document": {+ "concept": "demo.Document",+ "content": {+ "url": "https://example.invalid/doc",+ "summary": "line one\nline two",+ "page_count": 0,+ "score": 0.0,+ "is_signed": False,+ "tags": ["tags_item"],+ "metadata": {"metadata_key": "metadata_value"},+ },+ },+ "people": {+ "concept": "demo.Person",+ "content": [{"name": "name_value", "age": 0}],+ },+ }++ toml_file = tmp_path / "inputs.toml"+ toml_file.write_text(serialize_inputs_template_to_toml(template), encoding="utf-8")+ json_file = tmp_path / "inputs.json"+ json_file.write_text(json.dumps(template, indent=2, ensure_ascii=False), encoding="utf-8")++ toml_loaded = load_inputs_dict_from_path(toml_file)+ json_loaded = load_inputs_dict_from_path(json_file)++ assert toml_loaded == template+ assert toml_loaded == json_loadeddiff --git a/tests/unit/pipelex/cli/test_run_core_execution.py b/tests/unit/pipelex/cli/test_run_core_execution.pyindex 336b97b81..17973478d 100644--- a/tests/unit/pipelex/cli/test_run_core_execution.py+++ b/tests/unit/pipelex/cli/test_run_core_execution.py@@ -192,6 +192,58 @@ class TestRunCoreExecution:assert exc_info.value.exit_code == 1+ @pytest.mark.usefixtures("config_mock", "console")+ def test_toml_file_inputs_loaded_and_resolved(self, mocker: MockerFixture, tmp_path: Path) -> None:+ """A .toml inputs file is loaded through the TOML parser and run through the path resolver."""+ inputs_file = tmp_path / "inputs.toml"+ inputs_file.write_text('[report]\nconcept = "Text"\ncontent = """\nLine one.\nLine two.\n"""\n', encoding="utf-8")+ loaded_inputs = {"report": {"concept": "Text", "content": "Line one.\nLine two.\n"}}+ resolver_mock = mocker.patch(+ "pipelex.cli.commands.run._run_core.resolve_inputs_paths",+ return_value={**loaded_inputs, "resolved": True},+ )+ pipe_output = self._make_pipe_output(mocker)+ runner_class_mock = self._mock_runner(mocker, pipe_output)++ _run_async(_call_execute_run(inputs=str(inputs_file)))++ resolver_mock.assert_called_once_with(loaded_inputs, base_dir=tmp_path.resolve())+ execute_kwargs = runner_class_mock.return_value.execute.call_args.kwargs+ assert execute_kwargs["inputs"] == {**loaded_inputs, "resolved": True}++ @pytest.mark.usefixtures("console")+ def test_toml_syntax_error_input_file_exits(self, tmp_path: Path) -> None:+ """A .toml inputs file with invalid TOML syntax is rejected cleanly."""+ inputs_file = tmp_path / "inputs.toml"+ inputs_file.write_text("topic = \n", encoding="utf-8")++ with pytest.raises(typer.Exit) as exc_info:+ _run_async(_call_execute_run(inputs=str(inputs_file)))++ assert exc_info.value.exit_code == 1++ @pytest.mark.usefixtures("console")+ def test_toml_datetime_input_file_exits(self, tmp_path: Path) -> None:+ """A .toml inputs file holding a TOML datetime is rejected (not supported yet)."""+ inputs_file = tmp_path / "inputs.toml"+ inputs_file.write_text("deadline = 2026-07-06T12:00:00Z\n", encoding="utf-8")++ with pytest.raises(typer.Exit) as exc_info:+ _run_async(_call_execute_run(inputs=str(inputs_file)))++ assert exc_info.value.exit_code == 1++ @pytest.mark.usefixtures("console")+ def test_invalid_json_input_file_exits(self, tmp_path: Path) -> None:+ """A .json inputs file with invalid JSON syntax is rejected cleanly."""+ inputs_file = tmp_path / "inputs.json"+ inputs_file.write_text("{not valid json", encoding="utf-8")++ with pytest.raises(typer.Exit) as exc_info:+ _run_async(_call_execute_run(inputs=str(inputs_file)))++ assert exc_info.value.exit_code == 1+@pytest.mark.usefixtures("config_mock")def test_graph_outputs_saved(self, mocker: MockerFixture, console: Console, tmp_path: Path) -> None:"""A graph spec on the output triggers graph generation into the output dir."""diff --git a/tests/unit/pipelex/cli/test_stdin_resolver.py b/tests/unit/pipelex/cli/test_stdin_resolver.pyindex b12499664..ebf856ec6 100644--- a/tests/unit/pipelex/cli/test_stdin_resolver.py+++ b/tests/unit/pipelex/cli/test_stdin_resolver.py@@ -4,13 +4,17 @@ from __future__ import annotationsimport ioimport json-from typing import Any+from typing import TYPE_CHECKING, Anyimport pytestimport typer+from pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, set_agent_cli_error_formatfrom pipelex.cli.agent_cli.commands.run.stdin_resolver import parse_cli_inputs, resolve_stdin_inputs+if TYPE_CHECKING:+ from pathlib import Path+class TestStdinResolver:"""Tests for resolve_stdin_inputs() and parse_cli_inputs()."""@@ -289,11 +293,68 @@ class TestStdinResolver:assert exc_info.value.exit_code == 1# -------------------------------------------------------------------------- # auto_inputs_path precedence tests+ # TOML inputs file tests (.toml suffix routes through the TOML parser)+ # -------------------------------------------------------------------------++ def test_inputs_toml_file_path(self, tmp_path: Path) -> None:+ """--inputs with a .toml file path loads TOML, multi-line strings preserved."""+ toml_file = tmp_path / "inputs.toml"+ toml_file.write_text('[contract_text]\nconcept = "Text"\ncontent = """\nFirst line.\nSecond line.\n"""\n', encoding="utf-8")++ result = parse_cli_inputs(inputs_arg=str(toml_file))++ assert result == {"contract_text": {"concept": "Text", "content": "First line.\nSecond line.\n"}}++ def test_inputs_toml_syntax_error_envelope(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ """Invalid TOML in a .toml inputs file emits a TomlError envelope with input domain."""+ set_agent_cli_error_format(CliOutputFormat.JSON)+ toml_file = tmp_path / "inputs.toml"+ toml_file.write_text("topic = \n", encoding="utf-8")++ with pytest.raises(typer.Exit) as exc_info:+ parse_cli_inputs(inputs_arg=str(toml_file))++ assert exc_info.value.exit_code == 1+ envelope = json.loads(capsys.readouterr().err)+ assert envelope["error_type"] == "TomlError"+ assert envelope["error_domain"] == "input"+ assert "hint" in envelope++ def test_inputs_toml_datetime_error_envelope(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ """A TOML datetime input emits the not-supported envelope with the quote-as-string hint."""+ set_agent_cli_error_format(CliOutputFormat.JSON)+ toml_file = tmp_path / "inputs.toml"+ toml_file.write_text("deadline = 2026-07-06T12:00:00Z\n", encoding="utf-8")++ with pytest.raises(typer.Exit) as exc_info:+ parse_cli_inputs(inputs_arg=str(toml_file))++ assert exc_info.value.exit_code == 1+ envelope = json.loads(capsys.readouterr().err)+ assert envelope["error_type"] == "InputsDatetimeNotSupportedError"+ assert envelope["error_domain"] == "input"+ assert "deadline" in envelope["message"]+ assert "Quote the datetime as a string" in envelope["hint"]++ def test_inputs_json_syntax_error_envelope(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ """Invalid JSON in a .json inputs file emits a JSONDecodeError envelope (not a raw traceback)."""+ set_agent_cli_error_format(CliOutputFormat.JSON)+ json_file = tmp_path / "inputs.json"+ json_file.write_text("{not valid json", encoding="utf-8")++ with pytest.raises(typer.Exit) as exc_info:+ parse_cli_inputs(inputs_arg=str(json_file))++ assert exc_info.value.exit_code == 1+ envelope = json.loads(capsys.readouterr().err)+ assert envelope["error_type"] == "JSONDecodeError"++ # -------------------------------------------------------------------------+ # auto_inputs_dir precedence tests# -------------------------------------------------------------------------def test_stdin_beats_auto_detected_path(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> None:- """When stdin has data and auto_inputs_path is set, stdin wins."""+ """When stdin has data and auto_inputs_dir is set, stdin wins."""auto_file = tmp_path / "inputs.json"auto_file.write_text('{"from_auto": true}')@@ -302,11 +363,11 @@ class TestStdinResolver:mock_stdin.isatty = lambda: False # type: ignore[assignment]monkeypatch.setattr("sys.stdin", mock_stdin)- result = parse_cli_inputs(inputs_arg=None, auto_inputs_path=str(auto_file))+ result = parse_cli_inputs(inputs_arg=None, auto_inputs_dir=tmp_path)assert result == {"from_stdin": True}def test_explicit_inputs_beats_stdin_and_auto(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> None:- """When inputs_arg, stdin, and auto_inputs_path are all set, inputs_arg wins."""+ """When inputs_arg, stdin, and auto_inputs_dir are all set, inputs_arg wins."""auto_file = tmp_path / "inputs.json"auto_file.write_text('{"from_auto": true}')@@ -317,12 +378,12 @@ class TestStdinResolver:result = parse_cli_inputs(inputs_arg='{"from_arg": true}',- auto_inputs_path=str(auto_file),+ auto_inputs_dir=tmp_path,)assert result == {"from_arg": True}def test_empty_stdin_falls_back_to_auto_inputs_path(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> None:- """When stdin is non-TTY but empty and auto_inputs_path is set, auto path is used."""+ """When stdin is non-TTY but empty and auto_inputs_dir is set, the auto-detected file is used."""auto_file = tmp_path / "inputs.json"auto_file.write_text('{"from_auto": true}')@@ -330,11 +391,11 @@ class TestStdinResolver:mock_stdin.isatty = lambda: False # type: ignore[assignment]monkeypatch.setattr("sys.stdin", mock_stdin)- result = parse_cli_inputs(inputs_arg=None, auto_inputs_path=str(auto_file))+ result = parse_cli_inputs(inputs_arg=None, auto_inputs_dir=tmp_path)assert result == {"from_auto": True}def test_auto_detected_path_used_when_no_stdin(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> None:- """When stdin is a TTY and auto_inputs_path is set, auto path is used."""+ """When stdin is a TTY and auto_inputs_dir is set, the auto-detected file is used."""auto_file = tmp_path / "inputs.json"auto_file.write_text('{"from_auto": true}')@@ -342,5 +403,39 @@ class TestStdinResolver:mock_stdin.isatty = lambda: True # type: ignore[assignment]monkeypatch.setattr("sys.stdin", mock_stdin)- result = parse_cli_inputs(inputs_arg=None, auto_inputs_path=str(auto_file))+ result = parse_cli_inputs(inputs_arg=None, auto_inputs_dir=tmp_path)assert result == {"from_auto": True}++ def test_stdin_beats_ambiguous_auto_dir(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> None:+ """Piped stdin outranks auto-detect, so an ambiguous dir (both files) does NOT raise."""+ (tmp_path / "inputs.json").write_text('{"from_auto": true}')+ (tmp_path / "inputs.toml").write_text("from_auto = true\n")++ stdin_data = json.dumps({"from_stdin": True})+ mock_stdin = io.StringIO(stdin_data)+ mock_stdin.isatty = lambda: False # type: ignore[assignment]+ monkeypatch.setattr("sys.stdin", mock_stdin)++ result = parse_cli_inputs(inputs_arg=None, auto_inputs_dir=tmp_path)+ assert result == {"from_stdin": True}++ def test_ambiguous_auto_dir_raises_when_no_stdin(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Any, capsys: pytest.CaptureFixture[str]+ ) -> None:+ """With no stdin and both default files present, auto-detect is the active source and emits the ambiguity envelope."""+ set_agent_cli_error_format(CliOutputFormat.JSON)+ (tmp_path / "inputs.json").write_text('{"from_auto": true}')+ (tmp_path / "inputs.toml").write_text("from_auto = true\n")++ mock_stdin = io.StringIO("")+ mock_stdin.isatty = lambda: True # type: ignore[assignment]+ monkeypatch.setattr("sys.stdin", mock_stdin)++ with pytest.raises(typer.Exit) as exc_info:+ parse_cli_inputs(inputs_arg=None, auto_inputs_dir=tmp_path)++ assert exc_info.value.exit_code == 1+ envelope = json.loads(capsys.readouterr().err)+ assert envelope["error_type"] == "AmbiguousInputsFilesError"+ assert envelope["error_domain"] == "input"+ assert "--inputs" in envelope["hint"]diff --git a/tests/unit/pipelex/core/pipes/test_inputs_template_toml.py b/tests/unit/pipelex/core/pipes/test_inputs_template_toml.pynew file mode 100644index 000000000..fbbfce48e--- /dev/null+++ b/tests/unit/pipelex/core/pipes/test_inputs_template_toml.py@@ -0,0 +1,66 @@+"""Unit tests for the inputs-template TOML serializer (serialize_inputs_template_to_toml)."""++from __future__ import annotations++import tomli++from pipelex.core.pipes.inputs.input_renderer import serialize_inputs_template_to_toml+++class TestSerializeInputsTemplateToml:+ def test_representative_template_round_trips(self) -> None:+ """A template shaped like the generator's output survives a TOML dump/parse unchanged."""+ template = {+ "document": {+ "concept": "demo.Document",+ "content": {+ "url": "https://example.invalid/doc",+ "page_count": 0,+ "score": 0.0,+ "is_signed": False,+ "tags": ["tags_item"],+ "metadata": {"metadata_key": "metadata_value"},+ },+ },+ "people": {+ "concept": "demo.Person",+ "content": [{"name": "name_value", "age": 0}],+ },+ }++ toml_str = serialize_inputs_template_to_toml(template)++ assert tomli.loads(toml_str) == template++ def test_multiline_string_round_trips(self) -> None:+ """Multi-line string placeholders survive the TOML round trip byte-for-byte."""+ template = {"note": {"concept": "demo.Note", "content": {"text": "line one\nline two\n\nline four"}}}++ toml_str = serialize_inputs_template_to_toml(template)++ assert tomli.loads(toml_str) == template++ def test_none_values_become_empty_strings(self) -> None:+ """The pinned policy: TOML has no null, so None placeholders become empty strings — keys stay visible."""+ template = {+ "record": {+ "concept": "demo.Record",+ "content": {+ "maybe_text": None,+ "nested": {"maybe_inner": None},+ "items": [None, "kept"],+ },+ },+ }++ loaded = tomli.loads(serialize_inputs_template_to_toml(template))++ assert loaded["record"]["content"]["maybe_text"] == ""+ assert loaded["record"]["content"]["nested"]["maybe_inner"] == ""+ assert loaded["record"]["content"]["items"] == ["", "kept"]++ def test_empty_template_serializes_to_empty_document(self) -> None:+ """An empty template is a valid, empty TOML document."""+ toml_str = serialize_inputs_template_to_toml({})++ assert tomli.loads(toml_str) == {}