Skip to content

Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.

fix: harden run-by-address (alias-aware structures refusal, persistent outputs for fetched targets, agent-CLI error envelope) (#1162)

Louis Choquel42714143a276
diff --git a/.drift/acks/cli-docs.toml b/.drift/acks/cli-docs.toml
index 49e69244a..66075a5f9 100644
--- a/.drift/acks/cli-docs.toml
+++ b/.drift/acks/cli-docs.toml
@@ -1,8 +1,8 @@
contract = "cli-docs"
-digest = "sha256:ff4d5a366ab260fa3f93c01df71d949514a8b56549201ba84f8f1b827f9c4395"
+digest = "sha256:39e793b298f79da4dbc094804492f81fb91057e696ab1440d4197c3df7bdf44c"
reviewed_by = "Louis Choquel"
-reviewed_at = "2026-08-29T00:19:01Z"
-rationale = "Docstring/help-text only: the run method command's help now names the address form and adds an address example; the docs pages were already updated in this same change and stay accurate."
+reviewed_at = "2026-08-29T01:58:32Z"
+rationale = "Reviewed the targets against the build-runner materialization change: build/runner.md and run-by-address.md now document that a fetched target's package is copied beside the generated script and the script references the copy; the agent-CLI contract doc is unaffected (main-CLI-only change)."
[trigger_files]
"pipelex/cli/__init__.py" = "blob:8b137891791fe96927ad78e64b0aad7bded08bdc"
@@ -30,7 +30,7 @@ rationale = "Docstring/help-text only: the run method command's help now names t
"pipelex/cli/agent_cli/commands/inputs/_inputs_core.py" = "blob:d37826d96099028a1ad5dbc5cbf8ce0cfdb01e30"
"pipelex/cli/agent_cli/commands/inputs/app.py" = "blob:7e19284687b334c684fb03381a8d9d20af1aa152"
"pipelex/cli/agent_cli/commands/inputs/bundle_cmd.py" = "blob:43ac0fe0887f5f31144df4e4973a1ab1d0dec166"
-"pipelex/cli/agent_cli/commands/inputs/method_cmd.py" = "blob:80b08588fcde09e3a903b5bb7c774fc03d164d86"
+"pipelex/cli/agent_cli/commands/inputs/method_cmd.py" = "blob:15e8d82bd1536449c6690fd2975d84b4018b6130"
"pipelex/cli/agent_cli/commands/inputs/pipe_cmd.py" = "blob:a5cf89c89d5e2e84cc7b817ec184e8dc9e92b781"
"pipelex/cli/agent_cli/commands/lint_cmd.py" = "blob:91ad9cb4d618ba4c0b7da366cde2f74f38d350df"
"pipelex/cli/agent_cli/commands/migrate_cmd.py" = "blob:ce733b78df03e65c3c8a10d46b27b57c05ec054c"
@@ -39,18 +39,18 @@ rationale = "Docstring/help-text only: the run method command's help now names t
"pipelex/cli/agent_cli/commands/plxt_passthrough.py" = "blob:a1c530d110482485ce462f199b9e79fac29f8896"
"pipelex/cli/agent_cli/commands/run/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
"pipelex/cli/agent_cli/commands/run/_output_helpers.py" = "blob:40ed1700e0d5e86d7696eadd7f9887baeb8059f6"
-"pipelex/cli/agent_cli/commands/run/_run_core.py" = "blob:71847c81c0fd1986f73c117c7b358ea4a20d5d5d"
+"pipelex/cli/agent_cli/commands/run/_run_core.py" = "blob:9feae5b136a7399d30a9c221bf6f218ef1443395"
"pipelex/cli/agent_cli/commands/run/_run_core_api.py" = "blob:78a27e0ba91e6bbf99c11caedb29ad4cf20ac78b"
"pipelex/cli/agent_cli/commands/run/app.py" = "blob:64b2ecc02007cda11b526d8d3fc139593875dd9d"
"pipelex/cli/agent_cli/commands/run/bundle_cmd.py" = "blob:daf6207146c0ea41fe34bb272ed51350208af790"
-"pipelex/cli/agent_cli/commands/run/method_cmd.py" = "blob:577f5b301de7de5cec263ac0af04d82c317992a2"
+"pipelex/cli/agent_cli/commands/run/method_cmd.py" = "blob:d65cdba36e63563d0f225dafc7f8593b91af9317"
"pipelex/cli/agent_cli/commands/run/pipe_cmd.py" = "blob:df5e7f80a328932ffde901eda8d0585d009678ad"
"pipelex/cli/agent_cli/commands/run/stdin_resolver.py" = "blob:4bc7f4e91ddb3900a75356f8f8e6ba5a586a3690"
"pipelex/cli/agent_cli/commands/validate/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
"pipelex/cli/agent_cli/commands/validate/_validate_core.py" = "blob:6e9e8488573fe17d7769608e299879a092ceaf6c"
"pipelex/cli/agent_cli/commands/validate/app.py" = "blob:d2d0ed19288c2d1c25be1650dd962189fcdb3b86"
"pipelex/cli/agent_cli/commands/validate/bundle_cmd.py" = "blob:3207973c194b096ed5c6ec2d3a955c417789e019"
-"pipelex/cli/agent_cli/commands/validate/method_cmd.py" = "blob:27d0e4b3f3550bd6352356abe06bc863a0255260"
+"pipelex/cli/agent_cli/commands/validate/method_cmd.py" = "blob:38fae7d9f8f26594f80e875251e926cc99f26dff"
"pipelex/cli/agent_cli/commands/validate/pipe_cmd.py" = "blob:7c15cf5a7341b774baad2f14540acbef8daebf76"
"pipelex/cli/bundle_target_resolution.py" = "blob:8dccc50b700b877968ed1b2c1c3652ab1c32e956"
"pipelex/cli/cli_factory.py" = "blob:1f859ab3b995e1a67e5fdc812a168d56c338e970"
@@ -61,19 +61,19 @@ rationale = "Docstring/help-text only: the run method command's help now names t
"pipelex/cli/commands/build/inputs/_inputs_core.py" = "blob:50317e058df75070722d2e29edab4537e6b7b438"
"pipelex/cli/commands/build/inputs/app.py" = "blob:2a7770c8294b8c2c1b4420ac00d6ffdfa50609bf"
"pipelex/cli/commands/build/inputs/bundle_cmd.py" = "blob:0cd99e9d307f46b8e8899bf7d5f3813563fcdf10"
-"pipelex/cli/commands/build/inputs/method_cmd.py" = "blob:4ab9efefc01572c24f5f15bc0eeded2dd4f60804"
+"pipelex/cli/commands/build/inputs/method_cmd.py" = "blob:fffeebfbec3ae19c5030619b647719e953c50b15"
"pipelex/cli/commands/build/inputs/pipe_cmd.py" = "blob:00625740fd29837e3165d31be692e40e96065fc8"
"pipelex/cli/commands/build/output/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
"pipelex/cli/commands/build/output/_output_core.py" = "blob:9ba47b88a3c0b6cbf3f8de5f9a4939373f64ceb8"
"pipelex/cli/commands/build/output/app.py" = "blob:67996650b99551fbd58be30e692688204d16935a"
"pipelex/cli/commands/build/output/bundle_cmd.py" = "blob:54c07aedb123eaaf2049965859e82b6d4800560d"
-"pipelex/cli/commands/build/output/method_cmd.py" = "blob:89bb60c732b1ecb1a0b1bad756c846bc56e64cdb"
+"pipelex/cli/commands/build/output/method_cmd.py" = "blob:1a21e5d106870ea4d66014ccba07a378b7aa970b"
"pipelex/cli/commands/build/output/pipe_cmd.py" = "blob:eb0db8279c93fcff9d5fe4546f593d753282acb5"
"pipelex/cli/commands/build/runner/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
"pipelex/cli/commands/build/runner/_runner_core.py" = "blob:e4745231cb46547de93d83d1ac7a6db28ae81494"
"pipelex/cli/commands/build/runner/app.py" = "blob:b5aa321ed93dc2cb9b138e4a26bae9eb75c732b7"
"pipelex/cli/commands/build/runner/bundle_cmd.py" = "blob:5b5ca0628f0595a0c3aae9b539ae4e7e0c92a853"
-"pipelex/cli/commands/build/runner/method_cmd.py" = "blob:63ecd2c06b1455e300b4f0090af188c527298299"
+"pipelex/cli/commands/build/runner/method_cmd.py" = "blob:7d8ff2457569b3efa68830db6cdd031e4c6b9b2d"
"pipelex/cli/commands/build/structures_cmd.py" = "blob:d13ba3b6fc1433f787e1aa97c6c04a67483ec7ed"
"pipelex/cli/commands/bundle_path_resolver.py" = "blob:60c6a2994c9b7c6e0ec212702467d668eecb6d50"
"pipelex/cli/commands/codegen/__init__.py" = "blob:e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
@@ -115,7 +115,7 @@ rationale = "Docstring/help-text only: the run method command's help now names t
"pipelex/cli/commands/run/app.py" = "blob:a7090b0ff6bf2f1d47827fa27d2a138096a2e148"
"pipelex/cli/commands/run/bundle_cmd.py" = "blob:cb420bf4879c863d64c5e20ed535c42732b720a2"
"pipelex/cli/commands/run/exceptions.py" = "blob:e9552226e597922b6ac0757f7b52eb880a2e1472"
-"pipelex/cli/commands/run/method_cmd.py" = "blob:6be6e163eb3c1ca768332a47916f8fe479e20e7c"
+"pipelex/cli/commands/run/method_cmd.py" = "blob:47344150d71386398ef9a4fad8aca54a3ea1d0a8"
"pipelex/cli/commands/run/pipe_cmd.py" = "blob:f92fcb94e3ad55cf5aeec366a59fa7a74bcc9667"
"pipelex/cli/commands/show_cmd.py" = "blob:7974d91404ea93f05b16b05b9aef3c1a540b965d"
"pipelex/cli/commands/update_cmd.py" = "blob:06100ec3b9d6c66ca89a8c1536aa27983ae409ca"
@@ -130,5 +130,5 @@ rationale = "Docstring/help-text only: the run method command's help now names t
"pipelex/cli/error_handlers.py" = "blob:7a925ef0517bf9b01c3ca4b91ae54a70f57123a6"
"pipelex/cli/exceptions.py" = "blob:1d51c3a53ddd3f6cf8de566fa2ade3fa75ab7a3a"
"pipelex/cli/installed_methods.py" = "blob:565b08fdd10efa0682d17619cfd7df252dbf61b5"
-"pipelex/cli/method_resolver.py" = "blob:83511db5f6010982aa6c4d3569c475acbfe3af61"
+"pipelex/cli/method_resolver.py" = "blob:1230dde5f89ac28bbdcbcbbd0c1d485c71803caf"
"pipelex/cli/readiness.py" = "blob:6d185324ed0784663e1dc78d1194a28312c54798"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1c888ba22..dcfb530bd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,7 @@
### Added
-- **Run a method by address**: every command that resolves a method target (`pipelex run method`, `pipelex validate method`, the `pipelex build` method commands, and their agent-CLI twins) now accepts a method reference `<address>[@<tag>]` — `github.com/<owner>/<repo>[/<selector>]`, optionally pinned at a git tag (a `@<name>` that names a branch rather than a tag is refused, so only tags pin a revision) — alongside installed names, local paths, and full GitHub URLs. The new `pipelex/methods/` package is the single implementation the CLI, the API, and tests all share: the `MethodRef` grammar parser, fetch-at-tag (wiring the `mthds` `clone_at_version` machinery beside `clone_default_branch`, with the fetched commit SHA always resolved and reported as provenance), package location inside the clone by **manifest identity** (scan for `METHODS.toml`, match the full address, case-insensitively; a miss or ambiguity is a loud error listing the packages the clone contains), env-tunable fetched-package ceilings (file count and total bytes, plus a bounded manifest scan — a size cap per `METHODS.toml` read and a cap on manifests considered per repository), and the reusable structures-refusal check — an AST scan for `StructuredContent` subclasses producing the rule-naming error (*hosted execution accepts MTHDS concepts and sandboxed PipeFuncs, not in-process Python*), which the CLI surfaces as a hosted-parity warning and a hosted runner can apply as a hard refusal. See [Run a Method by Address](tools/cli/run-by-address.md). (Breaking: bare `github.com/...` targets no longer resolve as local paths, and packages inside a fetched repository are located by manifest identity rather than directory path — `/tree/<branch>/<dir>` deep links now resolve through the manifest's `address`/`name`.)
+- **Run a method by address**: every command that resolves a method target (`pipelex run method`, `pipelex validate method`, the `pipelex build` method commands, and their agent-CLI twins) now accepts a method reference `<address>[@<tag>]` — `github.com/<owner>/<repo>[/<selector>]`, optionally pinned at a git tag (a `@<name>` that names a branch rather than a tag is refused, so only tags pin a revision) — alongside installed names, local paths, and full GitHub URLs. The new `pipelex/methods/` package is the single implementation the CLI, the API, and tests all share: the `MethodRef` grammar parser, fetch-at-tag (wiring the `mthds` `clone_at_version` machinery beside `clone_default_branch`, with the fetched commit SHA always resolved and reported as provenance), package location inside the clone by **manifest identity** (scan for `METHODS.toml`, match the full address, case-insensitively; a miss or ambiguity is a loud error listing the packages the clone contains), env-tunable fetched-package ceilings (file count and total bytes, plus a bounded manifest scan — a size cap per `METHODS.toml` read and a cap on manifests considered per repository), and the reusable structures-refusal check — an alias-aware AST scan for `StructuredContent` subclasses (bases reached through `import ... as` aliases and attribute access are caught alongside the literal name) producing the rule-naming error (*hosted execution accepts MTHDS concepts and sandboxed PipeFuncs, not in-process Python*), which the CLI surfaces as a hosted-parity warning and a hosted runner can apply as a hard refusal. A fetched target's default outputs (run results, graphs, generated files) anchor in the caller's working directory — the fetched clone itself is ephemeral and deleted at process exit — `build runner` additionally copies the fetched package beside the generated script so the runner stays self-contained, and a method-reference failure reaches the agent CLI as its structured error envelope, like every other agent-CLI error. See [Run a Method by Address](tools/cli/run-by-address.md). (Breaking: bare `github.com/...` targets no longer resolve as local paths, and packages inside a fetched repository are located by manifest identity rather than directory path — `/tree/<branch>/<dir>` deep links now resolve through the manifest's `address`/`name`.)
### Changed
diff --git a/docs/tools/cli/build/runner.md b/docs/tools/cli/build/runner.md
index d850b5b16..423be944a 100644
--- a/docs/tools/cli/build/runner.md
+++ b/docs/tools/cli/build/runner.md
@@ -40,6 +40,8 @@ pipelex build runner method <NAME> [OPTIONS]
- `--output`, `-o` - Path to save the generated Python file
- `--library-dirs`, `-L` - Directories to search for pipe definitions. Can be specified multiple times.
+For a method fetched by address, the package is copied beside the generated script (into a directory named after the method) and the script references that copy — the fetched clone itself is temporary and deleted at process exit, so the generated runner stays self-contained and usable afterwards. See [Run a Method by Address](../run-by-address.md).
+
## Examples
**Generate runner from a bundle (uses main_pipe):**
diff --git a/docs/tools/cli/run-by-address.md b/docs/tools/cli/run-by-address.md
index 81f873cb2..9cb7d4e2d 100644
--- a/docs/tools/cli/run-by-address.md
+++ b/docs/tools/cli/run-by-address.md
@@ -44,6 +44,12 @@ No match, or more than one, is a loud error listing the packages the clone does
The pipe to run defaults to the manifest's `main_pipe`; `--pipe <code>` overrides it. A method with no `main_pipe` requires `--pipe`.
+## Where outputs land
+
+The fetched clone is temporary: it lives in a system temp directory and is deleted when the CLI process exits. Default outputs therefore anchor in **your current working directory** — `pipelex run method <ref>` writes into `./results/`, and the `pipelex build` method commands write their generated files there too, so nothing you produced disappears with the clone. An explicit `--output-dir` / `--output` is honored verbatim. For an installed method or a local path, defaults stay inside the method's own directory, as before.
+
+`pipelex build runner method <ref>` goes one step further: the generated script embeds the library directory it loads at run time, so the fetched package is copied beside the script (into a directory named after the method) and the script references that copy — a self-contained artifact that still works after the clone is gone.
+
## Python in fetched methods: the hosted rule
What decides whether Python in a method is acceptable is **where it would execute**:
diff --git a/docs/tools/cli/run.md b/docs/tools/cli/run.md
index 8ebfbfb38..29df6f7e3 100644
--- a/docs/tools/cli/run.md
+++ b/docs/tools/cli/run.md
@@ -129,7 +129,7 @@ Runs a pipeline from an installed method package.
- `--pipe PIPE_CODE` - Run a specific pipe within the method (defaults to the method's main pipe)
- `--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
+- `--output-dir`, `-o` - Directory to save outputs (defaults to `results/` inside the method's directory; for a method fetched by address, `results/` under your current working directory — see [Run a Method by Address](run-by-address.md))
- `--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
- `--working-memory-path` - Custom path for the working memory output file
diff --git a/pipelex/cli/agent_cli/CLAUDE.md b/pipelex/cli/agent_cli/CLAUDE.md
index c20dd4cc6..6a91bf111 100644
--- a/pipelex/cli/agent_cli/CLAUDE.md
+++ b/pipelex/cli/agent_cli/CLAUDE.md
@@ -106,5 +106,6 @@ commands/
- **The `migration` field on a configuration error**: A `PipelexConfigError` carries one when a scan of this machine's configuration directories found something — and only then, so its presence is the test for whether the migration history has anything to say. Whether a command *repairs* it is the separate `would_write` field: true means the configuration is *old*, and the loop is `pipelex-agent migrate --dry-run --format json`, show the user, then `--yes`; false means the block is a diagnosis its `plans` carry and the command would rewrite nothing, so branching on presence alone sends an agent to a run with nothing to do. Its `plans` are the same shape that command emits under its own `plans` key. `error_domain` stays `config`: a domain the hook specification does not know routes to BLOCK, which would stop an agent instead of telling it what to run. See `docs/migration-ledger.md` → "Reporting a stale configuration on a validation error".
- **Init**: All commands that need Pipelex use `make_pipelex_for_agent_cli(library_dirs)`. It catches init errors and routes them through `agent_error()`.
- **Async core**: Run and validate are async — commands use `asyncio.run()`.
-- **File convention**: Generated outputs go to `mthds-wip/` with incremental naming (`pipeline_01/`, `pipeline_02/`).
+- **File convention**: Generated outputs go to `mthds-wip/` with incremental naming (`pipeline_01/`, `pipeline_02/`). Exception: `run method` on a fetched target (a method address or GitHub URL) anchors its run outputs in `results/` under the caller's CWD via `run_pipeline_core`'s `output_dir_override` — the fetched clone is an ephemeral temp dir deleted at process exit, so bundle-adjacent outputs would be lost.
+- **Method-reference failures**: the `run`/`validate`/`inputs` method commands call `resolve_method_target(..., raise_ref_errors=True)` and shape the typed `MethodRefError` subclasses into `agent_error(...)` themselves (validate uses `exit_code=2`, its no-verdict convention) — the human CLI's red-text rendering stays in `resolve_method_target`'s default arm.
- **TOML handling**: Uses `tomlkit` (not `tomllib`) to preserve formatting and inline tables.
diff --git a/pipelex/cli/agent_cli/commands/inputs/method_cmd.py b/pipelex/cli/agent_cli/commands/inputs/method_cmd.py
index 80b08588f..15e8d82bd 100644
--- a/pipelex/cli/agent_cli/commands/inputs/method_cmd.py
+++ b/pipelex/cli/agent_cli/commands/inputs/method_cmd.py
@@ -14,6 +14,7 @@ from pipelex.cli.agent_cli.commands.inputs._inputs_core import emit_inputs_resul
from pipelex.cli.method_resolver import resolve_method_target
from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError
from pipelex.core.pipes.inputs.exceptions import NoInputsRequiredError
+from pipelex.methods.exceptions import MethodRefError
from pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormat
from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError
from pipelex.pipelex import Pipelex
@@ -54,11 +55,18 @@ def inputs_method_cmd(
pipelex-agent inputs method my-method --format toml
pipelex-agent inputs method my-method --explicit
"""
- pipe_code, method_library_dirs, method = resolve_method_target(
- method_name=name,
- pipe_override=pipe,
- library_dirs=library_dir,
- )
+ try:
+ pipe_code, method_library_dirs, method = resolve_method_target(
+ method_name=name,
+ pipe_override=pipe,
+ library_dirs=library_dir,
+ raise_ref_errors=True,
+ )
+ except MethodRefError as exc:
+ # Method-reference failure (parse, fetch, location, bounds, refusal): report it through
+ # the structured error envelope instead of the human CLI's plain red text.
+ agent_error(str(exc), error_type=type(exc).__name__, cause=exc)
+
bundle_path: Path | None = None
if method.mthds_files:
bundle_path = method.mthds_files[0]
diff --git a/pipelex/cli/agent_cli/commands/run/_run_core.py b/pipelex/cli/agent_cli/commands/run/_run_core.py
index 71847c81c..9feae5b13 100644
--- a/pipelex/cli/agent_cli/commands/run/_run_core.py
+++ b/pipelex/cli/agent_cli/commands/run/_run_core.py
@@ -33,6 +33,7 @@ async def run_pipeline_core(
costs: bool = True,
with_memory: bool = False,
inputs_base_dir: Path | None = None,
+ output_dir_override: Path | None = None,
) -> dict[str, Any]:
"""Core logic for running a pipeline and returning JSON-serializable output.
@@ -50,6 +51,9 @@ async def run_pipeline_core(
return compact concept JSON only (False, default).
inputs_base_dir: Directory bare relative file paths in ``inputs`` resolve against (Smart
Inputs D3) — the inputs file's parent when file-loaded, else ``None``.
+ output_dir_override: Directory to write run outputs (output JSON, graph files) into,
+ overriding the bundle-adjacent default. The caller passes one when the bundle lives
+ in a directory that will not survive the process — a fetched method's ephemeral clone.
Returns:
Dictionary with execution results suitable for JSON serialization.
@@ -107,9 +111,13 @@ async def run_pipeline_core(
compact_result=compact_result,
)
- # Determine output directory: next to the bundle, or mthds-wip/ fallback
+ # Determine output directory: an explicit override wins (a fetched method's bundle lives in an
+ # ephemeral clone deleted at process exit, so the caller re-anchors outputs somewhere durable);
+ # otherwise next to the bundle, or mthds-wip/ fallback
output_dir: Path
- if bundle_uris and not bundle_uris[0].startswith(("http://", "https://")):
+ if output_dir_override is not None:
+ output_dir = output_dir_override
+ elif bundle_uris and not bundle_uris[0].startswith(("http://", "https://")):
output_dir = Path(bundle_uris[0]).parent
else:
output_dir = Path("mthds-wip")
diff --git a/pipelex/cli/agent_cli/commands/run/method_cmd.py b/pipelex/cli/agent_cli/commands/run/method_cmd.py
index 577f5b301..d65cdba36 100644
--- a/pipelex/cli/agent_cli/commands/run/method_cmd.py
+++ b/pipelex/cli/agent_cli/commands/run/method_cmd.py
@@ -17,8 +17,9 @@ from pipelex.cli.agent_cli.commands.run._run_core import run_pipeline_core
from pipelex.cli.agent_cli.commands.run._run_core_api import run_pipeline_core_api
from 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_dir
-from pipelex.cli.method_resolver import resolve_method_target
+from pipelex.cli.method_resolver import method_output_base_dir, resolve_method_target
from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError
+from pipelex.methods.exceptions import MethodRefError
from pipelex.mthds_parsing.helpers import MTHDS_EXTENSION
from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError
from pipelex.pipelex import Pipelex
@@ -89,11 +90,24 @@ def run_method_cmd(
if mock_inputs and not dry_run:
agent_error("--mock-inputs requires --dry-run", error_type="ArgumentError")
- pipe_code, method_library_dirs, method = resolve_method_target(
- method_name=name,
- pipe_override=pipe,
- library_dirs=library_dir,
- )
+ try:
+ pipe_code, method_library_dirs, method = resolve_method_target(
+ method_name=name,
+ pipe_override=pipe,
+ library_dirs=library_dir,
+ raise_ref_errors=True,
+ )
+ except MethodRefError as exc:
+ # Method-reference failure (parse, fetch, location, bounds, refusal): report it through
+ # the structured error envelope instead of the human CLI's plain red text.
+ agent_error(str(exc), error_type=type(exc).__name__, cause=exc)
+
+ # A fetched method's package directory is an ephemeral clone deleted at process exit —
+ # anchor run outputs (output JSON, graph files) in a durable location instead.
+ output_dir_override: Path | None = None
+ if method.provenance is not None:
+ output_dir_override = method_output_base_dir(method=method) / "results"
+
bundle_path: str | None = None
mthds_content: str | None = None
@@ -172,6 +186,7 @@ def run_method_cmd(
costs=costs,
with_memory=with_memory,
inputs_base_dir=parsed_inputs.inputs_base_dir,
+ output_dir_override=output_dir_override,
)
)
agent_success_formatted(
diff --git a/pipelex/cli/agent_cli/commands/validate/method_cmd.py b/pipelex/cli/agent_cli/commands/validate/method_cmd.py
index 27d0e4b3f..38fae7d9f 100644
--- a/pipelex/cli/agent_cli/commands/validate/method_cmd.py
+++ b/pipelex/cli/agent_cli/commands/validate/method_cmd.py
@@ -22,6 +22,7 @@ from pipelex.cli.agent_cli.commands.validate._validate_core import (
)
from pipelex.cli.method_resolver import resolve_method_target
from pipelex.core.pipes.exceptions import PipeOperatorModelChoiceError
+from pipelex.methods.exceptions import MethodRefError
from pipelex.pipe_operators.exceptions import PipeOperatorModelAvailabilityError
from pipelex.pipelex import Pipelex
from pipelex.pipeline.exceptions import ValidateBundleError
@@ -70,11 +71,18 @@ def validate_method_cmd(
"""
set_agent_cli_error_format(error_format or output_format)
- pipe_code, method_library_dirs, method = resolve_method_target(
- method_name=name,
- pipe_override=pipe,
- library_dirs=library_dir,
- )
+ try:
+ pipe_code, method_library_dirs, method = resolve_method_target(
+ method_name=name,
+ pipe_override=pipe,
+ library_dirs=library_dir,
+ raise_ref_errors=True,
+ )
+ except MethodRefError as exc:
+ # Method-reference failure (parse, fetch, location, bounds, refusal): no verdict could be
+ # produced, so exit 2 with the structured error envelope (not the human CLI's red text).
+ agent_error(str(exc), error_type=type(exc).__name__, cause=exc, exit_code=2)
+
if not method.mthds_files:
agent_error(f"Method '{name}' has no .mthds bundle files.", error_type="MethodError", exit_code=2)
diff --git a/pipelex/cli/commands/build/inputs/method_cmd.py b/pipelex/cli/commands/build/inputs/method_cmd.py
index 4ab9efefc..fffeebfbe 100644
--- a/pipelex/cli/commands/build/inputs/method_cmd.py
+++ b/pipelex/cli/commands/build/inputs/method_cmd.py
@@ -7,7 +7,7 @@ import typer
from pipelex.builder.conventions import DEFAULT_INPUTS_FILE_NAME, DEFAULT_INPUTS_TOML_FILE_NAME
from pipelex.cli.commands.build.inputs._inputs_core import execute_generate_inputs
-from pipelex.cli.method_resolver import resolve_method_target
+from pipelex.cli.method_resolver import method_output_base_dir, resolve_method_target
from pipelex.pipe_machinery.rendering.input_renderer import InputsTemplateFormat
@@ -50,7 +50,7 @@ def build_inputs_method_cmd(
pipelex build inputs method my-method --format toml
pipelex build inputs method my-method --explicit
"""
- pipe_code, method_library_dirs, _ = resolve_method_target(
+ pipe_code, method_library_dirs, method = resolve_method_target(
method_name=name,
pipe_override=pipe,
library_dirs=library_dir,
@@ -60,7 +60,7 @@ def build_inputs_method_cmd(
if library_dir:
effective_library_dir.extend(library_dir)
- # Default output to a results/ folder inside the method's directory
+ # Default output to a results/ folder under the method's output base (the caller's CWD for fetched methods)
if output_path:
output_path_path = Path(output_path)
else:
@@ -70,7 +70,7 @@ def build_inputs_method_cmd(
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_name
+ output_path_path = method_output_base_dir(method=method) / "results" / default_file_name
execute_generate_inputs(
pipe_code=pipe_code,
diff --git a/pipelex/cli/commands/build/output/method_cmd.py b/pipelex/cli/commands/build/output/method_cmd.py
index 89bb60c73..1a21e5d10 100644
--- a/pipelex/cli/commands/build/output/method_cmd.py
+++ b/pipelex/cli/commands/build/output/method_cmd.py
@@ -6,7 +6,7 @@ from typing import Annotated
import typer
from pipelex.cli.commands.build.output._output_core import execute_generate_output
-from pipelex.cli.method_resolver import resolve_method_target
+from pipelex.cli.method_resolver import method_output_base_dir, resolve_method_target
from pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormat
@@ -63,7 +63,7 @@ def build_output_method_cmd(
)
raise typer.Exit(1)
- pipe_code, method_library_dirs, _ = resolve_method_target(
+ pipe_code, method_library_dirs, method = resolve_method_target(
method_name=name,
pipe_override=pipe,
library_dirs=library_dir,
@@ -73,11 +73,11 @@ def build_output_method_cmd(
if library_dir:
effective_library_dir.extend(library_dir)
- # Default output to a results/ folder inside the method's directory
+ # Default output to a results/ folder under the method's output base (the caller's CWD for fetched methods)
if output_path:
output_path_path: Path | None = Path(output_path)
else:
- results_dir = Path(method_library_dirs[0]) / "results"
+ results_dir = method_output_base_dir(method=method) / "results"
match concept_format:
case ConceptRepresentationFormat.JSON:
output_path_path = results_dir / "output.json"
diff --git a/pipelex/cli/commands/build/runner/method_cmd.py b/pipelex/cli/commands/build/runner/method_cmd.py
index 63ecd2c06..7d8ff2457 100644
--- a/pipelex/cli/commands/build/runner/method_cmd.py
+++ b/pipelex/cli/commands/build/runner/method_cmd.py
@@ -1,12 +1,13 @@
from __future__ import annotations
+import shutil
from pathlib import Path
from typing import Annotated
import typer
from pipelex.cli.commands.build.runner._runner_core import execute_prepare_runner
-from pipelex.cli.method_resolver import resolve_method_target
+from pipelex.cli.method_resolver import method_output_base_dir, resolve_method_target
def build_runner_method_cmd(
@@ -51,11 +52,23 @@ def build_runner_method_cmd(
raise typer.Exit(1)
bundle_path = method.mthds_files[0]
- # Default output to a results/ folder inside the method's directory
+ # Default output to a results/ folder under the method's output base (the caller's CWD for fetched methods)
+ output_path_path: Path
if output_path:
- output_path_path: Path | None = Path(output_path)
+ output_path_path = Path(output_path)
else:
- output_path_path = Path(method_library_dirs[0]) / "results" / f"run_{pipe_code}.py"
+ output_path_path = method_output_base_dir(method=method) / "results" / f"run_{pipe_code}.py"
+
+ if method.provenance is not None:
+ # The generated script embeds the library dir it loads at run time, and a fetched
+ # package's directory is an ephemeral clone deleted at process exit — so a runner
+ # pointing there would be broken on first use. Materialize the package beside the
+ # generated script and embed that path instead, keeping the artifact self-contained.
+ materialized_dir = output_path_path.parent / method.name
+ shutil.copytree(method.path, materialized_dir, ignore=shutil.ignore_patterns(".git", "__pycache__"), dirs_exist_ok=True)
+ bundle_path = materialized_dir / bundle_path.relative_to(method.path)
+ method_library_dirs = [str(materialized_dir)]
+ typer.secho(f"Copied fetched package into {materialized_dir} (referenced by the generated runner)", fg=typer.colors.BLUE, err=True)
library_dirs_paths = [Path(lib_dir) for lib_dir in method_library_dirs]
if library_dirs:
diff --git a/pipelex/cli/commands/run/method_cmd.py b/pipelex/cli/commands/run/method_cmd.py
index 6be6e163e..47344150d 100644
--- a/pipelex/cli/commands/run/method_cmd.py
+++ b/pipelex/cli/commands/run/method_cmd.py
@@ -7,7 +7,7 @@ import typer
from pipelex.cli.commands.run._inputs_file_loader import resolve_inputs_arg_against_dir
from pipelex.cli.commands.run._run_core import COMMAND, execute_run, validate_run_flag_combination
-from pipelex.cli.method_resolver import resolve_method_target
+from pipelex.cli.method_resolver import method_output_base_dir, resolve_method_target
def run_method_cmd(
@@ -120,7 +120,7 @@ def run_method_cmd(
validate_run_flag_combination(dry_run=dry_run, mock_usage=mock_usage, mock_inputs=mock_inputs)
# Resolve method name to pipe_code and library dirs
- pipe_code, method_library_dirs, _ = resolve_method_target(
+ pipe_code, method_library_dirs, method = resolve_method_target(
method_name=name,
pipe_override=pipe,
library_dirs=library_dir,
@@ -128,8 +128,10 @@ def run_method_cmd(
method_dir = Path(method_library_dirs[0])
- # Default output_dir to a results/ folder inside the method's directory
- effective_output_dir = output_dir or str(method_dir / "results")
+ # Default output_dir to a results/ folder under the method's output base: the method's own
+ # directory for installed/local methods, the caller's CWD for fetched ones (whose package
+ # directory is an ephemeral clone deleted at process exit).
+ effective_output_dir = output_dir or str(method_output_base_dir(method=method) / "results")
# Resolve --inputs relative to the method's directory
effective_inputs = resolve_inputs_arg_against_dir(inputs, base_dir=method_dir)
diff --git a/pipelex/cli/method_resolver.py b/pipelex/cli/method_resolver.py
index 83511db5f..1230dde5f 100644
--- a/pipelex/cli/method_resolver.py
+++ b/pipelex/cli/method_resolver.py
@@ -15,7 +15,7 @@ from pipelex.cli.installed_methods import (
discover_method_at,
find_method_by_name,
)
-from pipelex.methods.exceptions import MethodRefError, MethodRefParseError
+from pipelex.methods.exceptions import MethodRefError
from pipelex.methods.fetching import fetch_method_package
from pipelex.methods.method_ref import looks_like_method_ref, parse_method_ref
from pipelex.methods.structures_check import (
@@ -116,7 +116,10 @@ def resolve_method_from_ref(ref_str: str) -> InstalledMethod:
classes that hosted execution would refuse.
Uses a temporary directory that persists for the duration of the CLI process, so the
- fetched files remain available for subsequent steps.
+ fetched files remain available for subsequent steps. Failures raise the typed
+ ``MethodRefError`` family — presentation is the caller's concern: the human CLI
+ renders them through ``resolve_method_target``, the agent CLI shapes them into its
+ structured error envelope.
Args:
ref_str: The method reference string.
@@ -125,22 +128,15 @@ def resolve_method_from_ref(ref_str: str) -> InstalledMethod:
The discovered ``InstalledMethod``, carrying the fetch provenance.
Raises:
- typer.Exit: On a parse, fetch, location, or bounds failure.
+ MethodRefError: On a parse, fetch, location, bounds, or refusal failure
+ (the concrete subclass names which).
"""
- try:
- method_ref = parse_method_ref(ref_str)
- except MethodRefParseError as exc:
- typer.secho(str(exc), fg=typer.colors.RED, err=True)
- raise typer.Exit(1) from exc
+ method_ref = parse_method_ref(ref_str)
dest = Path(tempfile.mkdtemp(prefix="mthds_remote_"))
atexit.register(shutil.rmtree, dest, True)
- try:
- fetched = fetch_method_package(ref=method_ref, dest_dir=dest)
- except MethodRefError as exc:
- typer.secho(str(exc), fg=typer.colors.RED, err=True)
- raise typer.Exit(1) from exc
+ fetched = fetch_method_package(ref=method_ref, dest_dir=dest)
typer.secho(
f"Fetched {fetched.full_address}{f'@{method_ref.tag}' if method_ref.tag else ''} at commit {fetched.commit_sha}",
@@ -173,6 +169,7 @@ def resolve_method_target(
*,
pipe_override: str | None = None,
library_dirs: list[str] | None = None,
+ raise_ref_errors: bool = False,
) -> tuple[str, list[str], InstalledMethod]:
"""Resolve a method name, address, URL, or local path to (pipe_code, library_dirs, method).
@@ -186,16 +183,28 @@ def resolve_method_target(
method_name: The installed method name, method reference, or local path to resolve.
pipe_override: Optional pipe code override (takes precedence over main_pipe).
library_dirs: Additional directories to search for methods.
+ raise_ref_errors: When True, a method-reference failure propagates as its typed
+ ``MethodRefError`` instead of being rendered and turned into ``typer.Exit`` —
+ the agent CLI commands pass True so their structured error envelope (not
+ plain red text) reports the failure.
Returns:
A tuple of (pipe_code, library_dirs, installed_method) for execution.
Raises:
typer.Exit: On resolution errors with user-friendly messages.
+ MethodRefError: On a method-reference failure, when ``raise_ref_errors`` is True.
"""
method: InstalledMethod
if looks_like_method_ref(method_name):
- method = resolve_method_from_ref(method_name)
+ if raise_ref_errors:
+ method = resolve_method_from_ref(method_name)
+ else:
+ try:
+ method = resolve_method_from_ref(method_name)
+ except MethodRefError as exc:
+ typer.secho(str(exc), fg=typer.colors.RED, err=True)
+ raise typer.Exit(1) from exc
elif is_local_path(method_name):
method = resolve_method_from_path(method_name)
else:
@@ -236,6 +245,25 @@ def resolve_method_target(
return pipe_code, library_dirs, method
+def method_output_base_dir(*, method: InstalledMethod) -> Path:
+ """Base directory anchoring a method target's default output paths.
+
+ An installed or local-path method anchors its outputs in its own directory. A fetched
+ method's directory is an ephemeral clone deleted at process exit, so anchoring outputs
+ there would silently lose them — a fetched method anchors in the caller's current
+ working directory instead, where a run's results survive the process.
+
+ Args:
+ method: The resolved method target.
+
+ Returns:
+ The directory default output paths should be built under.
+ """
+ if method.provenance is None:
+ return method.path
+ return Path.cwd()
+
+
def resolve_pipe_from_exports(
pipe_code: str,
) -> list[str] | None:
diff --git a/pipelex/methods/structures_check.py b/pipelex/methods/structures_check.py
index 66b5a2539..e44fa8b63 100644
--- a/pipelex/methods/structures_check.py
+++ b/pipelex/methods/structures_check.py
@@ -4,18 +4,25 @@ The rule (execution locus decides): `.mthds` content is data — always acceptab
`.py` executes in the network-blocked sandbox — acceptable on sandbox-hosted deployments.
`structures/*.py` is imported into the runner's own process, so a fetched package that
declares `StructuredContent` subclasses is refused, loudly, with an error that names the
-rule. The discrimination is what the AST declares — the same AST pre-check the library
-loader's import gate performs — never mere `.py` presence: PipeFunc-only Python is
-supported.
+rule. The discrimination is what the AST declares — never mere `.py` presence: PipeFunc-only
+Python is supported.
+
+The scan is alias-aware: a base written as `StructuredContent`, imported under another name
+(`from ... import StructuredContent as SC`), or reached as an attribute
+(`module.StructuredContent`, whatever the module was imported as) is caught. It remains a
+static pre-check, and honestly so: dynamic tricks (rebinding through assignments, metaclass
+construction, `type(...)` calls) are out of its scope — its job is that straightforward
+declarations and straightforward aliasing cannot defeat the refusal. A subclass of a caught
+class in the same package is covered transitively, because the file declaring the base is
+itself refused and refusal applies to the whole package.
"""
+import ast
from pathlib import Path
from pydantic import BaseModel, ConfigDict
from pipelex.methods.exceptions import MethodStructuresRefusedError
-from pipelex.tools.typing.exceptions import ModuleFileError
-from pipelex.tools.typing.module_inspector import find_class_names_in_file
STRUCTURE_BASE_CLASS_NAME = "StructuredContent"
@@ -24,6 +31,39 @@ STRUCTURES_REFUSAL_RULE = "hosted execution accepts MTHDS concepts and sandboxed
_SKIPPED_DIR_NAMES = {".git", "__pycache__"}
+def _collect_base_name_bindings(*, tree: ast.Module) -> set[str]:
+ """Names bound to `StructuredContent` in this module: the literal name plus `import ... as` aliases."""
+ bindings = {STRUCTURE_BASE_CLASS_NAME}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom):
+ for import_alias in node.names:
+ if import_alias.name == STRUCTURE_BASE_CLASS_NAME and import_alias.asname:
+ bindings.add(import_alias.asname)
+ return bindings
+
+
+def _structured_content_class_names(*, tree: ast.Module) -> list[str]:
+ """Class names in *tree* whose declared bases resolve to `StructuredContent`.
+
+ A base matches when it is a name bound to `StructuredContent` (directly or via an
+ `import ... as` alias) or an attribute access ending in `.StructuredContent` — the
+ attribute form always spells the real class name, whatever the module alias.
+ """
+ bindings = _collect_base_name_bindings(tree=tree)
+ class_names: list[str] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.ClassDef):
+ continue
+ for base in node.bases:
+ if isinstance(base, ast.Name) and base.id in bindings:
+ class_names.append(node.name)
+ break
+ if isinstance(base, ast.Attribute) and base.attr == STRUCTURE_BASE_CLASS_NAME:
+ class_names.append(node.name)
+ break
+ return class_names
+
+
class StructuredContentViolation(BaseModel):
"""One `.py` file inside a package that declares `StructuredContent` subclasses."""
@@ -36,8 +76,10 @@ class StructuredContentViolation(BaseModel):
def scan_structured_content_classes(*, package_dir: Path) -> list[StructuredContentViolation]:
"""AST-scan a package directory for `.py` files declaring `StructuredContent` subclasses.
- Files that cannot be parsed are skipped: the loader's own AST import gate skips them
- the same way, so they cannot smuggle a structure class into the process.
+ Alias-aware: bases reached through `from ... import StructuredContent as SC` or through
+ an attribute access (`module.StructuredContent`) are caught alongside the literal name.
+ Files that cannot be parsed are skipped: an unparseable file cannot be imported either,
+ so it cannot smuggle a structure class into the process.
Args:
package_dir: The package directory to scan.
@@ -51,10 +93,13 @@ def scan_structured_content_classes(*, package_dir: Path) -> list[StructuredCont
if any(part in _SKIPPED_DIR_NAMES for part in relative.parts):
continue
try:
- class_names = find_class_names_in_file(py_file, base_class_names=[STRUCTURE_BASE_CLASS_NAME])
- except ModuleFileError:
- # Unparseable or otherwise unloadable file: the loader's AST gate would skip it too.
+ source = py_file.read_text(encoding="utf-8")
+ tree = ast.parse(source, filename=str(py_file))
+ except (OSError, SyntaxError, ValueError):
+ # Unparseable or unreadable file: it cannot be imported either, so it cannot
+ # smuggle a structure class into the process.
continue
+ class_names = _structured_content_class_names(tree=tree)
if class_names:
violations.append(StructuredContentViolation(relative_path=relative.as_posix(), class_names=class_names))
return violations
diff --git a/tests/unit/pipelex/cli/agent_cli/test_agent_method_ref_errors.py b/tests/unit/pipelex/cli/agent_cli/test_agent_method_ref_errors.py
new file mode 100644
index 000000000..c1f1a1786
--- /dev/null
+++ b/tests/unit/pipelex/cli/agent_cli/test_agent_method_ref_errors.py
@@ -0,0 +1,80 @@
+"""Unit tests: agent CLI method commands report method-reference failures through the structured error envelope."""
+
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING, Any, cast
+
+import pytest
+import typer
+from mthds.package.exceptions import VCSFetchError
+
+from pipelex.cli.agent_cli.commands.agent_output import CliOutputFormat, set_agent_cli_error_format
+from pipelex.cli.agent_cli.commands.inputs.method_cmd import inputs_method_cmd
+from pipelex.cli.agent_cli.commands.run.method_cmd import run_method_cmd
+from pipelex.cli.agent_cli.commands.validate.method_cmd import validate_method_cmd
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from pytest_mock import MockerFixture
+
+BROKEN_REF = "github.com/test/broken-repo"
+
+
+def _parse_single_json_error(stderr_text: str) -> dict[str, Any]:
+ """Parse the one JSON error object printed on stderr."""
+ start = stderr_text.index("{")
+ parsed, _ = json.JSONDecoder().raw_decode(stderr_text, start)
+ assert isinstance(parsed, dict)
+ return cast("dict[str, Any]", parsed)
+
+
+class TestAgentMethodRefErrors:
+ """A fetch failure surfaces as the structured JSON envelope, never unstructured Typer text."""
+
+ def _mock_failing_clone(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ mocker.patch("pipelex.methods.fetching.clone_default_branch", side_effect=VCSFetchError("connection refused"))
+ mocker.patch("pipelex.cli.method_resolver.tempfile.mkdtemp", return_value=str(tmp_path / "dest"))
+
+ def test_run_method_fetch_failure_emits_json_envelope(self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
+ """`run method <ref>` with a failing fetch exits 1 with a MethodFetchError JSON envelope on stderr."""
+ self._mock_failing_clone(mocker, tmp_path)
+
+ with pytest.raises(typer.Exit) as exc_info:
+ run_method_cmd(ctx=mocker.MagicMock(), name=BROKEN_REF, error_format=CliOutputFormat.JSON)
+
+ assert exc_info.value.exit_code == 1
+ error_obj = _parse_single_json_error(capsys.readouterr().err)
+ assert error_obj["error"] is True
+ assert error_obj["error_type"] == "MethodFetchError"
+ assert "connection refused" in error_obj["message"]
+
+ def test_validate_method_fetch_failure_emits_json_envelope(
+ self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ """`validate method <ref>` with a failing fetch is a no-verdict condition: exit 2, structured envelope."""
+ self._mock_failing_clone(mocker, tmp_path)
+
+ with pytest.raises(typer.Exit) as exc_info:
+ validate_method_cmd(name=BROKEN_REF, output_format=CliOutputFormat.JSON)
+
+ assert exc_info.value.exit_code == 2
+ error_obj = _parse_single_json_error(capsys.readouterr().err)
+ assert error_obj["error"] is True
+ assert error_obj["error_type"] == "MethodFetchError"
+ assert "connection refused" in error_obj["message"]
+
+ def test_inputs_method_fetch_failure_emits_json_envelope(self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
+ """`inputs method <ref>` with a failing fetch exits 1 with the structured envelope (JSON is its error default)."""
+ set_agent_cli_error_format(CliOutputFormat.JSON)
+ self._mock_failing_clone(mocker, tmp_path)
+
+ with pytest.raises(typer.Exit) as exc_info:
+ inputs_method_cmd(name=BROKEN_REF)
+
+ assert exc_info.value.exit_code == 1
+ error_obj = _parse_single_json_error(capsys.readouterr().err)
+ assert error_obj["error"] is True
+ assert error_obj["error_type"] == "MethodFetchError"
+ assert "connection refused" in error_obj["message"]
diff --git a/tests/unit/pipelex/cli/agent_cli/test_agent_run_method_output_location.py b/tests/unit/pipelex/cli/agent_cli/test_agent_run_method_output_location.py
new file mode 100644
index 000000000..0314e0b4a
--- /dev/null
+++ b/tests/unit/pipelex/cli/agent_cli/test_agent_run_method_output_location.py
@@ -0,0 +1,71 @@
+"""Unit tests: agent CLI `run method` anchors a fetched method's outputs outside the ephemeral clone."""
+
+from __future__ import annotations
+
+import io
+from pathlib import Path
+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 pytest_mock import MockerFixture
+
+RUN_METHOD_MODULE = "pipelex.cli.agent_cli.commands.run.method_cmd"
+
+
+class TestAgentRunMethodOutputLocation:
+ """A fetched method's clone is deleted at process exit — its run outputs must land somewhere durable."""
+
+ @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, fetched: bool) -> 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
+ method_mock.provenance = mocker.MagicMock() if fetched else None
+ 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={"answer": "42"}))
+
+ def _make_ctx(self, mocker: MockerFixture) -> Any:
+ ctx = mocker.MagicMock()
+ ctx.obj = {"runner": RunnerType.PIPELEX}
+ return ctx
+
+ @pytest.mark.usefixtures("tty_stdin")
+ def test_fetched_method_overrides_output_dir_to_cwd(self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
+ """A fetched method (provenance set) re-anchors run outputs under the caller's CWD, not the clone."""
+ clone_dir = tmp_path / "mthds_remote_clone"
+ run_core_mock = self._patch_method_run(mocker, method_dir=clone_dir, fetched=True)
+
+ run_method_cmd(ctx=self._make_ctx(mocker), name="github.com/test/remote-method", output_format=CliOutputFormat.JSON)
+
+ capsys.readouterr()
+ override = run_core_mock.call_args.kwargs["output_dir_override"]
+ assert override == Path.cwd() / "results"
+ assert not override.is_relative_to(clone_dir)
+
+ @pytest.mark.usefixtures("tty_stdin")
+ def test_installed_method_keeps_bundle_adjacent_default(self, mocker: MockerFixture, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
+ """An installed method (no provenance) keeps the bundle-adjacent default: no override is passed."""
+ run_core_mock = self._patch_method_run(mocker, method_dir=tmp_path, fetched=False)
+
+ run_method_cmd(ctx=self._make_ctx(mocker), name="my-method", output_format=CliOutputFormat.JSON)
+
+ capsys.readouterr()
+ assert run_core_mock.call_args.kwargs["output_dir_override"] is None
diff --git a/tests/unit/pipelex/cli/test_build_runner_method_materialization.py b/tests/unit/pipelex/cli/test_build_runner_method_materialization.py
new file mode 100644
index 000000000..c06aae5a7
--- /dev/null
+++ b/tests/unit/pipelex/cli/test_build_runner_method_materialization.py
@@ -0,0 +1,78 @@
+"""Unit tests: `build runner method` on a fetched target embeds only paths that survive process exit."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from pipelex.cli.commands.build.runner.method_cmd import build_runner_method_cmd
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from pytest_mock import MockerFixture
+
+RUNNER_METHOD_MODULE = "pipelex.cli.commands.build.runner.method_cmd"
+
+
+class TestBuildRunnerMethodMaterialization:
+ """The generated runner embeds its library dir — for a fetched target that dir must outlive the clone."""
+
+ def _patch_method(self, mocker: MockerFixture, *, method_dir: Path, fetched: bool) -> Any:
+ """Create a real method package at *method_dir*, patch resolution; return the execute_prepare_runner mock."""
+ method_dir.mkdir(parents=True, exist_ok=True)
+ bundle_file = method_dir / "core.mthds"
+ bundle_file.write_text("# placeholder", encoding="utf-8")
+
+ method_mock = mocker.MagicMock()
+ method_mock.name = "remote_method"
+ method_mock.path = method_dir
+ method_mock.mthds_files = [bundle_file]
+ method_mock.provenance = mocker.MagicMock() if fetched else None
+ mocker.patch(
+ f"{RUNNER_METHOD_MODULE}.resolve_method_target",
+ return_value=("my_pipe", [str(method_dir)], method_mock),
+ )
+ return mocker.patch(f"{RUNNER_METHOD_MODULE}.execute_prepare_runner")
+
+ def test_fetched_method_is_materialized_beside_the_script(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ """A fetched target's package is copied beside the generated runner, and only the copy is referenced."""
+ clone_dir = tmp_path / "mthds_remote_clone"
+ prepare_mock = self._patch_method(mocker, method_dir=clone_dir, fetched=True)
+ output_file = tmp_path / "out" / "run_my_pipe.py"
+
+ build_runner_method_cmd(name="github.com/test/remote-method", output_path=str(output_file))
+
+ materialized_dir = output_file.parent / "remote_method"
+ assert (materialized_dir / "core.mthds").is_file()
+ kwargs = prepare_mock.call_args.kwargs
+ assert kwargs["bundle_path"] == materialized_dir / "core.mthds"
+ assert kwargs["library_dirs"] == [materialized_dir]
+ assert not kwargs["bundle_path"].is_relative_to(clone_dir)
+ assert not kwargs["library_dirs"][0].is_relative_to(clone_dir)
+
+ def test_fetched_materialization_excludes_git_metadata(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ """The clone's .git directory is not copied into the materialized package."""
+ clone_dir = tmp_path / "mthds_remote_clone"
+ self._patch_method(mocker, method_dir=clone_dir, fetched=True)
+ (clone_dir / ".git").mkdir()
+ (clone_dir / ".git" / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")
+ output_file = tmp_path / "out" / "run_my_pipe.py"
+
+ build_runner_method_cmd(name="github.com/test/remote-method", output_path=str(output_file))
+
+ materialized_dir = output_file.parent / "remote_method"
+ assert (materialized_dir / "core.mthds").is_file()
+ assert not (materialized_dir / ".git").exists()
+
+ def test_installed_method_is_not_copied(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ """An installed method (no provenance) is referenced in place — no copy is made."""
+ method_dir = tmp_path / "installed-method"
+ prepare_mock = self._patch_method(mocker, method_dir=method_dir, fetched=False)
+ output_file = tmp_path / "out" / "run_my_pipe.py"
+
+ build_runner_method_cmd(name="my-method", output_path=str(output_file))
+
+ kwargs = prepare_mock.call_args.kwargs
+ assert kwargs["bundle_path"] == method_dir / "core.mthds"
+ assert kwargs["library_dirs"] == [method_dir]
+ assert not (output_file.parent / "remote_method").exists()
diff --git a/tests/unit/pipelex/cli/test_method_resolver.py b/tests/unit/pipelex/cli/test_method_resolver.py
index 27327673e..80ba32fc7 100644
--- a/tests/unit/pipelex/cli/test_method_resolver.py
+++ b/tests/unit/pipelex/cli/test_method_resolver.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from pathlib import Path
from typing import TYPE_CHECKING
import pytest
@@ -11,14 +12,14 @@ from mthds.package.exceptions import VCSFetchError
from pipelex.cli.method_resolver import (
is_local_path,
+ method_output_base_dir,
resolve_method_from_path,
resolve_method_from_ref,
resolve_method_target,
)
+from pipelex.methods.exceptions import MethodFetchError, MethodPackageNotFoundError, MethodRefParseError
if TYPE_CHECKING:
- from pathlib import Path
-
from pytest_mock import MockerFixture
FAKE_SHA = "0123456789abcdef0123456789abcdef01234567"
@@ -85,29 +86,69 @@ class TestResolveMethodTarget:
assert method.name == "remote_method"
def test_resolve_method_from_ref_clone_failure(self, mocker: MockerFixture, tmp_path: Path) -> None:
- """A VCSFetchError during clone raises typer.Exit."""
+ """A VCSFetchError during clone propagates as the typed MethodFetchError — presentation is the caller's concern."""
mocker.patch("pipelex.methods.fetching.clone_default_branch", side_effect=VCSFetchError("connection refused"))
mocker.patch("pipelex.cli.method_resolver.tempfile.mkdtemp", return_value=str(tmp_path / "dest"))
- with pytest.raises(typer.Exit):
+ with pytest.raises(MethodFetchError):
resolve_method_from_ref("github.com/test/broken-repo")
def test_resolve_method_from_ref_no_matching_package(self, mocker: MockerFixture, tmp_path: Path) -> None:
- """A clone whose packages match no requested address raises typer.Exit."""
+ """A clone whose packages match no requested address propagates the typed not-found error."""
self._mock_clone(mocker, tmp_path / "cloned")
- with pytest.raises(typer.Exit):
+ with pytest.raises(MethodPackageNotFoundError):
resolve_method_from_ref("github.com/test/other-address")
def test_resolve_method_from_ref_parse_error(self, mocker: MockerFixture) -> None:
- """An invalid reference raises typer.Exit without attempting a clone."""
+ """An invalid reference propagates the typed parse error without attempting a clone."""
clone_spy = mocker.patch("pipelex.methods.fetching.clone_default_branch")
- with pytest.raises(typer.Exit):
+ with pytest.raises(MethodRefParseError):
resolve_method_from_ref("github.com/only-owner")
assert clone_spy.call_count == 0
+ def test_resolve_method_target_renders_ref_error_as_exit(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ """The human-CLI default renders a reference failure and exits — no raw traceback."""
+ mocker.patch("pipelex.methods.fetching.clone_default_branch", side_effect=VCSFetchError("connection refused"))
+ mocker.patch("pipelex.cli.method_resolver.tempfile.mkdtemp", return_value=str(tmp_path / "dest"))
+ secho_spy = mocker.patch("pipelex.cli.method_resolver.typer.secho")
+
+ with pytest.raises(typer.Exit) as exc_info:
+ resolve_method_target("github.com/test/broken-repo")
+
+ assert exc_info.value.exit_code == 1
+ rendered = [call for call in secho_spy.call_args_list if "connection refused" in str(call)]
+ assert len(rendered) == 1
+
+ def test_resolve_method_target_propagates_ref_error_when_requested(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ """With raise_ref_errors=True the typed error propagates, so the agent CLI can shape its envelope."""
+ mocker.patch("pipelex.methods.fetching.clone_default_branch", side_effect=VCSFetchError("connection refused"))
+ mocker.patch("pipelex.cli.method_resolver.tempfile.mkdtemp", return_value=str(tmp_path / "dest"))
+
+ with pytest.raises(MethodFetchError):
+ resolve_method_target("github.com/test/broken-repo", raise_ref_errors=True)
+
+ def test_method_output_base_dir_local_method_anchors_in_method_dir(self, tmp_path: Path) -> None:
+ """An installed or local-path method (no provenance) anchors default outputs in its own directory."""
+ method_dir = tmp_path / "local-method"
+ _write_method_package(method_dir)
+ method = resolve_method_from_path(str(method_dir))
+
+ assert method_output_base_dir(method=method) == method_dir
+
+ def test_method_output_base_dir_fetched_method_anchors_in_cwd(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ """A fetched method's clone dies at process exit, so default outputs anchor in the caller's CWD instead."""
+ clone_dir = tmp_path / "cloned"
+ self._mock_clone(mocker, clone_dir)
+ method = resolve_method_from_ref("github.com/test/remote-method")
+
+ base_dir = method_output_base_dir(method=method)
+
+ assert base_dir == Path.cwd()
+ assert not base_dir.is_relative_to(clone_dir)
+
def test_resolve_method_from_ref_warns_on_structures(self, mocker: MockerFixture, tmp_path: Path) -> None:
"""Hosted-parity: a fetched package declaring StructuredContent subclasses resolves locally with a warning."""
dest_dir = tmp_path / "cloned"
diff --git a/tests/unit/pipelex/cli/test_run_method_output_location.py b/tests/unit/pipelex/cli/test_run_method_output_location.py
new file mode 100644
index 000000000..618478476
--- /dev/null
+++ b/tests/unit/pipelex/cli/test_run_method_output_location.py
@@ -0,0 +1,56 @@
+"""Unit tests: main CLI `run method` anchors a fetched method's default outputs outside the ephemeral clone."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from pipelex.cli.commands.run.method_cmd import run_method_cmd
+
+if TYPE_CHECKING:
+ from pytest_mock import MockerFixture
+
+RUN_METHOD_MODULE = "pipelex.cli.commands.run.method_cmd"
+
+
+class TestRunMethodOutputLocation:
+ """A fetched method's clone is deleted at process exit — default outputs must land somewhere durable."""
+
+ def _patch_method_run(self, mocker: MockerFixture, *, method_dir: Path, fetched: bool) -> Any:
+ """Patch method resolution and execution; return the execute_run mock."""
+ method_mock = mocker.MagicMock()
+ method_mock.path = method_dir
+ method_mock.provenance = mocker.MagicMock() if fetched else None
+ mocker.patch(
+ f"{RUN_METHOD_MODULE}.resolve_method_target",
+ return_value=("my_pipe", [str(method_dir)], method_mock),
+ )
+ return mocker.patch(f"{RUN_METHOD_MODULE}.execute_run")
+
+ def test_fetched_method_defaults_output_to_cwd_results(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ """A fetched method (provenance set) defaults --output-dir to results/ under the caller's CWD, not the clone."""
+ clone_dir = tmp_path / "mthds_remote_clone"
+ execute_run_mock = self._patch_method_run(mocker, method_dir=clone_dir, fetched=True)
+
+ run_method_cmd(name="github.com/test/remote-method")
+
+ output_dir = Path(execute_run_mock.call_args.kwargs["output_dir"])
+ assert output_dir == Path.cwd() / "results"
+ assert not output_dir.is_relative_to(clone_dir)
+
+ def test_installed_method_defaults_output_to_method_results(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ """An installed method (no provenance) keeps the results/ default inside its own directory."""
+ execute_run_mock = self._patch_method_run(mocker, method_dir=tmp_path, fetched=False)
+
+ run_method_cmd(name="my-method")
+
+ assert execute_run_mock.call_args.kwargs["output_dir"] == str(tmp_path / "results")
+
+ def test_explicit_output_dir_wins_for_fetched_method(self, mocker: MockerFixture, tmp_path: Path) -> None:
+ """An explicit --output-dir is honored verbatim, fetched or not."""
+ clone_dir = tmp_path / "mthds_remote_clone"
+ execute_run_mock = self._patch_method_run(mocker, method_dir=clone_dir, fetched=True)
+
+ run_method_cmd(name="github.com/test/remote-method", output_dir="custom_out")
+
+ assert execute_run_mock.call_args.kwargs["output_dir"] == "custom_out"
diff --git a/tests/unit/pipelex/methods/test_structures_check.py b/tests/unit/pipelex/methods/test_structures_check.py
index ee2b12580..a6cab4a58 100644
--- a/tests/unit/pipelex/methods/test_structures_check.py
+++ b/tests/unit/pipelex/methods/test_structures_check.py
@@ -42,6 +42,30 @@ class Helper:
pass
"""
+ALIASED_IMPORT_MODULE = """\
+from pipelex.core.stuffs.structured_content import StructuredContent as SC
+
+
+class Invoice(SC):
+ total: float
+"""
+
+ATTRIBUTE_BASE_MODULE = """\
+import pipelex.core.stuffs.structured_content as sc_module
+
+
+class Invoice(sc_module.StructuredContent):
+ total: float
+"""
+
+UNRELATED_ALIAS_MODULE = """\
+from some.other.module import OtherBase as SC
+
+
+class Helper(SC):
+ pass
+"""
+
class TestStructuresCheck:
"""Tests for the AST-based StructuredContent refusal — never gating on mere .py presence."""
@@ -77,6 +101,32 @@ class TestStructuresCheck:
assert "Invoice" in message
assert "MTHDS concepts" in message
+ def test_from_import_alias_is_detected(self, tmp_path: Path) -> None:
+ """`from ... import StructuredContent as SC` does not bypass the refusal."""
+ (tmp_path / "aliased.py").write_text(ALIASED_IMPORT_MODULE, encoding="utf-8")
+
+ violations = scan_structured_content_classes(package_dir=tmp_path)
+
+ assert len(violations) == 1
+ assert violations[0].relative_path == "aliased.py"
+ assert violations[0].class_names == ["Invoice"]
+
+ def test_attribute_base_is_detected(self, tmp_path: Path) -> None:
+ """A base reached as `module.StructuredContent` (whatever the module alias) is caught."""
+ (tmp_path / "attribute_base.py").write_text(ATTRIBUTE_BASE_MODULE, encoding="utf-8")
+
+ violations = scan_structured_content_classes(package_dir=tmp_path)
+
+ assert len(violations) == 1
+ assert violations[0].relative_path == "attribute_base.py"
+ assert violations[0].class_names == ["Invoice"]
+
+ def test_unrelated_alias_is_not_flagged(self, tmp_path: Path) -> None:
+ """An alias named `SC` bound to some other class is not a violation — bindings are tracked, not guessed."""
+ (tmp_path / "unrelated.py").write_text(UNRELATED_ALIAS_MODULE, encoding="utf-8")
+
+ assert scan_structured_content_classes(package_dir=tmp_path) == []
+
def test_unparseable_python_is_skipped(self, tmp_path: Path) -> None:
"""A syntactically invalid .py cannot smuggle a structure class: skipped, like the loader's gate."""
(tmp_path / "broken.py").write_text("def broken(:\n", encoding="utf-8")